To use asymmetric encryption, load your public and private keys using crypto.NewKeyFromArmored(pubkey) and crypto.NewPrivateKeyFromArmored(privkey, passphrase).
Basic Encryption/Decryption
Use pgp.Encryption().Recipient(publicKey).New() to encrypt for a specific recipient. Use pgp.Decryption().DecryptionKey(privateKey).New() to decrypt. Always call decHandle.ClearPrivateParams() after use to clear sensitive data from memory.
Signing and Encryption
To sign a message while encrypting, chain .SigningKey(privateKey) to the encryption handle. During decryption, use .VerificationKey(publicKey) on the decryption handle and check decrypted.SignatureError() to verify the signature.
Multiple Recipients and Hidden Recipients
- Multiple Recipients: Use
crypto.NewKeyRing(key) to create a keyring and recipients.AddKey(key) to add more, then pass the keyring to .Recipients(recipients). - Hidden Recipients: Use
.HiddenRecipient(key) to prevent the recipient's fingerprint from being visible in the key packet. When decrypting, you must call .DisableIntendedRecipients() on the decryption handle to avoid signature errors caused by the missing intended recipient list.
// Encrypt and sign plaintext message from alice to bob
encHandle, err := pgp.Encryption().
Recipient(bobKeyPub).
SigningKey(aliceKeyPriv).
New()
pgpMessage, err := encHandle.Encrypt([]byte("my message"))
armored, err := pgpMessage.ArmorBytes()
// Decrypt armored encrypted message using the private key and obtain the plaintext
decHandle, err := pgp.Decryption().
DecryptionKey(bobKeyPriv).
VerificationKey(aliceKeyPub).
New()
decrypted, err := decHandle.Decrypt(armored, crypto.Armor)
if sigErr := decrypted.SignatureError(); sigErr != nil {
// Signature verification failed
}
myMessage := decrypted.Bytes()
encHandle.ClearPrivateParams()
decHandle.ClearPrivateParams()