Created
February 1, 2018 13:37
-
-
Save chrj/1d25c18882b33e78d5882fb1fd8bf693 to your computer and use it in GitHub Desktop.
PEM encoded private RSA key in Go
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/sha256" | |
"crypto/x509" | |
"encoding/pem" | |
"errors" | |
"fmt" | |
"io" | |
"io/ioutil" | |
"log" | |
"os" | |
) | |
func decodePrivateKey(r io.Reader) (*rsa.PrivateKey, error) { | |
keydata, err := ioutil.ReadAll(r) | |
if err != nil { | |
return nil, err | |
} | |
var keybytes []byte | |
for { | |
block, rest := pem.Decode(keydata) | |
if block == nil { | |
return nil, errors.New("pem decode of private key failed") | |
} | |
if block.Type != "RSA PRIVATE KEY" { | |
keydata = rest | |
continue | |
} | |
keybytes = block.Bytes | |
break | |
} | |
return x509.ParsePKCS1PrivateKey(keybytes) | |
} | |
func main() { | |
f, err := os.Open("test.pem") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer f.Close() | |
private, err := decodePrivateKey(f) | |
if err != nil { | |
log.Fatal(err) | |
} | |
public := private.PublicKey | |
secretMessage := []byte("send reinforcements, we're going to advance") | |
label := []byte("orders") | |
rng := rand.Reader | |
ciphertext, err := rsa.EncryptOAEP(sha256.New(), rng, &public, secretMessage, label) | |
if err != nil { | |
log.Fatal(err) | |
return | |
} | |
fmt.Printf("%x\n", ciphertext) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment