| 1 |
package crypto |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto" |
| 5 |
"crypto/ecdsa" |
| 6 |
"crypto/ed25519" |
| 7 |
"crypto/rsa" |
| 8 |
"crypto/x509" |
| 9 |
"encoding/pem" |
| 10 |
"errors" |
| 11 |
|
| 12 |
"github.com/go-jose/go-jose/v4" |
| 13 |
) |
| 14 |
|
| 15 |
var ( |
| 16 |
ErrPEMDecode = errors.New("PEM decode failed") |
| 17 |
ErrUnsupportedFormat = errors.New("key is neither in PKCS#1 nor PKCS#8 format") |
| 18 |
ErrUnsupportedPrivateKey = errors.New("unsupported key type, must be RSA, ECDSA or ED25519 private key") |
| 19 |
) |
| 20 |
|
| 21 |
func BytesToPrivateKey(b []byte) (crypto.PublicKey, jose.SignatureAlgorithm, error) { |
| 22 |
block, _ := pem.Decode(b) |
| 23 |
if block == nil { |
| 24 |
return nil, "", ErrPEMDecode |
| 25 |
} |
| 26 |
|
| 27 |
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) |
| 28 |
if err == nil { |
| 29 |
return privateKey, jose.RS256, nil |
| 30 |
} |
| 31 |
key, err := x509.ParsePKCS8PrivateKey(block.Bytes) |
| 32 |
if err != nil { |
| 33 |
return nil, "", ErrUnsupportedFormat |
| 34 |
} |
| 35 |
switch privateKey := key.(type) { |
| 36 |
case *rsa.PrivateKey: |
| 37 |
return privateKey, jose.RS256, nil |
| 38 |
case ed25519.PrivateKey: |
| 39 |
return privateKey, jose.EdDSA, nil |
| 40 |
case *ecdsa.PrivateKey: |
| 41 |
return privateKey, jose.ES256, nil |
| 42 |
default: |
| 43 |
return nil, "", ErrUnsupportedPrivateKey |
| 44 |
} |
| 45 |
} |