Skip to content

Commit 0c71834

Browse files
Merge pull request spacemonkeygo#10 from mendersoftware/engine_load_private_key_review
EngineLoadPrivateKey wrapper over ENGINE_load_private_key
2 parents b6c4587 + 41cb95f commit 0c71834

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

key.go

+27
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
package openssl
1616

17+
// #include "openssl/engine.h"
1718
// #include "shim.h"
1819
import "C"
1920

@@ -105,6 +106,7 @@ type PrivateKey interface {
105106

106107
type pKey struct {
107108
key *C.EVP_PKEY
109+
engine_ref interface{} //see comment below in EngineLoadPrivateKey
108110
}
109111

110112
func (key *pKey) evpPKey() *C.EVP_PKEY { return key.key }
@@ -272,6 +274,31 @@ func (key *pKey) MarshalPKIXPublicKeyDER() (der_block []byte,
272274
return ioutil.ReadAll(asAnyBio(bio))
273275
}
274276

277+
// EngineLoadPrivateKey loads a private key by id
278+
// the id is a pkcs#11 URI https://tools.ietf.org/html/rfc7512#section-2.3
279+
// Engine comes from e.g.: e,err:=openssl.EngineById("pkcs11")
280+
func EngineLoadPrivateKey(e *Engine, id string) (PrivateKey, error) {
281+
if e == nil {
282+
return nil, errors.New("ENGINE_load_private_key cannot be called with NULL engine")
283+
}
284+
285+
keyID := C.CString(id)
286+
defer C.free(unsafe.Pointer(keyID))
287+
288+
key := C.ENGINE_load_private_key(e.e, keyID, nil, nil)
289+
if key == nil {
290+
return nil, errors.New("cannot load private key, ENGINE_load_private_key error")
291+
}
292+
293+
// engine_ref trick inspired by the work of Renato Aguiar https://github.com/renatoaguiar
294+
// it prevents the engine to be freed while we still use the key.
295+
p := &pKey{key: key, engine_ref: e}
296+
runtime.SetFinalizer(p, func(p *pKey) {
297+
C.X_EVP_PKEY_free(p.key)
298+
})
299+
return p, nil
300+
}
301+
275302
// LoadPrivateKeyFromPEM loads a private key from a PEM-encoded block.
276303
func LoadPrivateKeyFromPEM(pem_block []byte) (PrivateKey, error) {
277304
if len(pem_block) == 0 {

0 commit comments

Comments
 (0)