0

We are trying to create a ’SecKey’ from a ‘.der’ file. But ‘SecKeyCreateWithData’ always throw ‘Nil ’ with Error.


Steps Followed::

First we created a ECDSA Private & Public key pair with the below Commands , then converted the .pem file holding the private key to ‘.der’file. 
Finally used the ‘.der’ file to generate a ‘SecKey’ via code.

Commands Used to Generate Private & Public Keys::

openssl ecparam -genkey -name prime256v1 -noout -out ec-key-pair.pem

openssl ec -in ec-key-pair.pem -pubout -out ec-key-pair.pub

Command Used to Generate .Der file::


openssl pkey -outform der -in ec-key-pair.pem -out ec-key-pair.der

Content Inside .pem file::

-----BEGIN EC PRIVATE KEY----- MHcCAQEEIKJTc3zI8D07Myh7ZIR+wGyQgsjEeKdH0+hSiErK5AjzoAoGCCqGSM49 AwEHoUQDQgAEvbOBrM/D2fX05zKQYuJiTRP6YiUBabImrHb9s+OHimxUxX+E9jVe oQ6nxSOkfgm0H1OjLfp2xGLqkDTuF38UGQ== -----END EC PRIVATE KEY-----

Error Received::

Unmanaged - _value : Error Domain=NSOSStatusErrorDomain Code=-50 "EC private key creation from data failed" UserInfo={NSDescription=EC private key creation from data failed}

Minimum Deployment Target Used::

iOS 14.0

Code Used::

    if let certificateData = NSData(contentsOf:Bundle.main.url(forResource: "ec-key-pair", withExtension: "der")! ) {
            var error: Unmanaged<CFError>? = nil
            let privateSecKey = SecKeyCreateWithData(certificateData , [
                   kSecAttrKeyType: kSecAttrKeyTypeEC,
                   kSecAttrKeyClass: kSecAttrKeyClassPrivate] as NSDictionary, &error)
}

1 Answer 1

0

It looks like you're not passing the key in the correct format. You're passing ASN.1 DER and the format SecKeyCreateWithData expects is explained here: https://developer.apple.com/documentation/security/1643698-seckeycopyexternalrepresentation

For an elliptic curve private key, the output is formatted as the public key concatenated with the big endian encoding of the secret scalar, or 04 || X || Y || K.

I do not know if there is a way to directly generate the format required from OpenSSL. You may have to do some parsing!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.