获取 Golang 中的 ECDH 私钥
时间:2024-02-02
浏览:228
作者:佚名
在Golang实战开发的过程中,我们经常会遇到一些这样那样的问题,然后要卡好半天,等问题解决了才发现原来一些细节知识点还是没有掌握好。今天golang学习网就整理分享《获取 Golang 中的 ECDH 私钥》,聊聊,希望可以帮助到正在努力赚钱的你。
问题内容
我知道ECDH私钥是公钥的超集。任务是提取私钥ecdh。
生成PublicKey的方法如下:
import (
"crypto/ecdh"
"crypto/rand"
"crypto/ecdsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
)
func main() {
alicePrivateKey, err := ecdh.P256().GenerateKey(rand.Reader)
alicePublicKey, err := MarshalECDHPublicKey(alicePrivateKey.PublicKey())
if err != nil {
fmt.Errorf("failed to marshal public key into PKIX format")
}
fmt.Printf("alicePubK => %s\n", alicePublicKey)
clientECDSAPubKey, err := UnmarshalECDSAPublicKey(alicePublicKey)
if err != nil {
panic(err)
}
println(clientECDSAPubKey)
println("no error")
}
func MarshalECDHPublicKey(pk *ecdh.PublicKey) (string, error) {
ecdhSKBytes, err := x509.MarshalPKIXPublicKey(pk)
if err != nil {
return "", fmt.Errorf("failed to marshal public key into PKIX format")
}
ecdhSKPEMBlock := pem.EncodeToMemory(
&pem.Block{
Type: "PUBLIC KEY",
Bytes: ecdhSKBytes,
},
)
return base64.StdEncoding.EncodeToString(ecdhSKPEMBlock), nil
}正确答案
我假设您想以 pem 格式提取 ecdh 私钥,就像使用公钥一样。从公钥中提取私钥是不可能的(计算上不可行)。我已经为您实现了 UnmarshalECDSAPublicKey 函数(最好重命名为 MarshalECDHPrivateKey)
// MarshalPKCS8PrivateKey converts a private key to PKCS #8, ASN.1 DER form.
//
// The following key types are currently supported: *rsa.PrivateKey,
// *ecdsa.PrivateKey, ed25519.PrivateKey (not a pointer), and *ecdh.PrivateKey.
// Unsupported key types result in an error.
//
// This kind of key is commonly encoded in PEM blocks of type "PRIVATE KEY".
func UnmarshalECDSAPublicKey(alicePrivateKey *ecdh.PrivateKey) (string, error) {
ecdhSKBytes, err := x509.MarshalPKCS8PrivateKey(alicePrivateKey)
if err != nil {
return "", fmt.Errorf("failed to marshal private key into PKIX format")
}
ecdhSKPEMBlock := pem.EncodeToMemory(
&pem.Block{
Type: "PRIVATE KEY",
Bytes: ecdhSKBytes,
},
)
return string(ecdhSKPEMBlock), nil
}
正如其他人在有关 MarshalECDHPublicKey 函数的评论中指出的那样,您不需要使用 base64.StdEncoding.EncodeToString(ecdhSKPEMBlock) 再次编码,因为 pem.EncodeToMemory 会做同样的事情,您只需将其转换为字符串即可。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.20
11.20
11.20
11.20
热门专题
