Skip to content

Instantly share code, notes, and snippets.

@FrenchBen
Created April 4, 2018 21:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrenchBen/3a73d2cf6f7b6d2211ca8bb103948958 to your computer and use it in GitHub Desktop.
Save FrenchBen/3a73d2cf6f7b6d2211ca8bb103948958 to your computer and use it in GitHub Desktop.
Encrypting/Decrypting a string using golang, from https://stackoverflow.com/a/14944339
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"crypto/x509"
"encoding/pem"
"flag"
"io/ioutil"
"log"
)
// Command-line flags
var (
keyFile = flag.String("key", "id_rsa", "Path to RSA private key")
inFile = flag.String("in", "in.txt", "Path to input file")
outFile = flag.String("out", "out.txt", "Path to output file")
label = flag.String("label", "", "Label to use (filename by default)")
decrypt = flag.Bool("decrypt", false, "Decrypt instead of encrypting")
)
func main() {
flag.Parse()
// Read the input file
in, err := ioutil.ReadFile(*inFile)
if err != nil {
log.Fatalf("input file: %s", err)
}
// Read the private key
pemData, err := ioutil.ReadFile(*keyFile)
if err != nil {
log.Fatalf("read key file: %s", err)
}
// Extract the PEM-encoded data block
block, _ := pem.Decode(pemData)
if block == nil {
log.Fatalf("bad key data: %s", "not PEM-encoded")
}
if got, want := block.Type, "RSA PRIVATE KEY"; got != want {
log.Fatalf("unknown key type %q, want %q", got, want)
}
// Decode the RSA private key
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Fatalf("bad private key: %s", err)
}
var out []byte
if *decrypt {
if *label == "" {
*label = *outFile
}
// Decrypt the data
out, err = rsa.DecryptOAEP(sha1.New(), rand.Reader, priv, in, []byte(*label))
if err != nil {
log.Fatalf("decrypt: %s", err)
}
} else {
if *label == "" {
*label = *inFile
}
out, err = rsa.EncryptOAEP(sha1.New(), rand.Reader, &priv.PublicKey, in, []byte(*label))
if err != nil {
log.Fatalf("encrypt: %s", err)
}
}
// Write data to output file
if err := ioutil.WriteFile(*outFile, out, 0600); err != nil {
log.Fatalf("write output: %s", err)
}
}
@holid019
Copy link

where should we input the rsa public key? I can only run the encrypting, but not the decrypting, any tips? thanks

@FrenchBen
Copy link
Author

@holid019 - a little late to reply, but the decryption is done with the private key, which is passed here: https://gist.github.com/FrenchBen/3a73d2cf6f7b6d2211ca8bb103948958#file-encryptor-go-L16

The public key, used in the encryption, is derived from the private key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment