Created
September 1, 2014 22:38
-
-
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
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" | |
"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)) | |
} |
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
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!