-
-
Save itsbalamurali/eed3d04039a1adaca52170fcd94b4f2c to your computer and use it in GitHub Desktop.
golang gpg/openpgp encryption/decryption example
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 ( | |
| "log" | |
| "bytes" | |
| "code.google.com/p/go.crypto/openpgp" | |
| "encoding/base64" | |
| "io/ioutil" | |
| "os" | |
| ) | |
| # create gpg keys with | |
| # $ gpg --gen-key | |
| # ensure you correct paths and passphrase | |
| const mysecretstring = "this is so very secret!" | |
| const secretKeyring = "/Users/stuart-warren/.gnupg/secring.gpg" | |
| const publicKeyring = "/Users/stuart-warren/.gnupg/pubring.gpg" | |
| const passphrase = "1234" | |
| func main() { | |
| log.Printf("Secret: ", mysecretstring) | |
| log.Printf("Secret Keyring: ", secretKeyring) | |
| log.Printf("Public Keyring: ", publicKeyring) | |
| log.Printf("Passphrase: ", passphrase) | |
| keyringFileBuffer, _ := os.Open(publicKeyring) | |
| defer keyringFileBuffer.Close() | |
| entitylist, _ := openpgp.ReadKeyRing(keyringFileBuffer) | |
| buf := new(bytes.Buffer) | |
| w, _ := openpgp.Encrypt(buf, entitylist, nil, nil, nil) | |
| w.Write([]byte(mysecretstring)) | |
| bytesp, _ := ioutil.ReadAll(buf) | |
| encstr := base64.StdEncoding.EncodeToString(bytesp) | |
| log.Printf("Encrypted Secret: ", encstr) | |
| var entity2 *openpgp.Entity | |
| var entitylist2 openpgp.EntityList | |
| keyringFileBuffer2, _ := os.Open(secretKeyring) | |
| defer keyringFileBuffer2.Close() | |
| entitylist2, _ = openpgp.ReadKeyRing(keyringFileBuffer2) | |
| entity2 = entitylist2[0] | |
| passphrasebyte := []byte(passphrase) | |
| log.Printf("Decrypting private key using passphrase") | |
| entity2.PrivateKey.Decrypt(passphrasebyte) | |
| for _, subkey := range entity2.Subkeys { | |
| subkey.PrivateKey.Decrypt(passphrasebyte) | |
| } | |
| log.Printf("Finished decrypting private key using passphrase") | |
| dec, _ := base64.StdEncoding.DecodeString(encstr) | |
| md, _ := openpgp.ReadMessage(bytes.NewBuffer(dec), entitylist2, nil, nil) | |
| bytess, _ := ioutil.ReadAll(md.UnverifiedBody) | |
| decstr := string(bytess) | |
| log.Printf("Decrypted Secret: ", decstr) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment