Created
January 4, 2014 01:12
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
@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)
}
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
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)