68

公開鍵でテキストを暗号化し、秘密鍵を持つユーザーがテキストを復号化できるようにするには、2つの鍵(秘密鍵と公開鍵)を生成する必要があります。

モジュールCryptoで可能ですか?

4

9 に答える 9

25

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

于 2014-01-02T05:59:14.850 に答える
17

次のコードは機能しますが、私はプロの暗号学者ではないため、ここにいくつかのコメントが役立ちます。

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 は既にパディングを行っているようです。

于 2014-01-21T15:26:05.830 に答える
12

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();  
});
于 2012-01-12T17:08:53.443 に答える
5

これが役立つかどうかはわかりませんが、これらの線に沿って何かをしたいとも思っていました。これが私が思いついたものです:

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を使用しているため、重要なポイントはどのアルゴリズムが使用されているかだと思います。キーの先頭は、キーのバージョンを識別するのに役立ち、暗号化されているかどうかに関する情報も含まれています。お役に立てれば!

于 2020-10-13T17:29:33.460 に答える
0

私はそれを使用していませんが、これは役に立つかもしれません:

http://ox.no/posts/diffie-hellman-support-in-node-js

これに関するドキュメントが大幅に不足しています(私が見つけることができる例はありません)。

于 2011-12-15T17:21:56.963 に答える