公開鍵でテキストを暗号化し、秘密鍵を持つユーザーがテキストを復号化できるようにするには、2つの鍵(秘密鍵と公開鍵)を生成する必要があります。
モジュールCryptoで可能ですか?
公開鍵でテキストを暗号化し、秘密鍵を持つユーザーがテキストを復号化できるようにするには、2つの鍵(秘密鍵と公開鍵)を生成する必要があります。
モジュールCryptoで可能ですか?
npm の crypto モジュールを使用して KeyPair を生成します。
var crypto = require('crypto');
var prime_length = 60;
var diffHell = crypto.createDiffieHellman(prime_length);
diffHell.generateKeys('base64');
console.log("Public Key : " ,diffHell.getPublicKey('base64'));
console.log("Private Key : " ,diffHell.getPrivateKey('base64'));
console.log("Public Key : " ,diffHell.getPublicKey('hex'));
console.log("Private Key : " ,diffHell.getPrivateKey('hex'));
上記はスニペットの例です。詳細なチェックアウト ドキュメントを知るにはhttp://nodejs.org/api/crypto.html
次のコードは機能しますが、私はプロの暗号学者ではないため、ここにいくつかのコメントが役立ちます。
crypto の代わりに ursa RSA モジュールを使用しました。
同様のデータが AES などのパスなしで直接暗号化された場合、これを破るのは簡単かもしれないと心配しています。コメントください...
var ursa = require('ursa');
var fs = require('fs');
// create a pair of keys (a private key contains both keys...)
var keys = ursa.generatePrivateKey();
console.log('keys:', keys);
// reconstitute the private key from a base64 encoding
var privPem = keys.toPrivatePem('base64');
console.log('privPem:', privPem);
var priv = ursa.createPrivateKey(privPem, '', 'base64');
// make a public key, to be used for encryption
var pubPem = keys.toPublicPem('base64');
console.log('pubPem:', pubPem);
var pub = ursa.createPublicKey(pubPem, 'base64');
// encrypt, with the public key, then decrypt with the private
var data = new Buffer('hello world');
console.log('data:', data);
var enc = pub.encrypt(data);
console.log('enc:', enc);
var unenc = priv.decrypt(enc);
console.log('unenc:', unenc);
さらなる調査http://en.wikipedia.org/w/index.php?title=RSA_%28cryptosystem%29§ion=12#Attacks_against_plain_RSAの後、 ursa は既にパディングを行っているようです。
OpenSSL から必要なものを取得する方法を知っている場合は、Node.js を使用して OpenSSL を実行することは完全に合理的だと思いますchild_process
。
var cp = require('child_process')
, assert = require('assert')
;
var privateKey, publicKey;
publicKey = '';
cp.exec('openssl genrsa 2048', function(err, stdout, stderr) {
assert.ok(!err);
privateKey = stdout;
console.log(privateKey);
makepub = cp.spawn('openssl', ['rsa', '-pubout']);
makepub.on('exit', function(code) {
assert.equal(code, 0);
console.log(publicKey);
});
makepub.stdout.on('data', function(data) {
publicKey += data;
});
makepub.stdout.setEncoding('ascii');
makepub.stdin.write(privateKey);
makepub.stdin.end();
});
これが役立つかどうかはわかりませんが、これらの線に沿って何かをしたいとも思っていました。これが私が思いついたものです:
Nelson Owalo の回答で述べたように、次のように暗号ライブラリを使用できます。
//import the methods
const { generateKeyPair, createSign, createVerify } = require("crypto");
//generate the key pair
generateKeyPair(
"rsa",
{
modulusLength: 2048, // It holds a number. It is the key size in bits and is applicable for RSA, and DSA algorithm only.
publicKeyEncoding: {
type: "pkcs1", //Note the type is pkcs1 not spki
format: "pem",
},
privateKeyEncoding: {
type: "pkcs1", //Note again the type is set to pkcs1
format: "pem",
//cipher: "aes-256-cbc", //Optional
//passphrase: "", //Optional
},
},
(err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
if (err) console.log("Error!", err);
console.log({
publicKey,
privateKey,
});//Print the keys to the console or save them to a file.
/*
* At this point you will have to pem files,
* the public key which will start with
* '-----BEGIN RSA PUBLIC KEY-----\n' +
* and the private key which will start with
* '-----BEGIN RSA PRIVATE KEY-----\n' +
*/
//Verify it works by signing some data and verifying it.
//Create some sample data that we want to sign
const verifiableData = "this need to be verified";
// The signature method takes the data we want to sign, the
// hashing algorithm, and the padding scheme, and generates
// a signature in the form of bytes
const signature = require("crypto").sign("sha256", Buffer.from(verifiableData),
{
key: privateKey,
padding: require("crypto").constants.RSA_PKCS1_PSS_PADDING,
});
//Convert the signature to base64 for storage.
console.log(signature.toString("base64"));
// To verify the data, we provide the same hashing algorithm and
// padding scheme we provided to generate the signature, along
// with the signature itself, the data that we want to
// verify against the signature, and the public key
const isVerified = require("crypto").verify(
"sha256",
Buffer.from(verifiableData),
{
key: publicKey,
padding: require("crypto").constants.RSA_PKCS1_PSS_PADDING,
},
Buffer.from(signature.toString("base64"), "base64")
);
// isVerified should be `true` if the signature is valid
console.log("signature verified: ", isVerified);
}
);
古いバージョンのpemはpkcs8ではなくpkcs1を使用しているため、重要なポイントはどのアルゴリズムが使用されているかだと思います。キーの先頭は、キーのバージョンを識別するのに役立ち、暗号化されているかどうかに関する情報も含まれています。お役に立てれば!
私はそれを使用していませんが、これは役に立つかもしれません:
http://ox.no/posts/diffie-hellman-support-in-node-js
これに関するドキュメントが大幅に不足しています(私が見つけることができる例はありません)。