Skip to content

Instantly share code, notes, and snippets.

@graetzer
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save graetzer/ec4d446670343bc25498 to your computer and use it in GitHub Desktop.
Save graetzer/ec4d446670343bc25498 to your computer and use it in GitHub Desktop.
Extract modulus and exponent from public key
// 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