椭圆(JS lib)和Bouncy Castle(.NET lib)之间的公钥派生不一致

时间:2018-07-12 10:51:23

标签: cryptography bouncycastle elliptic-curve

我已经使用elliptic库(JavaScript)生成了两个密钥对(secp256k1)。当我使用生成的私钥并使用Bouncy Castle库(.NET)派生公钥时,我并不总是获得与从椭圆形相同的公钥。

在下面的示例中,案例1在两个库中产生了相同的公共密钥,而案例2产生了不同的公共密钥。

Case 1:
Private Key: 1bd86a6ed359cbbd342ac1b35be5ac112ee71210a542ff86c2f5d304d1f6bd72
Public Key (elliptic): 0478eec03dac240f1be5bd816b8a5a7ca0d41126a524abf0ae217200570e5ba34c47b96d57510779f443af3e9e7e434354bac205c210e2f96ca875d77976a436e6
Public Key (Bouncy Castle): 0478eec03dac240f1be5bd816b8a5a7ca0d41126a524abf0ae217200570e5ba34c47b96d57510779f443af3e9e7e434354bac205c210e2f96ca875d77976a436e6

Case 2:
Private Key: 9ede1270644719a1ab2557c11b99a0d5e00b2e7f1e4d073b794bf5424868be06
Public Key (elliptic): 0462097811d7af637460e86046a1ef7996f784aa6c1ca78adf2c19e49d9ce7a47cb9542164c2ee96b9a866efded0ab88042d155006adf8095b8b07157f0924f437
Public Key (Bouncy Castle): 048e22b2295c14505800610d6cc0cd8169852da500e2199281bacbdd5944a67da018d7f8864d1ce43c593eefd06b2f97f20dadb9452085989a26bbc87cf918a614

值得一提的是,如果我使用Bouncy Castle生成密钥对,那么在使用椭圆派生时,它们总是会产生相同的公共密钥。

我不确定这是库问题还是我的使用方式,但是代码(JS)非常简单:

var EC = require('elliptic').ec;
var ec = new EC('secp256k1');

// Generate a key pair
var keyPair = ec.genKeyPair();
var privateKey = keyPair.getPrivate('hex');
var publicKey = keyPair.getPublic('hex');

// Calculate public key from private key
ec.keyFromPrivate(somePrivateKey, 'hex').getPublic('hex');

这是在F#中使用Bouncy Castle lib的代码:

let curve = SecNamedCurves.GetByName("secp256k1")
let domain = ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H)

// Generate a key pair
let secureRandom = SecureRandom()
let keyGenParams = ECKeyGenerationParameters(domain, secureRandom)

let gen = ECKeyPairGenerator()
gen.Init(keyGenParams)

let keyPair = gen.GenerateKeyPair()

let privateKey = (keyPair.Private :?> ECPrivateKeyParameters).D.ToByteArray()
let publicKey = (keyPair.Public :?> ECPublicKeyParameters).Q.GetEncoded()

// Calculate public key from private key
curve.G.Multiply(BigInteger privateKey).GetEncoded()

任何人都可以提供对此问题的任何见解,或者推荐我可以使用的其他JS库吗?

1 个答案:

答案 0 :(得分:1)

如@ dave_thompson_085所建议,问题出在BigInteger实例化中。 BC BigInteger构造函数,采用单个byte[]参数威胁第一个字节的第一位作为符号。在第二种情况下,私钥以9e开头,而BC创建负数。将私钥转换为公钥的正确C#代码:

byte[] data = Org.BouncyCastle.Utilities.Encoders.Hex.Decode("9ede1270644719a1ab2557c11b99a0d5e00b2e7f1e4d073b794bf5424868be06");

var curve = Org.BouncyCastle.Asn1.Sec.SecNamedCurves.GetByName("secp256k1");
var privateKey = new Org.BouncyCastle.Math.BigInteger(1, data); // 1 means positive number
var publicKey = curve.G.Multiply(privateKey);
byte[] pubKeyEncoded = publicKey.GetEncoded(false);

Console.WriteLine(Org.BouncyCastle.Utilities.Encoders.Hex.ToHexString(pubKeyEncoded));