node v0.12の公開鍵暗号API

Added APIs for RSA public/private key encryption/decryption.

Node v0.12.0 (Stable)

cryptoモジュールに公開鍵暗号APIが追加されたそうなので試す。

鍵生成

$ openssl genrsa 2048 > test_private.key
$ openssl rsa -pubout < test_private.key > test_public.key

コード

var crypto = require('crypto');
var fs = require('fs');

// 公開鍵、暗号化用
var publicKey = fs.readFileSync('test_public.key', {encoding: 'ascii'});

// 秘密鍵、復号用
var privateKey = fs.readFileSync('test_private.key', {encoding: 'ascii'});

// 暗号化するメッセージ
var message = "hogehoge-fugafuga-nyan_nyan_nyan";

// 暗号化
var encrypted = crypto.publicEncrypt(publicKey, new Buffer(message, 'ascii'));
console.log('encrypted: ' + crypted.toString('hex') + '\n');

// 復号
var decrypted = crypto.privateDecrypt(privateKey, encrypted);
console.log('decrypted: ' + decrypted.toString('hex') + '\n');
console.log('decrypted string: ' + decrypted.toString('ascii') + '\n');

実行結果

encrypted: 25cab4c78f44b55bb4911163f0863254c80941a63ecaf9ef49229a3db50080f93bea59c72aee45c59490112cae15ef5ab3d4feefb34bf181b718a2691bf7dbfca14e80aec76bb32cdb7e772499b913b3b2aa8c147cfe0982092efb5561b4952d974b964882559f65e43c6eeed32f8e34321b8804b65cfd29b3edc786bc48a0903ebd5daf3706ce94854340936ca9d6a835362c3388658a63d48ff561ae07570df0c2ebd938324b60609c663e38f5b6ec80df8cd129f63511e11a9fd24e7e78dbc799c40adf418bfa9d44ace7666d59ac1c2c4a1e3963d316adb5dfa982e5a808259080afe12599b18175da6ffd74454eecb48b8bd066a211c6a21fd5517514c7

decrypted: 686f6765686f67652d66756761667567612d6e79616e5f6e79616e5f6e79616e

decrypted string: hogehoge-fugafuga-nyan_nyan_nyan

簡単すぎる