Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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))
}

how can we catch the error when we try to decrypt with wrong key?

I mean this one (https://gist.github.com/jyap808/8250124#file-encrypt_decrypt_gpg_armor-go-L44)

    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)
    }

@vodolaz095 Here is one solution for throwing an error if the passphrase is incorrect:

alreadyPrompted := false
md, err := openpgp.ReadMessage(encryptedText, nil, func(keys []openpgp.Key, symmetric bool) ([]byte, error) {
    // from openpgp docs: https://godoc.org/golang.org/x/crypto/openpgp#PromptFunction:
    // If the decrypted private key or given passphrase isn't correct, the function will be called again, forever.
    if alreadyPrompted {
        return nil, errors.New("Could not decrypt data using supplied passphrase")
    } else {
        alreadyPrompted = true
    }
    return key, nil
}, config)
if err != nil {
    log.Fatal("Could not decrypt data: ", err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment