如何从 PublicKey 生成字节数组
How to generate bytes array from PublicKey
我在使用 crypto lib、运行 时遇到了一个问题:我需要将 PublicKey
类型转换为 byte[]
,因为它可以通过 private 完成键:
privkey.D.Bytes()
我该如何解决这个问题?
ecdsa.PrivateKey
是一个结构:
type PrivateKey struct {
PublicKey
D *big.Int
}
所以 privkey.D.Bytes()
returns 你 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 converts a point into the uncompressed form specified in section 4.3.6 of ANSI X9.62.
使用示例:
var pubkey *ecdsa.PublicKey = // ...
data := elliptic.Marshal(pubkey, pubkey.X, pubkey.Y)
对于在 ed25519/crypto
上寻找解决方案的可爱的人们。敲了将近3个小时的脑袋才弄明白:
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)
}
我在使用 crypto lib、运行 时遇到了一个问题:我需要将 PublicKey
类型转换为 byte[]
,因为它可以通过 private 完成键:
privkey.D.Bytes()
我该如何解决这个问题?
ecdsa.PrivateKey
是一个结构:
type PrivateKey struct {
PublicKey
D *big.Int
}
所以 privkey.D.Bytes()
returns 你 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 converts a point into the uncompressed form specified in section 4.3.6 of ANSI X9.62.
使用示例:
var pubkey *ecdsa.PublicKey = // ...
data := elliptic.Marshal(pubkey, pubkey.X, pubkey.Y)
对于在 ed25519/crypto
上寻找解决方案的可爱的人们。敲了将近3个小时的脑袋才弄明白:
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)
}