With PGP, we normally sign with a private key of the sender, and use the public key of the recipient. We can also use it in the "pgp -c" or "pgp --symmetric" mode to encrypt with only a symmetric cipher. In this mode we ask for a passphrase to generate the key.
PGP in Go |
Code
The coding is [from here]:
package main import ( "bytes" "errors" "fmt" "io/ioutil" "os" "golang.org/x/crypto/openpgp" "golang.org/x/crypto/openpgp/armor" "golang.org/x/crypto/openpgp/packet" ) func main() { s:="hello world" p:="hello world" s = string(os.Args[1]) p = string(os.Args[2]) plaintext := []byte(s) password := []byte(p) packetConfig := &packet.Config{ DefaultCipher: packet.CipherAES256, } encrypted, _ := Encrypt(plaintext, password, packetConfig) fmt.Println("Message: ", s) fmt.Println("Password: ", p) fmt.Println("\nEncrypted:\n\n", string(encrypted)) decrypted, _ := Decrypt(encrypted, password, packetConfig) fmt.Println("\n\nDecrypted:", string(decrypted)) } func Encrypt(plaintext []byte, password []byte, packetConfig *packet.Config) (ciphertext []byte, err error) { encbuf := bytes.NewBuffer(nil) w, _ := armor.Encode(encbuf, "PGP MESSAGE", nil) pt, _ := openpgp.SymmetricallyEncrypt(w, password, nil, packetConfig) _, err = pt.Write(plaintext) if err != nil { return } pt.Close() w.Close() ciphertext = encbuf.Bytes() return } func Decrypt(ciphertext []byte, password []byte, packetConfig *packet.Config) (plaintext []byte, err error) { decbuf := bytes.NewBuffer(ciphertext) armorBlock, _ := armor.Decode(decbuf) failed := false prompt := func(keys []openpgp.Key, symmetric bool) ([]byte, error) { if failed { return nil, errors.New("decryption failed") } failed = true return password, nil } md, err := openpgp.ReadMessage(armorBlock.Body, nil, prompt, packetConfig) if err != nil { return } plaintext, err = ioutil.ReadAll(md.UnverifiedBody) if err != nil { return } return }
A sample run is:
-----BEGIN PGP MESSAGE----- wy4ECQMI702U/65IOE9gpkJvs7+uwZDJxWFcECcTu6/oBNBaBw4SuEW5mzx9Cxgu 0uAB5CeF3hCjroJ/9H719YeLxsjhbSPg3+Dv4TQl4ILiSsWvW+DE4uLOm3LgueCx 4NrkeW0yaNQw/tobiT6PnsCTEOIiZnJ74bH1AA== =czPe -----END PGP MESSAGE----- Decrypted: hello
If we save the PGP message to a file name 1.asc, and then run "gpg -d 1.asc", we can enter the password and read the message.
GPG equivilant
We can also use GPG to do the same. First we create the message:
> type 1.txt So did NSA put a backdoor?
Next we create an amor file with the encrypted message:
> gpg -c -a 1.txt
We can then list the encrypted file:
> type 1.txt.asc -----BEGIN PGP MESSAGE----- Version: GnuPG v2 jA0EBwMCz1yj3ME13Nae0lQBp7yb3F1PpsC6J0Qe/3UXsh0P4HIxKzslPdXROGrh VtpKmtVUiLhEFFpHzdgEaFwCLBM/EP86dN7YVJBztoP/trM+Ib5j4buNv+EdGCra X5YPeJc= =BAb2 -----END PGP MESSAGE-----
Finally we decrypt with:
> pgp -d 1.txt.asc So did NSA put a backdoor?