Skip to content

Instantly share code, notes, and snippets.

@hoox
Last active August 26, 2019 17:28
Show Gist options
  • Save hoox/f1353dac02dd5f0d8be6 to your computer and use it in GitHub Desktop.
Save hoox/f1353dac02dd5f0d8be6 to your computer and use it in GitHub Desktop.
PFX RSA PKCS12 Encrypt Decrypt Data Example
package main
import (
"crypto/rand"
"crypto/rsa"
"fmt"
"io/ioutil"
"golang.org/x/crypto/pkcs12"
)
func main() {
privateKeyFile := "my-private-key-file.pfx"
privateKeyFilePass := "my-private-key-pass"
dataToEncrypt := []byte("my encrypted data")
// PRIVATE KEY
data, err := ioutil.ReadFile(privateKeyFile)
if err != nil {
fmt.Printf("Error reading private key file: %s", err)
return
}
priv, _, err := pkcs12.Decode(data, privateKeyFilePass)
if err != nil {
fmt.Printf("Error decoding private key file: %s", err)
return
}
if err := priv.(*rsa.PrivateKey).Validate(); err != nil {
fmt.Printf("Error validating private key file: %s", err)
return
}
// ENCRYPT
encryptedData, err := rsa.EncryptPKCS1v15(rand.Reader, &priv.(*rsa.PrivateKey).PublicKey, dataToEncrypt)
if err != nil {
fmt.Printf("Error encrypting data: %s", err)
return
}
// DECRYPT
decryptedData, err := rsa.DecryptPKCS1v15(rand.Reader, priv.(*rsa.PrivateKey), encryptedData)
if err != nil {
fmt.Printf("Error decrypting data: %s", err)
return
}
fmt.Printf("Decrypted data: %s\n", string(decryptedData))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment