IOS SecItemCopyMatching RSA Public Key Format?

I am trying to extract a 1024-bit RSA public key from an already generated key pair (two SecKeyRef s) to send it over the wire. All I need is a simple pair (modulus, exponent) , which should occupy exactly 131 bytes (128 for the module and 3 for the exponent).

However, when I retrieve key information as an NSData object, I get 140 bits instead of 131. Here is an example:

 <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 re-generating the key generation and comparing the resulting NSData objects, the bytes that remain unchanged for all keys are the first 7:

 <30818902 818100> 

The last three bytes look like an exponent (65537, total value). There are also two bytes between the "module" and the metric:

 <0203> 

Can someone with more crypto experience help me determine what encoding is? DER? How to decode a module and an exponent?

I tried to manually disable the module 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 the data that the remote host encoded with this "key".

EDIT:

Here is the gist of the solution I used to unpack the RSA blob: https://gist.github.com/vl4dimir/6079882

+4
source share
1 answer

Assuming you want the solution to work under iOS, check out this topic . The message confirms that the encoding is DER and shows how to extract the exponent and module from the NSData object you started with.

There is another solution that will not work on iOS, but will work on desktop systems (including MacOS X) in which OpenSSL is installed in this thread . Even if you are looking for an iOS-only solution, you can still use this to make sure your code is working correctly.

+2
source

Source: https://habr.com/ru/post/1440294/


All Articles