Problem using P256.Signing.PublicKey on iOS

1.4k views Asked by At

I generated a public/private key pair using the following commands:

openssl ecparam -genkey -name secp256k1 -noout -out private.pem
openssl ec -in private.pem -text -noout

This generates the following result (don't worry, private key is for testing and not used anywhere)

read EC key
Private-Key: (256 bit)
priv:
    4c:b2:38:08:ab:d7:95:eb:38:20:7c:a8:cd:7d:d7:
    64:41:17:12:26:d4:77:ce:b7:f8:12:05:15:9e:d2:
    dc:0b
pub:
    04:ef:01:0e:e3:28:49:e3:ef:bc:52:a7:c6:c5:5d:
    96:3c:3e:7c:3f:f9:9b:65:c8:69:76:59:54:16:c2:
    31:9c:70:bc:2b:07:a9:fe:c9:26:ed:00:78:72:11:
    e1:fb:99:bc:ab:ea:1c:d4:d2:2c:27:a1:06:81:52:
    bf:5c:9d:ec:62

The public key is 65 bytes.

Next I export the public key in Base64 format

openssl ec -in private.pem -pubout -out ec-pub.pem

this generates the following file

-----BEGIN PUBLIC KEY-----
MFYwEAYHKoZIzj0CAQYFK4EEAAoDQgAE7wEO4yhJ4++8UqfGxV2WPD58P/mbZchp
dllUFsIxnHC8Kwep/skm7QB4chHh+5m8q+oc1NIsJ6EGgVK/XJ3sYg==
-----END PUBLIC KEY-----

However if I do a base64decode of the above key, the result is 88 bytes.

Passing these 88 bytes to P256.Signing.PublicKey(rawRepresentation: data) results in the following error:

CryptoKit.CryptoKitError.incorrectParameterSize

This however, works:

let data = Array<UInt8>(arrayLiteral: 04,0xef,0x01,0x0e,0xe3,0x28,0x49,0xe3,0xef,0xbc,0x52,0xa7,0xc6,0xc5,0x5d,0x96,0x3c,0x3e,0x7c,0x3f,0xf9,0x9b,0x65,0xc8,0x69,0x76,0x59,0x54,0x16,0xc2,0x31,0x9c,0x70,0xbc,0x2b,0x07,0xa9,0xfe,0xc9,0x26,0xed,0x00,0x78,0x72,0x11,0xe1,0xfb,0x99,0xbc,0xab,0xea,0x1c,0xd4,0xd2,0x2c,0x27,0xa1,0x06,0x81,0x52,0xbf,0x5c,0x9d,0xec,0x62)

let key = try P256.Signing.PublicKey(x963Representation: data)

Any idea what I need to do to get this working?

Thanks!

1

There are 1 answers

0
Asperi On

Passing these 88 bytes to P256.Signing.PublicKey(rawRepresentation: data) results in the following error:

There is a PEM prefix, the raw key is at the end, so use instead

P256.Signing.PublicKey(rawRepresentation: data.suffix(65))