使用ECDH和nodejsencryption解密秘密

这是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公钥encryption)。 我有爱丽丝的私钥和公钥,鲍勃的encryption信息,我怎么能解密这一切呢?

上述步骤构成了ECDH密钥协商协议,以在Alice和Bob之间build立共享秘密(对称密钥),随后它们可以用于安全地进行通信。

秘密密钥alice_secret使用Alice的私钥和Bob的公钥在Alice的末尾计算。
密钥bob_secret使用Bob的私钥和Alice的公钥在Bob的末尾计算。

两个键都是平等的。 现在,Alice和Bob有一个共享的秘密(alice_secret = bob_secret),可以用来隐藏/解密消息。

请注意,只有公钥在这里交换,中间人无法获得Alice或Bob的私钥。

共享密钥应理想地转换为适合AES等algorithm的适当对称密钥。 请参阅KDF

伪代码

– 使用bob_secret和AESencryption –

  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');