Home > Article > Backend Development > How to Store ECDSA Private Keys Securely in Go?
Storing ECDSA Private Keys in Go
When working with ECDSA key pairs in Go, the need often arises to store the private key securely. This guide will delve into techniques for effectively storing private keys in files on the user's computer.
Encoding and Decoding Private Keys
Go does not provide a direct mechanism for marshaling private keys using the elliptic.Marshal method. Instead, a multi-step encoding process is required:
Sample Code
The following Go code demonstrates the above process:
package main 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 main() { 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.") } }
By storing the PEM-encoded private key as a file, it can be retrieved and decoded later as needed. Remember to employ appropriate security measures to protect the file from unauthorized access or exposure.
The above is the detailed content of How to Store ECDSA Private Keys Securely in Go?. For more information, please follow other related articles on the PHP Chinese website!