Node.js 使用ECDH和nodejs加密解密机密

Node.js 使用ECDH和nodejs加密解密机密,node.js,encryption,cryptography,Node.js,Encryption,Cryptography,这是nodejs文档示例: const crypto = require('crypto'); const alice = crypto.createECDH('secp256k1'); const bob = crypto.createECDH('secp256k1'); // Note: This is a shortcut way to specify one of Alice's previous private // keys. It would be unwise to use s

这是nodejs文档示例:

const crypto = require('crypto');
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');

// Note: This is a shortcut way to specify one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
  crypto.createHash('sha256').update('alice', 'utf8').digest()
);

// Bob uses a newly generated cryptographically strong
// pseudorandom key pair bob.generateKeys();

const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

// alice_secret and bob_secret should be the same shared secret value
console.log(alice_secret === bob_secret);

我不明白这个秘密是从哪里来的。假设我想解密来自Bob的消息
foo bar
(用Alice公钥加密)。我有Alice的私钥和公钥,以及Bob的加密消息如何解密包含所有这些信息的消息?

上述步骤构成ECDH密钥协议协议,以在Alice和Bob之间建立共享密钥(对称密钥),然后他们可以使用该共享密钥进行安全通信

密钥alice_secret是使用alice的私钥和Bob在alice端的公钥计算的。
密钥bob_secret是使用bob的私钥和Alice在bob端的公钥计算的

两个键将相等。现在,Alice和Bob有一个共享的秘密(Alice_secret=Bob_secret),他们可以用它来加密/解密消息

请注意,此处仅交换公钥,中间的人无法获得Alice或Bob的私钥

理想情况下,共享密钥应通过使用密钥派生函数转换为适用于AES等算法的适当对称密钥。提及

伪代码

-Bob使用Bob_secret和AES进行加密:

  var crypto = require('crypto'),
  algo = 'aes-256-ctr',
  var cipher = crypto.createCipher(algo,bob_secret)
  var encrypted = cipher.update("foo-bar",'utf8','hex')
  encrypted += cipher.final('hex');
-爱丽丝解密:

 var decipher = crypto.createDecipher(algo,alice_secret)
 var decrypted = decipher.update(encrypted,'hex','utf8')
 decrypted += decipher.final('utf8');

更新了答案。请注意,如果此代码用于具有相同对称密钥的多条消息(
bob\u secret
alice\u secret
),则此代码是完全不安全的。CTR模式是一种流媒体模式,当IV+键组合使用两次时(键和IV是从传递的
xxx_secret
中确定派生的),它会显示一个多时间段。最好使用
crypto.createCipheriv
@NicolasDelValle为每个加密随机生成一个12字节的IV,因为
alice_secret
bob_secret
都是伪随机的,所以您可以使用一个简单的散列来根据散列函数获得特定的长度。SHA-256应该可以正常工作。@NicolasDelValle不,我的意思是每一方都应该通过一个散列函数来运行他们计算的秘密,以获得实际的密钥。@NicolasDelValle答案中有一个讨论密钥派生的链接。