Created
June 6, 2021 02:16
-
-
Save vniche/cf777d728f3e035c56f6ce9dc9a1f3f8 to your computer and use it in GitHub Desktop.
How to decrypt a EC password encrypted private key in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
... | |
privateKeyBytes, err := ioutil.ReadFile("/path/to/my/private.key") | |
if err != nil { | |
log.Fatalf("failed to read private key file: %v", err) | |
} | |
block, _ := pem.Decode(privateKeyBytes) | |
if err != nil { | |
log.Fatalf("failed to decode private key to PEM: %v", err) | |
} | |
fmt.Printf("private key PEM type: %s\n", block.Type) | |
decryptedPrivateKeyBytes, err := x509.DecryptPEMBlock(block, []byte("mysupersecretpassword")) | |
if err != nil { | |
log.Fatalf("failed to decrypt private key: %v", err) | |
} | |
ecdsaPrivateKey, err := x509.ParseECPrivateKey(block.Bytes) | |
if err != nil { | |
log.Fatalf("failed to parse PEM block EC private key: %v", err) | |
} | |
privateKeyDERBytes, err := x509.MarshalECPrivateKey(ecdsaPrivateKey) | |
if err != nil { | |
log.Fatalf("failed to marshal EC private key to DER: %v", err) | |
} | |
keyBlock := &pem.Block{ | |
Type: "EC PRIVATE KEY", | |
Bytes: privateKeyDERBytes, | |
} | |
privateKeyBytes = pem.EncodeToMemory(keyBlock) | |
fmt.Printf("decoded private key %s\n", string(privateKeyBytes)) | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment