-
-
Save Lestx/2cf5e9f196d9044e8b08ab0cad161bef 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 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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment