Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rjmcguire/e91c77f7e8e241329c0e9be34e25a09b to your computer and use it in GitHub Desktop.
Save rjmcguire/e91c77f7e8e241329c0e9be34e25a09b to your computer and use it in GitHub Desktop.
Symmetrically encrypting a string into ASCII armored GPG format and then Decrypting it in Golang
package main
import (
"bytes"
"code.google.com/p/go.crypto/openpgp"
"code.google.com/p/go.crypto/openpgp/armor"
"fmt"
"io/ioutil"
"log"
)
func main() {
encryptionPassphrase := []byte("golang")
encryptionText := "Hello world. Encryption and Decryption testing.\n"
encryptionType := "PGP SIGNATURE"
encbuf := bytes.NewBuffer(nil)
w, err := armor.Encode(encbuf, encryptionType, nil)
if err != nil {
log.Fatal(err)
}
plaintext, err := openpgp.SymmetricallyEncrypt(w, encryptionPassphrase, nil, nil)
if err != nil {
log.Fatal(err)
}
message := []byte(encryptionText)
_, err = plaintext.Write(message)
plaintext.Close()
w.Close()
fmt.Printf("Encrypted:\n%s\n", encbuf)
decbuf := bytes.NewBuffer([]byte(encbuf.String()))
result, err := armor.Decode(decbuf)
if err != nil {
log.Fatal(err)
}
md, err := openpgp.ReadMessage(result.Body, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
return encryptionPassphrase, nil
}, nil)
if err != nil {
log.Fatal(err)
}
bytes, err := ioutil.ReadAll(md.UnverifiedBody)
fmt.Printf("Decrypted:\n%s\n", string(bytes))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment