Skip to content

Instantly share code, notes, and snippets.

@marete
Last active December 20, 2015 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marete/6189760 to your computer and use it in GitHub Desktop.
Save marete/6189760 to your computer and use it in GitHub Desktop.
Use Go's openpgp implementation to symmetrically encrypt a file, possibly with compression.
symmetric-encrypt
package main
import (
"code.google.com/p/go.crypto/openpgp"
"code.google.com/p/go.crypto/openpgp/packet"
"flag"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"time"
)
var pp = "ithai5Phieth"
var input string
var z int
var algo string
var algo_ packet.CompressionAlgo
func init() {
flag.StringVar(&input, "input", "", "Input file (- means Stdin)")
flag.StringVar(&algo, "compress-algo", "zip",
"Compression Algorithm - none, zip or zlib")
flag.IntVar(&z, "z", packet.DefaultCompression,
"Compression level")
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU() * 2)
flag.Parse()
switch algo {
case "none":
algo_ = packet.CompressionNone
case "zip":
algo_ = packet.CompressionZIP
case "zlib":
algo_ = packet.CompressionZLIB
default:
fmt.Fprintf(os.Stderr,
"ERROR: Unknown compression algo %s\n", algo)
os.Exit(1)
}
var r io.Reader
var filenameHint string
var modtimeHint time.Time
if input == "" || input == "-" {
r = os.Stdin
} else {
file, err := os.Open(input)
if err != nil {
fmt.Fprintln(os.Stderr, "ERROR:", err)
os.Exit(1)
}
defer file.Close()
filenameHint = filepath.Base(input)
fi, err := os.Stat(input)
if err != nil {
fmt.Fprintln(os.Stderr, "ERROR:", err)
os.Exit(1)
}
modtimeHint = fi.ModTime()
r = file
}
hints := &openpgp.FileHints{IsBinary: true, FileName: filenameHint, ModTime: modtimeHint}
var config *packet.Config
if algo_ != packet.CompressionNone {
config = &packet.Config{DefaultCompressionAlgo: algo_,
CompressionConfig: &packet.CompressionConfig{z}}
}
w := os.Stdout
plaintext, err := openpgp.SymmetricallyEncrypt(w, []byte(pp), hints,
config)
if err != nil {
fmt.Fprintln(os.Stderr, "ERROR:", err)
os.Exit(1)
}
_, err = io.Copy(plaintext, r)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR:", err)
os.Exit(1)
}
plaintext.Close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment