Skip to content

Commit 66e979e

Browse files
committed
feat(client): Register public/private key from PEM data
Signed-off-by: Pierre-Henri Symoneaux <[email protected]>
1 parent ff1753d commit 66e979e

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

kmipclient/register.go

+53
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,59 @@ func (ex ExecRegisterWantType) PemKey(data []byte, usage kmip.CryptographicUsage
194194
}
195195
}
196196

197+
// PemPublicKey registeres a public key from PEM data. It also accepts PEM encoded private keys but will
198+
// register only the public key part of it.
199+
func (ex ExecRegisterWantType) PemPublicKey(data []byte, usage kmip.CryptographicUsageMask) ExecRegister {
200+
block, _ := pem.Decode(data)
201+
if block == nil {
202+
return ex.error(fmt.Errorf("Invalid PEM data provider"))
203+
}
204+
switch block.Type {
205+
case "RSA PUBLIC KEY":
206+
return ex.Pkcs1PublicKey(block.Bytes, usage)
207+
case "PUBLIC KEY":
208+
return ex.X509PublicKey(block.Bytes, usage)
209+
case "RSA PRIVATE KEY":
210+
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
211+
if err != nil {
212+
return ex.error(err)
213+
}
214+
return ex.RsaPublicKey(&key.PublicKey, usage)
215+
case "EC PRIVATE KEY":
216+
key, err := x509.ParseECPrivateKey(block.Bytes)
217+
if err != nil {
218+
return ex.error(err)
219+
}
220+
return ex.EcdsaPublicKey(&key.PublicKey, usage)
221+
case "PRIVATE KEY":
222+
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
223+
if err != nil {
224+
return ex.error(err)
225+
}
226+
pk := key.(interface{ Public() crypto.PublicKey })
227+
return ex.PublicKey(pk.Public().(PublicKey), usage)
228+
default:
229+
return ex.error(fmt.Errorf("Unsupported PEM type %q", block.Type))
230+
}
231+
}
232+
233+
func (ex ExecRegisterWantType) PemPrivateKey(data []byte, usage kmip.CryptographicUsageMask) ExecRegister {
234+
block, _ := pem.Decode(data)
235+
if block == nil {
236+
return ex.error(fmt.Errorf("Invalid PEM data provider"))
237+
}
238+
switch block.Type {
239+
case "RSA PRIVATE KEY":
240+
return ex.Pkcs1PrivateKey(block.Bytes, usage)
241+
case "EC PRIVATE KEY":
242+
return ex.Sec1PrivateKey(block.Bytes, usage)
243+
case "PRIVATE KEY":
244+
return ex.Pkcs8PrivateKey(block.Bytes, usage)
245+
default:
246+
return ex.error(fmt.Errorf("Unsupported PEM type %q", block.Type))
247+
}
248+
}
249+
197250
func (ex ExecRegisterWantType) Pkcs1PrivateKey(der []byte, usage kmip.CryptographicUsageMask) ExecRegister {
198251
key, err := x509.ParsePKCS1PrivateKey(der)
199252
if err != nil {

0 commit comments

Comments
 (0)