Home >Backend Development >Golang >How can I securely store and retrieve ECDSA private keys in Go?
Storing ECDSA Private Key in Go
When working with ECDSA key pairs in Go, the need arises to store the private key securely. While the elliptic.Marshal method provides encoding for the public key, there's no equivalent for the private key. This article explores how to save and load private keys in Go.
Encoding and Decoding
To store the private key, it's necessary to adopt a multi-step approach involving ECDSA key encryption, standard encoding, and a file format. The common combination involves using the ECDSA algorithm for key generation, X.509 for encoding, and the PEM (Privacy-Enhanced Mail) format for storage.
Code Example
The following code snippet demonstrates how to encode and decode ECDSA keys in Go:
import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "encoding/pem" "fmt" "reflect" ) func encode(privateKey *ecdsa.PrivateKey, publicKey *ecdsa.PublicKey) (string, string) { x509Encoded, _ := x509.MarshalECPrivateKey(privateKey) pemEncoded := pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: x509Encoded}) x509EncodedPub, _ := x509.MarshalPKIXPublicKey(publicKey) pemEncodedPub := pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: x509EncodedPub}) return string(pemEncoded), string(pemEncodedPub) } func decode(pemEncoded string, pemEncodedPub string) (*ecdsa.PrivateKey, *ecdsa.PublicKey) { block, _ := pem.Decode([]byte(pemEncoded)) x509Encoded := block.Bytes privateKey, _ := x509.ParseECPrivateKey(x509Encoded) blockPub, _ := pem.Decode([]byte(pemEncodedPub)) x509EncodedPub := blockPub.Bytes genericPublicKey, _ := x509.ParsePKIXPublicKey(x509EncodedPub) publicKey := genericPublicKey.(*ecdsa.PublicKey) return privateKey, publicKey } func test() { privateKey, _ := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) publicKey := &privateKey.PublicKey encPriv, encPub := encode(privateKey, publicKey) fmt.Println(encPriv) fmt.Println(encPub) priv2, pub2 := decode(encPriv, encPub) if !reflect.DeepEqual(privateKey, priv2) { fmt.Println("Private keys do not match.") } if !reflect.DeepEqual(publicKey, pub2) { fmt.Println("Public keys do not match.") } }
In the test function:
By utilizing the techniques outlined above, you can securely store and retrieve ECDSA private keys in Go, enabling the creation and management of digital signatures within your applications.
The above is the detailed content of How can I securely store and retrieve ECDSA private keys in Go?. For more information, please follow other related articles on the PHP Chinese website!