how I can get the modulus and the exponent values as a byte array using
SecKey
and having the public key.
iOS has no API for this. My recommendation is that you change your server to support a more sensible way of transporting RSA keys. This approach makes things unnecessarily difficult for iOS clients.
And while you’re doing that you can upgrade the security (-:
If this is actually safe …
Personally, I don’t consider anything that uses 1024-bit RSA keys to be safe. You can find links to the ongoing debate about the safety of small RSA keys in the fount of all knowledge.
Anyway, if you absolutely have to do this then you’ll need to write (or acquire) ASN.1 parsing code. Specifically, the value you get back from
SecKeyCopyExternalRepresentation
is a DER-encoded ASN.1
RSAPublicKey
structure (per RFC 3447). For debugging purposes you can look into this structure using
dumpasn1. For example:
$ dumpasn1 public.asn1
0 159: SEQUENCE {
3 13: SEQUENCE {
5 9: OBJECT IDENTIFIER rsaEncryption (1 2 840 113549 1 1 1)
16 0: NULL
: }
18 141: BIT STRING, encapsulates {
22 137: SEQUENCE {
25 129: INTEGER
: 00 C1 BE 8F CB 91 9A 02 34 A2 4F 5B 27 3E 7D F1
: 34 24 5A 65 7B 41 50 8B D0 1E A1 9B DB FF D0 F6
: 00 82 08 CD 46 47 8B 82 F9 4A D9 16 EE B1 9C 15
: 12 A6 00 02 33 48 05 F3 70 92 8B 70 B2 C3 BE 2B
: B0 C4 8F 85 80 83 B4 A9 DB 1F A4 ED CD E0 2D 0E
: DE 08 49 33 37 92 05 55 FB 25 3B B9 BD 55 11 C6
: AE B8 F3 86 C9 18 06 A3 72 20 5B 38 C0 C9 80 EA
: 23 45 55 B1 EA CA 8A 8C 96 54 22 1E 75 1E EE DF
: [ Another 1 bytes skipped ]
157 3: INTEGER 65537
: }
: }
: }
0 warnings, 0 errors.
The first
INTEGER
element is the
modulus
field; the second is the
publicExponent
field. The value of the latter is 65537, or 0x00010001, which aligns with your “00 01 00 01” requirement.
IMPORTANT The
modulus
field in this example is 129 bytes, not 128 bytes, because of a leading zero. This leading zero shows up due to the way DER encodes ASN.1
INTEGER
elements. Dealing with this either requires you to understand DER, so you can write your own parser, or use some sort of DER parsing library. If you decide to attempt the former you can find a whole bunch of useful info hanging off the
ASN.1 Wikipedia page.
Share and Enjoy
—
Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware
let myEmail = "eskimo" + "1" + "@apple.com"