gpt4 book ai didi

node.js - 在 Node.js 中使用加密自定义私钥

转载 作者:太空宇宙 更新时间:2023-11-03 21:57:53 25 4
gpt4 key购买 nike

来自:https://nodejs.org/api/crypto.html#crypto_class_ecdh

const alice_key = alice.generateKeys();

会生成一个随机的私钥和对应的公钥。

但我想设置自己的私钥:e8f32e723decf...

如果我使用:

alice.setPrivateKey("e8f32e723decf");

对象 alice_key 不受影响,所以稍后:

const bob_secret = bob.computeSecret(alice_key, 'hex', 'hex');

将会是错误的。有没有办法做这样的事情:

const alice_key = alice.generateKeys("e8f32e723decf");

最佳答案

首先,我认为您的十六进制字符串缺少前导 0,因此它应该是 0e8f32e723decf

然后取决于你的node.js版本,ECDH.setPrivateKey()的实现从5.1更改为5.2

<小时/>

node.js 5.0


const crypto = require('crypto');

// this is just to generate a private/public key pair
const warmup = crypto.createECDH('secp521r1');
warmup.generateKeys();
const warmup_private_key = warmup.getPrivateKey();
const warmup_public_key = warmup.getPublicKey();

// convert it to hex string to match the example
// you would store these strings somewhere I guess
private_key = warmup_private_key.toString('hex');
public_key = warmup_public_key.toString('hex');

// now let's create the ciphers
const alice = crypto.createECDH('secp521r1');
const bob = crypto.createECDH('secp521r1');


----------


// Bob gets created keys
bob.generateKeys();

// Generate Alice's keys - that's really annoying since you will override it
alice.generateKeys();
// now set the keys:
alice.setPrivateKey(private_key, "hex");
alice.setPublicKey(public_key, "hex");

// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob.getPublicKey());
const bob_secret = bob.computeSecret(alice.getPublicKey());

console.log("alice's shared secret: " + alice_secret.toString('hex') + "\n");
console.log("bob's shared secret: " + bob_secret.toString('hex') + "\n");

console.log('shared secrets match: ' + alice_secret.equals(bob_secret));
<小时/>

node.js >= 5.2


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

alice.setPrivateKey('0e8f32e723decf', 'hex');

const alice_secret = alice.computeSecret(bob.getPublicKey());
const bob_secret = bob.computeSecret(alice.getPublicKey());

console.log(alice_secret.equals(bob_secret));

关于node.js - 在 Node.js 中使用加密自定义私钥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35527939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com