-
Notifications
You must be signed in to change notification settings - Fork 277
/
privkey.go
50 lines (47 loc) · 1.55 KB
/
privkey.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package athenzutils
import (
"crypto"
"crypto/ecdsa"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"reflect"
)
// ExtractSignerInfo extract crypto.Signer and x509.SignatureAlgorithm from the given private key (ECDSA or RSA).
func ExtractSignerInfo(privateKeyPEM []byte) (crypto.Signer, x509.SignatureAlgorithm, error) {
block, _ := pem.Decode(privateKeyPEM)
if block == nil {
return nil, x509.UnknownSignatureAlgorithm, fmt.Errorf("unable to load private key")
}
switch block.Type {
case "EC PRIVATE KEY":
key, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, x509.UnknownSignatureAlgorithm, err
}
return key, x509.ECDSAWithSHA256, nil
case "RSA PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, x509.UnknownSignatureAlgorithm, err
}
return key, x509.SHA256WithRSA, nil
case "PRIVATE KEY":
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, x509.UnknownSignatureAlgorithm, err
}
switch k := key.(type) {
case *ecdsa.PrivateKey:
return k, x509.ECDSAWithSHA256, nil
case *rsa.PrivateKey:
return k, x509.SHA256WithRSA, nil
default:
// PKCS#8 format may contain multiple key types other than RSA / EC, but current ZMS / ZTS server implementation only supports RSA / EC private keys
return nil, x509.UnknownSignatureAlgorithm, fmt.Errorf("unsupported private key type: %s", reflect.TypeOf(k).Name())
}
default:
return nil, x509.UnknownSignatureAlgorithm, fmt.Errorf("unsupported private key type: %s", block.Type)
}
}