mirror of
https://github.com/libp2p/go-openssl.git
synced 2025-04-25 17:50:23 +08:00
adding LoadPrivateKeyFromDER
This commit is contained in:
parent
ef69faf59b
commit
2ffbf8f57a
35
key.go
35
key.go
@ -283,6 +283,41 @@ func LoadPrivateKeyFromPEMWidthPassword(pem_block []byte, password string) (
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// LoadPrivateKeyFromDER loads a private key from a DER-encoded block.
|
||||
func LoadPrivateKeyFromDER(der_block []byte) (PrivateKey, error) {
|
||||
if len(der_block) == 0 {
|
||||
return nil, errors.New("empty der block")
|
||||
}
|
||||
bio := C.BIO_new_mem_buf(unsafe.Pointer(&der_block[0]),
|
||||
C.int(len(der_block)))
|
||||
if bio == nil {
|
||||
return nil, errors.New("failed creating bio")
|
||||
}
|
||||
defer C.BIO_free(bio)
|
||||
|
||||
rsakey := C.d2i_RSAPrivateKey_bio(bio, nil)
|
||||
if rsakey == nil {
|
||||
return nil, errors.New("failed reading rsa key")
|
||||
}
|
||||
defer C.RSA_free(rsakey)
|
||||
|
||||
// convert to PKEY
|
||||
key := C.EVP_PKEY_new()
|
||||
if key == nil {
|
||||
return nil, errors.New("failed converting to evp_pkey")
|
||||
}
|
||||
if C.EVP_PKEY_set1_RSA(key, (*C.struct_rsa_st)(rsakey)) != 1 {
|
||||
C.EVP_PKEY_free(key)
|
||||
return nil, errors.New("failed converting to evp_pkey")
|
||||
}
|
||||
|
||||
p := &pKey{key: key}
|
||||
runtime.SetFinalizer(p, func(p *pKey) {
|
||||
C.EVP_PKEY_free(p.key)
|
||||
})
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// LoadPublicKeyFromPEM loads a public key from a PEM-encoded block.
|
||||
func LoadPublicKeyFromPEM(pem_block []byte) (PublicKey, error) {
|
||||
if len(pem_block) == 0 {
|
||||
|
@ -35,6 +35,12 @@ func TestMarshal(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
privateBlock, _ := pem_pkg.Decode(keyBytes)
|
||||
key, err = LoadPrivateKeyFromDER(privateBlock.Bytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
pem, err := cert.MarshalPEM()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
|
Loading…
Reference in New Issue
Block a user