Thanks, that's very useful article. However, my main concern is that go's x509 package seems not to be able to parse all the formats commonly used... or was it just me doing something in the wrong way?
And when I say "working" I guess I mean compiles and gives a good result with the output of `openssl rsa -in key.pem -out rsakey.pem` but not the direct output of `openssl req`.
// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates
// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys.
// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three.
func parsePrivateKey(der []byte) (crypto.PrivateKey, error) {
if key, err := x509.ParsePKCS1PrivateKey(der); err == nil {
return key, nil
}
if key, err := x509.ParsePKCS8PrivateKey(der); err == nil {
switch key := key.(type) {
case *rsa.PrivateKey, *ecdsa.PrivateKey:
return key, nil
default:
return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping")
}
}
if key, err := x509.ParseECPrivateKey(der); err == nil {
return key, nil
}
return nil, errors.New("crypto/tls: failed to parse private key")
}
f, err := os.Open(file)
if err != nil {
return nil, err
}
buf, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
p, _ := pem.Decode(buf)
if p == nil {
return nil, errors.New("no pem block found")
}
return x509.ParsePKCS1PrivateKey(p.Bytes)
package auth
import (
"crypto/x509"
"encoding/pem"
"fmt"
jwt "github.com/dgrijalva/jwt-go"
"io/ioutil"
"time"
)
func createToken() (token string, err error) {
claims := jwt.StandardClaims{
Issuer: "client_id",
Subject: "em...@gmail.com",
Audience: "https://login.salesforce.com",
ExpiresAt: time.Now().Add(time.Minute * 3).Unix(),
}
at := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
crt, err := ioutil.ReadFile("test-crt/private_key.pem")
if err != nil {
panic(err)
}
block, _ := pem.Decode(crt)
if block == nil {
fmt.Println("No PEM blob found")
}
signKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
panic(err)
}
token, err = at.SignedString(signKey)
if err != nil {
return
}
return
}