Last active
August 29, 2015 14:06
-
-
Save graetzer/ec4d446670343bc25498 to your computer and use it in GitHub Desktop.
Extract modulus and exponent from public key
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create the keys with SecKeyGeneratePair | |
// Look at https://developer.apple.com/library/ios/samplecode/CryptoExercise/Introduction/Intro.html | |
NSData* keyData = [self _getPublicKeyBits]; | |
NSLog(@"Public Key: %@", [keyData hexadecimalString]); | |
// http://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One#Example_encoded_in_DER | |
const char *buffer = keyData.bytes; | |
NSData* modulus; | |
NSData* exponent; | |
// Check for correct ASN.1 DER start | |
if (buffer && buffer[0] == 0x30 && buffer[1] == keyData.length - 2) { | |
if (buffer[2] == 0x02) {// Check for first int number, | |
// supposed to be the modulus | |
NSUInteger length = buffer[3]; | |
modulus = [keyData subdataWithRange:NSMakeRange(4, length)]; | |
NSUInteger expOffset = 4+length; | |
if (buffer[expOffset] == 0x02) {// Check for seconds integer | |
length = buffer[expOffset + 1]; | |
exponent = [keyData subdataWithRange:NSMakeRange(expOffset+2, length)]; | |
} | |
} | |
} | |
NSLog(@"Modulus: %@", [modulus hexadecimalString]); | |
NSLog(@"Exponent: %@", [exponent hexadecimalString]); | |
// Should be the same for a 512 bit rsa key | |
// NSData* modulus = [keyData subdataWithRange:(NSRange){ 5, 64 }]; | |
// NSData* exponent = [keyData subdataWithRange:(NSRange){ 5 + 64 + 2, 3 }]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment