如何解压缩Go中ECDH P256曲线上的单个X9.62压缩点?

时间:2017-09-18 16:04:37

标签: go cryptography elliptic-curve ecdh

Golang的椭圆曲线库可以在给定具有X和Y值(未压缩坐标)的公共坐标的情况下导出密钥。

但是,当给定的点是具有给定y位的X9.62压缩形式的单个值时,我该如何解压缩它?

OpenSSL使用此方法处理此方案:

https://github.com/openssl/openssl/blob/4e9b720e90ec154c9708139e96ec0ff8e2796c82/include/openssl/ec.h#L494

似乎也有一个类似的问题涉及数学,但不是Go的最佳实践,特别是:

https://crypto.stackexchange.com/questions/8914/ecdsa-compressed-public-key-point-back-to-uncompressed-public-key-point

如何在Go中完成?

1 个答案:

答案 0 :(得分:6)

据我所知,Go标准库(或“x”包)中没有点解压缩功能,所以你必须自己做(或者找一个现有的实现)。

实施并不太难,但有几点需要注意。

基本上,您需要将X值插入曲线方程Y2 = X3 + aX + b,然后使用符号位确定所需的两个根中的哪一个。棘手的一点是要记住所有这些都需要以模块的字段填充为模。

我发现Go’s big integer package有时可能有点奇怪,因为它使用了可变值,但它确实有modular square root function,这使我们的事情变得更加容易。曲线参数在crypto/elliptic package中可用,但您需要知道这些曲线的a参数始终为-3

假设您在[]byte中将压缩点设为0x02(带有前导0x03compressed_bytes),following should work。这是一个非常直接的方程实现,用注释和许多命名变量分解,试图解释发生了什么。查看CurveParams.IsOnCurve的来源,以获得更高效(更短)的实施。直到模块化的平方根才基本相同。

compressed_bytes := //...

// Split the sign byte from the rest
sign_byte := uint(compressed_bytes[0])
x_bytes := compressed_bytes[1:]

// Convert to big Int.
x := new(big.Int).SetBytes(x_bytes)

// We use 3 a couple of times
three := big.NewInt(3)

// and we need the curve params for P256
c := elliptic.P256().Params()

// The equation is y^2 = x^3 - 3x + b
// First, x^3, mod P
x_cubed := new(big.Int).Exp(x, three, c.P)

// Next, 3x, mod P
three_X := new(big.Int).Mul(x, three)
three_X.Mod(three_X, c.P)

// x^3 - 3x ...
y_squared := new(big.Int).Sub(x_cubed, three_X)

// ... + b mod P
y_squared.Add(y_squared, c.B)
y_squared.Mod(y_squared, c.P)

// Now we need to find the square root mod P.
// This is where Go's big int library redeems itself.
y := new(big.Int).ModSqrt(y_squared, c.P)
if y == nil {
    // If this happens then you're dealing with an invalid point.
    // Panic, return an error, whatever you want here.
}

// Finally, check if you have the correct root by comparing
// the low bit with the low bit of the sign byte. If it’s not
// the same you want -y mod P instead of y.
if y.Bit(0) != sign_byte & 1 {
    y.Neg(y)
    y.Mod(y, c.P)
}

// Now your y coordinate is in y, for all your ScalarMult needs.