-
-
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
This file contains 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 ( | |
"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