Post

Replies

Boosts

Views

Activity

Reply to Export Public Key in PEM Format
SecKeyCopyExternalRepresentation returns data in the PKCS #1 format for an RSA key. The RSA Public key PEM file looks like below ----BEGIN RSA PUBLIC KEY BASE64 ENCODED DATA----END RSA PUBLIC KEY Within the base64 encoded data the following DER structure is present: RSAPublicKey ::= SEQUENCE { &#9;&#9;modulus&#9;&#9;&#9;&#9;&#9; INTEGER,&#9;-- n &#9;&#9;publicExponent&#9;&#9;INTEGER&#9; -- e } The PKCS #1 format for an RSA key should be preppended by appropriate “precoded” ASN.1 binary data structure. Refer to the pemPrefixBuffer in the example below: &#9;&#9;&#9;&#9;// creating client public and private key &#9;&#9;&#9;&#9;var publicKeySec, privateKeySec: SecKey? &#9;&#9;&#9;&#9;var error: Unmanaged<CFError>? &#9;&#9;&#9;&#9;let keyattribute = [ &#9;&#9;&#9;&#9;&#9;&#9;kSecAttrKeyType as String: kSecAttrKeyTypeRSA, &#9;&#9;&#9;&#9;&#9;&#9;kSecAttrKeySizeInBits as String : 1024, &#9;&#9;&#9;&#9;&#9;&#9;kSecAttrIsPermanent as String: false &#9;&#9;&#9;&#9;&#9;&#9;] as CFDictionary &#9;&#9;&#9;&#9;SecKeyGeneratePair(keyattribute, &publicKeySec, &privateKeySec) &#9;&#9;&#9;&#9;// client public key to pem string &#9;&#9;&#9;&#9;let keyData = SecKeyCopyExternalRepresentation(publicKeySec!, &error) &#9;&#9;&#9;&#9;let data = keyData! as Data &#9;&#9;&#9;&#9;let pemPrefixBuffer :[UInt8] = [ &#9;&#9;&#9;&#9;&#9;&#9;0x30, 0x81, 0x9f, 0x30, 0x0d, 0x06, 0x09, 0x2a, &#9;&#9;&#9;&#9;&#9;&#9;0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, &#9;&#9;&#9;&#9;&#9;&#9;0x05, 0x00, 0x03, 0x81, 0x8d, 0x00 &#9;&#9;&#9;&#9;] &#9;&#9;&#9;&#9;var finalPemData = Data(bytes: pemPrefixBuffer as [UInt8], count: pemPrefixBuffer.count) &#9;&#9;&#9;&#9;finalPemData.append(data) &#9;&#9;&#9;&#9;let finalPemString = finalPemData.base64EncodedString(options: .lineLength64Characters) &#9;&#9;&#9;&#9;let clientPublicKeyString = "-----BEGIN PUBLIC KEY-----\r\n\(finalPemString)\r\n-----END PUBLIC KEY-----\r\n" Now you can send clientPublicKeyString to your server expecting a PEM encoded RSA Public key.
Sep ’20