php小編蘋果為您帶來Golang提取ECDH私鑰的簡潔攻略。 ECDH是一種非對稱加密演算法,用於在兩個通訊方之間建立安全的金鑰交換。在Golang中,擷取ECDH私鑰是實現安全通訊的重要步驟之一。本文將介紹如何使用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 提取 ECDH 私鑰的詳細內容。更多資訊請關注PHP中文網其他相關文章!