我正在使用加密库,遇到了一个问题:我需要将PublicKey
类型转换为byte[]
,因为它可以用私钥完成:
privkey.D.Bytes()
如何解决这个问题?
ecdsa.PrivateKey
是一个结构体:
type PrivateKey struct {
PublicKey
D *big.Int
}
因此,privkey.D.Bytes()
返回D
大整数的字节数。
同样,ecdsa.PublicKey
:
type PublicKey struct {
elliptic.Curve
X, Y *big.Int
}
您可以对pubkey.X
和pubkey.Y
字段执行相同的操作。这些将为您提供 2 个单独的字节片。如果您需要将它们合并为一个,则需要提出某种"格式",例如使用 4 个字节对第一个切片的长度(pubkey.X.Bytes()
的结果(进行编码,然后是第一个切片,然后是第二个切片的长度(再次是 4 个字节(,以及第二个切片本身。
最好为此使用elliptic.Marshal()
函数:
func Marshal(curve Curve, x, y *big.Int) []byte
Marshal 将点转换为 ANSI X9.62 第 4.3.6 节中指定的未压缩形式。
使用它的示例:
var pubkey *ecdsa.PublicKey = // ...
data := elliptic.Marshal(pubkey, pubkey.X, pubkey.Y)
对于可爱的人们寻找解决方案,当涉及到ed25519/crypto
时。我砰
func getPrivateKey() ed25519.PrivateKey {
// TODO You fill in this one
}
func main() {
prvKey := getPrivateKey() // Get the private key
pubKey := prvKey.Public().(ed25519.PublicKey)
if !ok {
log.Errorf("Could not assert the public key to ed25519 public key")
}
pubKeyBytes := []byte(pubKey)
}