Skip to content

Instantly share code, notes, and snippets.

@apokalyptik
Created September 1, 2014 22:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save apokalyptik/b2319a73c97c6a5af5fe to your computer and use it in GitHub Desktop.
Save apokalyptik/b2319a73c97c6a5af5fe to your computer and use it in GitHub Desktop.
Go RSA public key encryption example. Compatible with http://us3.php.net/manual/en/function.openssl-private-decrypt.php for decryption
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
// Read the standard input
in, err := ioutil.ReadAll(os.Stdin)
if err != nil {
log.Fatalf("input file: %s", err)
}
pemData, err := ioutil.ReadFile("pub.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, "CERTIFICATE"; got != want {
log.Fatalf("unknown key type %q, want %q", got, want)
}
// Decode the RSA public key
key, err := x509.ParseCertificate(block.Bytes)
if err != nil {
log.Fatalf("bad private key: %s", err)
}
pkey := key.PublicKey.(*rsa.PublicKey)
// Encrypt the data
out, err := rsa.EncryptPKCS1v15(rand.Reader, pkey, in)
if err != nil {
log.Fatalf("decrypt: %s", err)
}
// Write data to output file
fmt.Fprint(os.Stdout, string(out))
}
@perholmes
Copy link

Late to the party, but top notch example. I was going nuts trying to do compatible encryption between Go and PHP. This Gist nailed it, thanks!

@apokalyptik
Copy link
Author

Late to the party, but top notch example. I was going nuts trying to do compatible encryption between Go and PHP. This Gist nailed it, thanks!

Lol. I don't even remember writing this. but I'm super glad it was useful to you!

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