Created
April 27, 2016 17:10
-
-
Save artyom/a4c8375cf8b65eb3ac282e36a595cbbd to your computer and use it in GitHub Desktop.
Encrypt file using OpenPGP
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 ( | |
| "flag" | |
| "io" | |
| "log" | |
| "os" | |
| "github.com/artyom/autoflags" | |
| "golang.org/x/crypto/openpgp" | |
| "golang.org/x/crypto/openpgp/armor" | |
| "golang.org/x/crypto/openpgp/packet" | |
| ) | |
| func main() { | |
| params := struct { | |
| Ours string `flag:"ours,our pgp ascii-armored key"` | |
| Theirs string `flag:"theirs,theirs pgp ascii-armored public key"` | |
| File string `flag:"f,file to encrypt"` | |
| SaveTo string `flag:"w,file to write encrypted content to"` | |
| }{} | |
| autoflags.Define(¶ms) | |
| flag.Parse() | |
| if params.Ours == "" || params.Theirs == "" || params.File == "" || params.SaveTo == "" { | |
| flag.Usage() | |
| os.Exit(1) | |
| } | |
| if err := run(params.Ours, params.Theirs, params.File, params.SaveTo); err != nil { | |
| log.Fatal(err) | |
| } | |
| } | |
| func run(ours, theirs, file, saveto string) error { | |
| f, err := os.Open(file) | |
| if err != nil { | |
| return err | |
| } | |
| defer f.Close() | |
| signer, err := readEntity(ours) | |
| if err != nil { | |
| return err | |
| } | |
| recipient, err := readEntity(theirs) | |
| if err != nil { | |
| return err | |
| } | |
| dst, err := os.Create(saveto) | |
| if err != nil { | |
| return err | |
| } | |
| defer dst.Close() | |
| return encrypt([]*openpgp.Entity{recipient}, signer, f, dst) | |
| } | |
| func encrypt(recip []*openpgp.Entity, signer *openpgp.Entity, r io.Reader, w io.Writer) error { | |
| wc, err := openpgp.Encrypt(w, recip, signer, &openpgp.FileHints{IsBinary: true}, nil) | |
| if err != nil { | |
| return err | |
| } | |
| if _, err := io.Copy(wc, r); err != nil { | |
| return err | |
| } | |
| return wc.Close() | |
| } | |
| func readEntity(name string) (*openpgp.Entity, error) { | |
| f, err := os.Open(name) | |
| if err != nil { | |
| return nil, err | |
| } | |
| defer f.Close() | |
| block, err := armor.Decode(f) | |
| if err != nil { | |
| return nil, err | |
| } | |
| return openpgp.ReadEntity(packet.NewReader(block.Body)) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment