6
6
"crypto/rsa"
7
7
"crypto/sha256"
8
8
"crypto/x509"
9
+ "encoding/pem"
10
+ "errors"
11
+ "fmt"
9
12
)
10
13
11
14
type RsaSuite struct {}
@@ -55,7 +58,7 @@ func (r RsaSuite) Verify(message []byte, publicKey []byte, signature []byte) err
55
58
}
56
59
57
60
func (r RsaSuite ) Encrypt (publicKey []byte , plaintext []byte ) ([]byte , error ) {
58
- pk , err := x509 . ParsePKCS1PublicKey (publicKey )
61
+ pk , err := parseRsaPublicKey (publicKey )
59
62
if err != nil {
60
63
return nil , err
61
64
}
@@ -71,3 +74,41 @@ func (r RsaSuite) Decrypt(privateKey []byte, ciphertext []byte) ([]byte, error)
71
74
72
75
return rsa .DecryptPKCS1v15 (rand .Reader , sk , ciphertext )
73
76
}
77
+
78
+ // parseRsaPublicKey will unmarshal any bytes that have been normalised using `NormalisePublicKeyBytes`
79
+ func parseRsaPublicKey (b []byte ) (* rsa.PublicKey , error ) {
80
+ if len (b ) == 0 {
81
+ return nil , errors .New ("public key was empty" )
82
+ }
83
+
84
+ return x509 .ParsePKCS1PublicKey (b )
85
+ }
86
+
87
+ // NormalisePublicKeyBytes takes bytes representing a public key from a variety of sources and transforms them
88
+ // into a format usable by the sidecar and other apps
89
+ func NormalisePublicKeyBytes (fileBytes []byte ) ([]byte , error ) {
90
+ // if it's in pkcs1 format, just return it
91
+ _ , err := x509 .ParsePKCS1PublicKey (fileBytes )
92
+ if err == nil {
93
+ return fileBytes , nil
94
+ }
95
+
96
+ // otherwise try unwrapping the PEM
97
+ block , _ := pem .Decode (fileBytes )
98
+ if block == nil {
99
+ return nil , fmt .Errorf ("could not decode the public key - not in PEM or PKCS1 format" )
100
+ }
101
+
102
+ out , err := x509 .ParsePKIXPublicKey (block .Bytes )
103
+ if err != nil {
104
+ return nil , fmt .Errorf ("failed to parse PEM: %w" , err )
105
+ }
106
+
107
+ // and try to parse the interior key as an RSA key
108
+ parsed , ok := out .(* rsa.PublicKey )
109
+ if ! ok {
110
+ return nil , fmt .Errorf ("failed to parse public key bytes wrapped in PEM: %w" , err )
111
+ }
112
+
113
+ return x509 .MarshalPKCS1PublicKey (parsed ), nil
114
+ }
0 commit comments