Skip to content

Instantly share code, notes, and snippets.

@jyap808
Created January 4, 2014 01:12
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save jyap808/8250124 to your computer and use it in GitHub Desktop.
Save jyap808/8250124 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))
}
@bobvanluijt
Copy link

Update, packages should be:

"golang.org/x/crypto/openpgp"
"golang.org/x/crypto/openpgp/armor"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment