Skip to content

Instantly share code, notes, and snippets.

@d4z3x
Forked from apokalyptik/decrypt.go
Created June 5, 2020 00:43
Show Gist options
  • Save d4z3x/4a2d10e9557a7c672ab6e057a40becef to your computer and use it in GitHub Desktop.
Save d4z3x/4a2d10e9557a7c672ab6e057a40becef to your computer and use it in GitHub Desktop.
Go RSA private key decryption example. Compatible with data encrypted via http://us3.php.net/openssl_public_encrypt
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"flag"
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
var PKPW string
flag.StringVar(&PKPW, "pp", PKPW, "private key passphrase")
flag.Parse()
// Read the standard input
in, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("input file: %s", err)
}
pemData, err := ioutil.ReadFile("pri.key")
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)
}
if PKPW != "" {
if decBlock, err := x509.DecryptPEMBlock(block, []byte(PKPW)); err != nil {
log.Fatalf("error decrypting pem file: %s", err.Error())
} else {
block.Bytes = decBlock
}
}
// Decode the RSA private key
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
log.Fatalf("bad private key: %s", err)
}
// Decrypt the data
out, err := rsa.DecryptPKCS1v15(rand.Reader, priv, in)
if err != nil {
log.Fatalf("decrypt: %s", err)
}
// Write data to output file
fmt.Fprint(os.Stdout, string(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment