Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS SecItemCopyMatching RSA public key format?

I'm trying to extract a 1024-bit RSA public key from an already generated key pair (two SecKeyRefs), in order to send it over the wire. All I need is a plain (modulus, exponent) pair, which should take up exactly 131 bytes (128 for the modulus and 3 for the exponent).

However, when I fetch the key info as a NSData object, I get 140 bits instead of 131. Here's an example result:

<30818902 818100d7 514f320d eacf48e1 eb64d8f9 4d212f77 10dd3b48 ba38c5a6
 ed6ba693 35bb97f5 a53163eb b403727b 91c34fc8 cba51239 3ab04f97 dab37736
 0377cdc3 417f68eb 9e351239 47c1f98f f4274e05 0d5ce1e9 e2071d1b 69a7cac4
 4e258765 6c249077 dba22ae6 fc55f0cf 834f260a 14ac2e9f 070d17aa 1edd8db1
 0cd7fd4c c2f0d302 03010001>

After retrying the key generation a couple of times and comparing the resulting NSData objects, the bytes that remain the same for all keys are the first 7:

<30818902 818100>

The last three bytes look like the exponent (65537, a common value). There are also two bytes between the "modulus" and the exponent:

<0203>

Can someone with more crypto experience help me identify what encoding is this? DER? How do I properly decode the modulus and exponent?

I tried manually stripping out the modulus and exponent using

NSData* modulus = [keyBits subdataWithRange:(NSRange){ 7, 128 }];
NSData* exponent = [keyBits subdataWithRange:(NSRange){ 7 + 128 + 2, 3 }];

but I get errors when trying to decrypt data which the remote host encoded using that "key".

EDIT:

Here's a gist of the solution I ended up using to unpack the RSA blob: https://gist.github.com/vl4dimir/6079882

like image 491
Vladimir Mitrovic Avatar asked Nov 03 '22 14:11

Vladimir Mitrovic


1 Answers

Assuming you want the solution to work under iOS, please have a look at this thread. The post confirms that the encoding is DER and shows how to extract the exponent and modulus from the NSData object you started with.

There is another solution that won't work on iOS, but will work on Desktop systems (including MacOS X) that have OpenSSL installed in this thread. Even if you are looking for the iOS-only solution you can still use this to verify your code is working correctly.

like image 127
user8472 Avatar answered Nov 15 '22 07:11

user8472