Skip to content

Commit

Permalink
Merge pull request spacemonkeygo#34 from norx85/master
Browse files Browse the repository at this point in the history
Add of method to permit the load of private key with password
  • Loading branch information
jtolio committed Nov 29, 2015
2 parents e54919e + 730bda1 commit 5230a35
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions key.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,41 @@ func LoadPrivateKeyFromPEM(pem_block []byte) (PrivateKey, error) {
return p, nil
}

// LoadPrivateKeyFromPEM loads a private key from a PEM-encoded block.
func LoadPrivateKeyFromPEMWidthPassword(pem_block []byte, password string) (PrivateKey, error) {
if len(pem_block) == 0 {
return nil, errors.New("empty pem block")
}
bio := C.BIO_new_mem_buf(unsafe.Pointer(&pem_block[0]),
C.int(len(pem_block)))
if bio == nil {
return nil, errors.New("failed creating bio")
}
defer C.BIO_free(bio)
cs := C.CString(password)
rsakey := C.PEM_read_bio_RSAPrivateKey(bio, nil, nil, unsafe.Pointer(cs))
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 {
Expand Down

0 comments on commit 5230a35

Please sign in to comment.