Get Modulus and Exponent from Public Key iOS - ios

I am looking to get the Modulus and Exponent from a public key in iOS. I have looked at many different sites and looked at Apple, but cannot just get it working.
This is my code so far:
- (void)generateKeyPairPlease
{
OSStatus status = noErr;
NSMutableDictionary *privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary *publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary *keyPairAttr = [[NSMutableDictionary alloc] init];
NSData * publicTag = [NSData dataWithBytes:publicKeyIdentifier
length:strlen((const char *)publicKeyIdentifier)];
NSData * privateTag = [NSData dataWithBytes:privateKeyIdentifier
length:strlen((const char *)privateKeyIdentifier)];
SecKeyRef publicKey = NULL;
SecKeyRef privateKey = NULL;
[keyPairAttr setObject:(__bridge id)kSecAttrKeyTypeRSA
forKey:(__bridge id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithInt:2048]
forKey:(__bridge id)kSecAttrKeySizeInBits];
[privateKeyAttr setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag
forKey:(__bridge id)kSecAttrApplicationTag];
[publicKeyAttr setObject:[NSNumber numberWithBool:YES]
forKey:(__bridge id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag
forKey:(__bridge id)kSecAttrApplicationTag];
[keyPairAttr setObject:privateKeyAttr
forKey:(__bridge id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr
forKey:(__bridge id)kSecPublicKeyAttrs];
status = SecKeyGeneratePair((__bridge CFDictionaryRef)keyPairAttr,
&publicKey, &privateKey);
// error handling...
NSData *ppp = [NSData dataWithBytes:publicKey length:strlen((const char *)publicKey)];
NSString *responseString, *responseStringASCII, *responseStringUTF8;
responseStringASCII = [[NSString alloc] initWithData:ppp encoding:NSASCIIStringEncoding];
if (!responseStringASCII)
{
responseString = [[NSString alloc] initWithData:ppp encoding:NSUTF8StringEncoding];
}
else
{
responseStringUTF8 = [[NSString alloc] initWithData:ppp encoding:NSUTF8StringEncoding];
if(responseStringUTF8 != nil && [responseStringUTF8 length] < [responseStringASCII length])
{
responseString = [responseStringUTF8 retain];
}
else
{
responseString = [responseStringASCII retain];
}
[responseStringUTF8 release];
}
publicKeyString = responseString;
if(publicKey) CFRelease(publicKey);
if(privateKey) CFRelease(privateKey);
NSData *exp = [self getPublicKeyExp];
NSData *mod = [self getPublicKeyMod];
NSString *expString = [[NSString alloc] initWithData:exp encoding:NSUTF8StringEncoding];
NSString *modString = [[NSString alloc] initWithData:mod encoding:NSUTF8StringEncoding];
NSLog(#"exponent = %# \n modulus = %#", expString, modString);
}
- (NSData *)getPublicKeyBits: (NSString*) publicKeyIdentifier {
OSStatus sanityCheck = noErr;
NSData * publicKeyBits = nil;
CFTypeRef pk = NULL;
NSMutableDictionary * queryPublicKey = [[NSMutableDictionary alloc] init];
NSData* publicTag = [publicKeyIdentifier dataUsingEncoding:NSUTF8StringEncoding];
// Set the public key query dictionary.
[queryPublicKey setObject:(__bridge_transfer id)kSecClassKey forKey:(__bridge_transfer id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge_transfer id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge_transfer id)kSecAttrKeyTypeRSA forKey:(__bridge_transfer id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge_transfer id)kSecReturnData];
// Get the key bits.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, &pk);
if (sanityCheck != noErr)
{
publicKeyBits = nil;
}
publicKeyBits = (__bridge id)pk;
NSLog(#"public bits %#",publicKeyBits);
return publicKeyBits;
}
- (NSData *)getPublicKeyExp
{
NSData* pk = [self getPublicKeyBits:publicKeyString];
if (pk == NULL) {
return NULL;
}
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
iterator += mod_size;
iterator++; // TYPE - bit stream exp
int exp_size = [self derEncodingGetSizeFrom:pk at:&iterator];
return [pk subdataWithRange:NSMakeRange(iterator, exp_size)];
return pk;
}
- (NSData *)getPublicKeyMod
{
NSData* pk = [self getPublicKeyBits:publicKeyString];
if (pk == NULL) {
return NULL;
}
int iterator = 0;
iterator++; // TYPE - bit stream - mod + exp
[self derEncodingGetSizeFrom:pk at:&iterator]; // Total size
iterator++; // TYPE - bit stream mod
int mod_size = [self derEncodingGetSizeFrom:pk at:&iterator];
return [pk subdataWithRange:NSMakeRange(iterator, mod_size)];
}
- (int)derEncodingGetSizeFrom:(NSData*)buf at:(int*)iterator
{
const uint8_t* data = [buf bytes];
int itr = *iterator;
int num_bytes = 1;
int ret = 0;
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80;
itr++;
}
for (int i = 0 ; i < num_bytes; i++) ret = (ret * 0x100) + data[itr + i];
*iterator = itr + num_bytes;
return ret;
}
However, when I get to retrieving the Modulus and Exponent from the relevant methods, they keep returning NULL?

Related

iOS reading data from bluetooth 4.2 BLE device

I'm trying to read data from a BLE device getting the data from delegate method
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error.
I am reading the data from CBCharacteristic object by using property value.
This returns the NSData.
I converted this NSData to Bytes.
How to Calculate the Weight from this Bytes data?. By this code i am not getting exact value.
Here is MyCode
/** This callback lets us know more data has arrived via notification on the characteristic
*/
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
NSLog(#"peripheral %#", peripheral);
NSLog(#"chacteristic %#", characteristic);
NSLog(#"chacteristic value %#", [characteristic value]);
Response Is Like This
peripheral <CBPeripheral: 0x15e469e90, identifier = A4B7E3A0-A988-02CF-3FAE-3B62056F465B, name = eBody-Fat-Scale, state = connected>
chacteristic <CBCharacteristic: 0x15e250980, UUID = 2A9D, properties = 0x20, value = <0ee803df 07010116 390901ff ff0000>, notifying = YES>
chacteristic value <0ee803df 07010116 390901ff ff0000>
if (error) {
NSLog(#"Error discovering characteristics: %# and %#", [error localizedDescription],[error localizedFailureReason]);
return;
}
int height;
self.targetPeripheral = peripheral;
NSData *tempData=characteristic.value;
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSString *str = [NSString stringWithUTF8String:[tempData bytes]];
NSLog(#"string data %#",str);
NSData *lol = characteristic.value;
NSLog(#"length %lu", (unsigned long)[lol length]);
Byte *byte = (Byte *)[lol bytes];
for(int i = 0;i<[lol length];i++)
{
NSLog(#"Receive byte:%d",byte[i]);
}
/* self.targetPeripheral = peripheral;
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
NSData *lol = characteristic.value;
Byte *byte = (Byte *)[lol bytes];
for(int i = 0;i<[lol length];i++)
{
NSLog(#"Received bytes:%d",byte[i]);
}*/
if(byte[0] == 0xfc)
{
Byte weightHigh = 0;
if(byte[1] >= 0xc0)
{
weightHigh = byte[1] - 0xc0;
}
else if(byte[1] >= 0x80)
{
weightHigh = byte[1] - 0x80;
}
else if(byte[1]>= 0x40)
{
weightHigh = byte[1] - 0x40;
}
float weightdata = (float)(weightHigh * 256 + byte[2])/10;
NSUserDefaults *prefers = [NSUserDefaults standardUserDefaults];
if([[prefers objectForKey:#"units"] isEqualToString:#"ft"])
{
NSString *weight = [[NSString alloc]initWithFormat:#"%.1f",[UnitParse convertKgToLb:weightdata]];
_weightDataLabel.text = [[NSString alloc] initWithFormat:#"%#",weight];
}
else
{
NSString *weight = [[NSString alloc]initWithFormat:#"%.1f",weightdata];
_weightDataLabel.text = [[NSString alloc] initWithFormat:#"%#",weight];
}
if(weightdata != _lastWeightData)
{
[RCCircleAnimation stopAnimation:_circleImageView.layer];
_lastWeightData = weightdata;
if(weightHigh * 256 + byte[2] == 0x3f*256+255)//overload
{
_weightDataLabel.text = #"overload";
}
else
{
NSThread* myThread1 = [[NSThread alloc] initWithTarget:self selector:#selector(mySoundPlayer)object:nil];
[myThread1 start];
NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
[dic setObject:[[NSString alloc] initWithFormat:#"%2f",weightdata] forKey:#"Weight"];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSString *datestr = [formatter stringFromDate:[NSDate date]];
[dic setObject:datestr forKey:#"TestTime"];
/* // First Time
NSUserDefaults *userDefaults ;
userDefaults = [NSUserDefaults standardUserDefaults];
if ([userDefaults objectForKey:#"UserWeightDataArray"] == nil)
{
[_valuesArray addObject:dic];
[userDefaults setObject:_valuesArray forKey:#"UserWeightDataArray"];
[userDefaults synchronize];
}
else
{
// second Time
[_dateArray addObject:dic];
_finalArray = [[_dateArray arrayByAddingObjectsFromArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"UserWeightDataArray"]] mutableCopy];
[userDefaults setObject:_finalArray forKey:#"UserWeightDataArray"];
[userDefaults synchronize];
}
*/
height = [[[MySingleton sharedSingleton].nowuserinfo valueForKey:#"Height"] intValue];
float bmi = weightdata/((height/100.0f)*(height/100.0f));
_bmiDataLabel.text = [[NSString alloc] initWithFormat:#"%.1f",bmi];
NSLog(#"_weightDataLabel.text %#", _weightDataLabel.text);
[self uploadDeviceInformationToServer:height weight:[[NSString alloc]initWithFormat:#"%.1f",weightdata]];
NSThread* myThread2 = [[NSThread alloc] initWithTarget:self selector:#selector(uploadWeightData:)object:dic];
[myThread2 start];
NSThread* myThread3 = [[NSThread alloc] initWithTarget:self selector:#selector(getAdviceByWeightData:)object:dic];
[myThread3 start];
NSThread* myThread = [[NSThread alloc] initWithTarget:self selector:#selector(sendCloseCmd)object:nil];
[myThread start];
}
}
}
else
{
_lastWeightData = 0;
Byte weightHigh = 0;
if(byte[1] >= 0xc0)
{
weightHigh = byte[1] - 0xc0;
}
else if(byte[1] >= 0x80)
{
weightHigh = byte[1] - 0x80;
}
else if(byte[1]>= 0x40)
{
weightHigh = byte[1] - 0x40;
}
float weightdata = (float)(weightHigh * 256 + byte[2])/10;
NSUserDefaults *prefers = [NSUserDefaults standardUserDefaults];
NSLog(#"data is %#",[prefers objectForKey:#"units"]);
if([[prefers objectForKey:#"units"] isEqualToString:#"ft"])
{
double temp=[UnitParse convertKgToLb:weightdata];
double temp1=[UnitParse convertLbToKg:weightdata];
NSString *weight = [[NSString alloc]initWithFormat:#"%.1f",temp];
NSLog(#"weight in if .... %# and lb is %.1f and kg %.1f",weight,temp,temp1);
_weightDataLabel.text = [[NSString alloc] initWithFormat:#"%#",weight];
}
else
{
double temp=[UnitParse convertKgToLb:weightdata];
double temp1=[UnitParse convertLbToKg:weightdata];
NSLog(#"weight in if .... %f and lb is %.1f and kg %.1f",weightdata,temp,temp1);
NSString *weight = [[NSString alloc]initWithFormat:#"%.1f",temp1];
NSLog(#"weight in else .... %#",weight);
_weightDataLabel.text = [[NSString alloc] initWithFormat:#"%#",weight];
}
// NSString *weight = [[NSString alloc]initWithFormat:#"%.1f",[UnitParse convertKgToLb:weightdata]];
// _weightDataLabel.text = [[NSString alloc] initWithFormat:#"%#",weight];
}
// Have we got everything we need?
if ([stringFromData isEqualToString:#"EOM"]) {
// We have, so show the data,
//[self.textview setText:[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]];
NSLog(#"GetDataValue : %#",[[NSString alloc] initWithData:self.data encoding:NSUTF8StringEncoding]);
// Cancel our subscription to the characteristic
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
// and disconnect from the peripehral
[self.centralManager cancelPeripheralConnection:peripheral];
}
}
output of bytes data is:
Receive byte:14 byte data is 0xe
Receive byte:176 byte data is 0xb0
Receive byte:4 byte data is 0x4
Receive byte:223 byte data is 0xdf
Receive byte:7 byte data is 0x7
Receive byte:1 byte data is 0x1
Receive byte:1 byte data is 0x1
Receive byte:23 byte data is 0x17
Receive byte:48 byte data is 0x30
Receive byte:17 byte data is 0x11
Receive byte:1 byte data is 0x1
Use this code for read the byte data of weight or heart rate or temperature.
Lol is the nsdata object.
const uint8_t *reportData = [lol bytes];
uint16_t bpm = (uint16_t)reportData;
CGFloat weightdata = 0;
if ((reportData[1] & 0x01) == 0)
{
/* uint8 bpm */
NSLog(#"if reportData is %d",reportData[1]);
bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
NSLog(#"if bpm data is %d",bpm);
weightdata = bpm/200.0;
}
else
{
/* uint16 bpm */
NSLog(#"reportData is %d",reportData[1]);
bpm = CFSwapInt16LittleToHost(*(uint16_t *)(&reportData[1]));
NSLog(#"bpm data is %d",bpm);
weightdata = bpm/200.0;
}

Can't setup VPN connection using Network Extension Framework iOS 8 in Swift

So I've been trying to use the iOS 8 Network Extension Framework to setup a VPN connection when the users presses a UIButton.
I've used the following tutorial: http://ramezanpour.net/post/2014/08/03/configure-and-manage-vpn-connections-programmatically-in-ios-8/
But for some reason it keeps asking for the vpn password and shared secret. Even though I set the passwordReference and sharedSecretReference.
And if I enter these details when installing the profile it will still not work. It just doesn't do anything when starting the connection using the framework. When trying to connect using the settings app it gives a "there's no sharedSecret" error.
This is the code I use to set up the connection.
func toggleConnection(sender: UIButton) {
if(!self.connected){
self.manager.loadFromPreferencesWithCompletionHandler { (error) -> Void in
if((error) != nil) {
println("VPN Preferences error: 1")
}
else {
var p = NEVPNProtocolIPSec()
p.username = "$username"
p.serverAddress = "$vpn"
p.passwordReference = KeychainService.dataForKey("vpnPassword")!
println(p.passwordReference)
p.authenticationMethod = NEVPNIKEAuthenticationMethod.SharedSecret
p.sharedSecretReference = KeychainService.dataForKey("sharedSecret")!
println(p.sharedSecretReference)
p.localIdentifier = "vpn"
p.remoteIdentifier = "vpn"
p.disconnectOnSleep = false
self.manager.`protocol` = p
self.manager.onDemandEnabled = true
self.manager.localizedDescription = "VPN"
self.manager.saveToPreferencesWithCompletionHandler({ (error) -> Void in
if((error) != nil) {
println("VPN Preferences error: 2")
println(error)
}
else {
var startError: NSError?
self.manager.connection.startVPNTunnelAndReturnError(&startError)
if((startError) != nil) {
println("VPN Preferences error: 3")
println(startError)
}
else {
println("Start VPN")
}
}
})
}
}
}
}
These are the functions I use as a keychain reference.
class func save(service: NSString, key: String, data: NSString) {
var dataFromString: NSData = data.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPassword, service, key, dataFromString], forKeys: [kSecClass, kSecAttrService, kSecAttrAccount, kSecValueData])
SecItemDelete(keychainQuery as CFDictionaryRef)
if data == "" { return }
var status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)
println(status)
}
class func load(service: NSString, key: String) -> NSData? {
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPassword, service, key, kCFBooleanTrue, kSecMatchLimitOne, kCFBooleanTrue], forKeys: [kSecClass, kSecAttrService, kSecAttrAccount, kSecReturnData, kSecMatchLimit, kSecReturnPersistentRef])
var dataTypeRef :Unmanaged<AnyObject>?
let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
println(status)
if (status != errSecSuccess) {
return nil
}
let opaque = dataTypeRef?.toOpaque()
var contentsOfKeychain: NSData? = nil
if let op = opaque {
let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue()
contentsOfKeychain = retrievedData
}
println(contentsOfKeychain)
return contentsOfKeychain
}
Any help is appreciated!
So I had to eventually replace the Swift library I used to access the keychain with the following Obj-C methods. This solved my problem as far as I'm currently able to tell.
+ (void) storeData: (NSString * )key data:(NSData *)data {
NSLog(#"Store Data");
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [key dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:#"VPN" forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:data forKey:(__bridge id)kSecValueData];
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
if(errSecSuccess != status) {
NSLog(#"Unable add item with key =%# error:%d",key,(int)status);
}
}
+ (NSData *) getData: (NSString *)key {
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [key dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:#"VPN" forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[dict setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnPersistentRef];
CFTypeRef result = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)dict,&result);
if( status != errSecSuccess) {
NSLog(#"Unable to fetch item for key %# with error:%d",key,(int)status);
return nil;
}
NSData *resultData = (__bridge NSData *)result;
return resultData;
}

createKeychainValue from a NSString

I'm trying to add a certificate to the keychain. I saw several posts that make this from a file, but I want to create one from a NSString.
My NSString is on RSA - 64base and is like:
-----BEGIN CERTIFICATE-----
MIIDoDCCAoigAwIBAgIJAL8qgXMVVVhPMA0GCSqGSIb3DQEBBQUAMGwxCzAJBgNVBAYTAkJSMRIw
...
FT70at8bty9ocDaXuI3j6mfw2SI=
-----END CERTIFICATE-----
And I'm trying to do something like this:
+ (NSMutableDictionary *)newSearchDictionary:(NSString *)identifier {
NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];
[searchDictionary setObject:(__bridge id)kSecClassCertificate forKey:(__bridge id)kSecClass];
NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
[searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric];
[searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount];
[searchDictionary setObject:SERVICE_NAME forKey:(__bridge id)kSecAttrService];
return searchDictionary;
}
+ (BOOL)createKeychainValue:(NSString *)certificado forIdentifier:(NSString *)identifier {
NSMutableDictionary *dictionary = [self newSearchDictionary:identifier];
NSData *certificadoData = [certificado dataUsingEncoding:NSUTF8StringEncoding];
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificadoData);
[dictionary setObject:(__bridge id)(cert) forKey:(__bridge id<NSCopying>)(kSecValueRef)];
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);
CFRelease(cert);
if (status == errSecSuccess) {
return YES;
}
return NO;
}
But is getting back the cert as nil. Probably because my certificate is PEM and I need a DER. How can I convert? I'm using openssl on my project.
The function that works for me and created the SecCertificateRef was:
+ (NSData *)derFromPem:(NSString *)pem {
BIO *certBio = BIO_new(BIO_s_mem());
BIO_write(certBio, [pem UTF8String], strlen([pem UTF8String]));
X509 *x = PEM_read_bio_X509(certBio,NULL,0,NULL);
BIO *outBio = BIO_new(BIO_s_mem());
i2d_X509_bio(outBio, x);
int len = BIO_pending(outBio);
char *out = calloc(len + 1, 1);
int i = BIO_read(outBio, out, len);
return [NSData dataWithBytes:out length:i];
}
Convert RSA public key from PEM to DER:
UPDATE
- (NSData *)derFromPem:(NSString *)pem
{
if (pem.length == 0) {
return nil;
}
NSData *result = nil;
const char *pem_str = [pem UTF8String];
BIO *bio;
RSA *rsa;
// X509 *x509;
bio = BIO_new_mem_buf(pem_str, strlen(pem_str));
if (bio) {
rsa = PEM_read_bio_RSAPublicKey(bio, &rsa, NULL, NULL);
// x509 = PEM_read_bio_X509(bio, &x509, NULL/*password*/, NULL);
if (rsa) { // or if (x509)
uint8_t *buf, *bufp;
int len = i2d_RSAPublicKey(rsa, NULL);
// int len = i2d_X509(x509, NULL);
if (len >= 0) {
buf = bufp = malloc(len);
i2d_RSAPublicKey(rsa, &bufp);
// i2d_X509(x509, &bufp);
}
if (len >= 0) {
result = [NSData dataWithBytes:buf length:len];
free(buf);
}
RSA_free(rsa);
// X509_free(x509);
}
BIO_free(bio);
}
return result;
}

Keychain Access Not Returning kSecValueData

I'm using the following code:
+ (void)createKeychainItem:(NSString *)name
{
// Don't create if one already exists
if ([self getKeychainItem:name] != nil) return;
NSData *encodedName = [name dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *attributes = #{
(id)kSecAttrAccount : encodedName,
(id)kSecAttrGeneric : encodedName,
(id)kSecAttrLabel : name,
(id)kSecAttrService : name,
(id)kSecClass : (id)kSecClassGenericPassword,
};
OSStatus result = SecItemAdd((CFDictionaryRef)attributes, NULL);
}
+ (NSDictionary *)getKeychainItem:(NSString *)name
{
// Build the query
NSData *encodedName = [name dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *query = #{
(id)kSecAttrAccount : encodedName,
(id)kSecAttrGeneric : encodedName,
(id)kSecAttrService : name,
(id)kSecClass : (id)kSecClassGenericPassword,
(id)kSecMatchLimit : (id)kSecMatchLimitOne,
(id)kSecReturnAttributes : (id)kCFBooleanTrue,
};
NSDictionary *output = nil;
OSStatus result = SecItemCopyMatching((CFDictionaryRef)query, (CFTypeRef *)&output);
// Convert the password if it exists
NSData *passwordData = [output objectForKey:kSecValueData];
if (passwordData != nil) {
NSMutableDictionary *mutableOutput = [[output mutableCopy] autorelease];
NSString *password = [[[NSString alloc] initWithBytes:passwordData length:passwordData.length encoding:NSUTF8StringEncoding] autorelease];
[mutableOutput setObject:password forKey:(id)kSecValueData];
output = [[mutableOutput copy] autorelease];
}
return output;
}
+ (void)updateKeychainItem:(NSString *)name value:(NSString *)value attribute:(id)attribute
{
// Get the item
NSDictionary *values = [self getKeychainItem:name];
// If we got nothing back, build it
if (values == nil) {
[self createKeychainItem:name];
}
// Create a query to update
NSData *encodedName = [name dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *query = #{
(id)kSecAttrAccount : encodedName,
(id)kSecAttrGeneric : encodedName,
(id)kSecAttrService : name,
(id)kSecClass : (id)kSecClassGenericPassword,
};
NSDictionary *attributes = nil;
if (attribute == kSecValueData) {
attributes = #{ (id)kSecValueData : [value dataUsingEncoding:NSUTF8StringEncoding] };
} else {
attributes = #{ attribute : value };
}
OSStatus result = SecItemUpdate((CFDictionaryRef)query, (CFDictionaryRef)attributes);
}
Setting a value with [self updateKeychainItem:AuthTokenIdentifer value:authToken attribute:kSecValueData]; works and I can see it in Keychain Access.
Fetching the results with NSDictionary *values = [self getKeychainItem:AuthTokenIdentifer]; works, but the kSecValueData is not set in the dictionary. Everything else is set, like the create and modified dates, just not the secure data.
Any ideas? This happens on iOS and Mac.
You need to use the attributes dictionary from getKeychainItem: to fetch the value. Something like
NSMutableDictionary *dataQuery = [attrs mutableCopy];
[dataQuery setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[dataQuery setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
CFTypeRef resultData;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)(dataQuery), &resultData);
NSData *tokenData = CFBridgingRelease(resultData);

RSA implementations in Objective C

I am working on a simple app in objective-C that uses RSA Algorithm. I want to use it on Server/Client Communications. I need help in RSA Algorithm Implementation in iOS/iPhone.
I have knowledge of encryption and decryption.
I want an opensource library or code to add into my project.
I have to go though CommonCryptor.h.
I have tried RSA Encryption and Decryption for NSString. Here is the code:
Add Security.Framework to your project bundle.
ViewController.h code is as follows:
#import <UIKit/UIKit.h>
#import <Security/Security.h>
#interface ViewController : UIViewController
{
SecKeyRef publicKey;
SecKeyRef privateKey;
NSData *publicTag;
NSData *privateTag;
}
- (void)encryptWithPublicKey:(uint8_t *)plainBuffer cipherBuffer:(uint8_t *)cipherBuffer;
- (void)decryptWithPrivateKey:(uint8_t *)cipherBuffer plainBuffer:(uint8_t *)plainBuffer;
- (SecKeyRef)getPublicKeyRef;
- (SecKeyRef)getPrivateKeyRef;
- (void)testAsymmetricEncryptionAndDecryption;
- (void)generateKeyPair:(NSUInteger)keySize;
#end
ViewController.m file code is as follows:
#import "ViewController.h"
const size_t BUFFER_SIZE = 64;
const size_t CIPHER_BUFFER_SIZE = 1024;
const uint32_t PADDING = kSecPaddingNone;
static const UInt8 publicKeyIdentifier[] = "com.apple.sample.publickey";
static const UInt8 privateKeyIdentifier[] = "com.apple.sample.privatekey";
#implementation ViewController
-(SecKeyRef)getPublicKeyRef {
OSStatus sanityCheck = noErr;
SecKeyRef publicKeyReference = NULL;
if (publicKeyReference == NULL) {
[self generateKeyPair:512];
NSMutableDictionary *queryPublicKey = [[NSMutableDictionary alloc] init];
// Set the public key query dictionary.
[queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// Get the key.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference);
if (sanityCheck != noErr)
{
publicKeyReference = NULL;
}
// [queryPublicKey release];
} else { publicKeyReference = publicKey; }
return publicKeyReference; }
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)testAsymmetricEncryptionAndDecryption {
uint8_t *plainBuffer;
uint8_t *cipherBuffer;
uint8_t *decryptedBuffer;
const char inputString[] = "This is a test demo for RSA Implementation in Objective C";
int len = strlen(inputString);
// TODO: this is a hack since i know inputString length will be less than BUFFER_SIZE
if (len > BUFFER_SIZE) len = BUFFER_SIZE-1;
plainBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));
cipherBuffer = (uint8_t *)calloc(CIPHER_BUFFER_SIZE, sizeof(uint8_t));
decryptedBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));
strncpy( (char *)plainBuffer, inputString, len);
NSLog(#"init() plainBuffer: %s", plainBuffer);
//NSLog(#"init(): sizeof(plainBuffer): %d", sizeof(plainBuffer));
[self encryptWithPublicKey:(UInt8 *)plainBuffer cipherBuffer:cipherBuffer];
NSLog(#"encrypted data: %s", cipherBuffer);
//NSLog(#"init(): sizeof(cipherBuffer): %d", sizeof(cipherBuffer));
[self decryptWithPrivateKey:cipherBuffer plainBuffer:decryptedBuffer];
NSLog(#"decrypted data: %s", decryptedBuffer);
//NSLog(#"init(): sizeof(decryptedBuffer): %d", sizeof(decryptedBuffer));
NSLog(#"====== /second test =======================================");
free(plainBuffer);
free(cipherBuffer);
free(decryptedBuffer);
}
/* Borrowed from:
* https://developer.apple.com/library/mac/#documentation/security/conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html
*/
- (void)encryptWithPublicKey:(uint8_t *)plainBuffer cipherBuffer:(uint8_t *)cipherBuffer
{
NSLog(#"== encryptWithPublicKey()");
OSStatus status = noErr;
NSLog(#"** original plain text 0: %s", plainBuffer);
size_t plainBufferSize = strlen((char *)plainBuffer);
size_t cipherBufferSize = CIPHER_BUFFER_SIZE;
NSLog(#"SecKeyGetBlockSize() public = %lu", SecKeyGetBlockSize([self getPublicKeyRef]));
// Error handling
// Encrypt using the public.
status = SecKeyEncrypt([self getPublicKeyRef],
PADDING,
plainBuffer,
plainBufferSize,
&cipherBuffer[0],
&cipherBufferSize
);
NSLog(#"encryption result code: %ld (size: %lu)", status, cipherBufferSize);
NSLog(#"encrypted text: %s", cipherBuffer);
}
- (void)decryptWithPrivateKey:(uint8_t *)cipherBuffer plainBuffer:(uint8_t *)plainBuffer
{
OSStatus status = noErr;
size_t cipherBufferSize = strlen((char *)cipherBuffer);
NSLog(#"decryptWithPrivateKey: length of buffer: %lu", BUFFER_SIZE);
NSLog(#"decryptWithPrivateKey: length of input: %lu", cipherBufferSize);
// DECRYPTION
size_t plainBufferSize = BUFFER_SIZE;
// Error handling
status = SecKeyDecrypt([self getPrivateKeyRef],
PADDING,
&cipherBuffer[0],
cipherBufferSize,
&plainBuffer[0],
&plainBufferSize
);
NSLog(#"decryption result code: %ld (size: %lu)", status, plainBufferSize);
NSLog(#"FINAL decrypted text: %s", plainBuffer);
}
- (SecKeyRef)getPrivateKeyRef {
OSStatus resultCode = noErr;
SecKeyRef privateKeyReference = NULL;
// NSData *privateTag = [NSData dataWithBytes:#"ABCD" length:strlen((const char *)#"ABCD")];
// if(privateKey == NULL) {
[self generateKeyPair:512];
NSMutableDictionary * queryPrivateKey = [[NSMutableDictionary alloc] init];
// Set the private key query dictionary.
[queryPrivateKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPrivateKey setObject:privateTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPrivateKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPrivateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// Get the key.
resultCode = SecItemCopyMatching((__bridge CFDictionaryRef)queryPrivateKey, (CFTypeRef *)&privateKeyReference);
NSLog(#"getPrivateKey: result code: %ld", resultCode);
if(resultCode != noErr)
{
privateKeyReference = NULL;
}
// [queryPrivateKey release];
// } else {
// privateKeyReference = privateKey;
// }
return privateKeyReference;
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
privateTag = [[NSData alloc] initWithBytes:privateKeyIdentifier length:sizeof(privateKeyIdentifier)];
publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
[self testAsymmetricEncryptionAndDecryption];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (void)generateKeyPair:(NSUInteger)keySize {
OSStatus sanityCheck = noErr;
publicKey = NULL;
privateKey = NULL;
// LOGGING_FACILITY1( keySize == 512 || keySize == 1024 || keySize == 2048, #"%d is an invalid and unsupported key size.", keySize );
// First delete current keys.
// [self deleteAsymmetricKeys];
// Container dictionaries.
NSMutableDictionary * privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * keyPairAttr = [[NSMutableDictionary alloc] init];
// Set top level dictionary for the keypair.
[keyPairAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithUnsignedInteger:keySize] forKey:(__bridge id)kSecAttrKeySizeInBits];
// Set the private key dictionary.
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag forKey:(__bridge id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set the public key dictionary.
[publicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set attributes to top level dictionary.
[keyPairAttr setObject:privateKeyAttr forKey:(__bridge id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr forKey:(__bridge id)kSecPublicKeyAttrs];
// SecKeyGeneratePair returns the SecKeyRefs just for educational purposes.
sanityCheck = SecKeyGeneratePair((__bridge CFDictionaryRef)keyPairAttr, &publicKey, &privateKey);
// LOGGING_FACILITY( sanityCheck == noErr && publicKey != NULL && privateKey != NULL, #"Something really bad went wrong with generating the key pair." );
if(sanityCheck == noErr && publicKey != NULL && privateKey != NULL)
{
NSLog(#"Successful");
}
// [privateKeyAttr release];
// [publicKeyAttr release];
// [keyPairAttr release];
}
#end
Here is where I originally posted my answer : Iphone - How to encrypt NSData with public key and decrypt with private key?
Let me know if you need more help.
Hope this helps.
It's very cool!
However i think it should not be a subclass of a UIViewController, but an NSObject, i changed and it works for me, here it is:
NOTE: ALL WORK IS THANKED TO #Parth Bath
RSAManager.h
#interface RSAManager : NSObject
{
SecKeyRef publicKey;
SecKeyRef privateKey;
NSData *publicTag;
NSData *privateTag;
}
- (void)encryptWithPublicKey:(uint8_t *)plainBuffer cipherBuffer:(uint8_t *)cipherBuffer;
- (void)decryptWithPrivateKey:(uint8_t *)cipherBuffer plainBuffer:(uint8_t *)plainBuffer;
- (SecKeyRef)getPublicKeyRef;
- (SecKeyRef)getPrivateKeyRef;
- (void)testAsymmetricEncryptionAndDecryption;
- (void)generateKeyPair:(NSUInteger)keySize;
#end
RSAManager.m
#import "RSAManager.h"
const size_t BUFFER_SIZE = 64;
const size_t CIPHER_BUFFER_SIZE = 1024;
const uint32_t PADDING = kSecPaddingNone;
static const UInt8 publicKeyIdentifier[] = "com.apple.sample.publickey";
static const UInt8 privateKeyIdentifier[] = "com.apple.sample.privatekey";
#implementation RSAManager
- (id)init
{
self = [super init];
if(self) {
privateTag = [[NSData alloc] initWithBytes:privateKeyIdentifier length:sizeof(privateKeyIdentifier)];
publicTag = [[NSData alloc] initWithBytes:publicKeyIdentifier length:sizeof(publicKeyIdentifier)];
[self testAsymmetricEncryptionAndDecryption];
}
return self;
}
-(SecKeyRef)getPublicKeyRef {
OSStatus sanityCheck = noErr;
SecKeyRef publicKeyReference = NULL;
if (publicKeyReference == NULL) {
[self generateKeyPair:512];
NSMutableDictionary *queryPublicKey = [[NSMutableDictionary alloc] init];
// Set the public key query dictionary.
[queryPublicKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPublicKey setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPublicKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPublicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// Get the key.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&publicKeyReference);
if (sanityCheck != noErr)
{
publicKeyReference = NULL;
}
// [queryPublicKey release];
} else { publicKeyReference = publicKey; }
return publicKeyReference;
}
- (void)testAsymmetricEncryptionAndDecryption {
uint8_t *plainBuffer;
uint8_t *cipherBuffer;
uint8_t *decryptedBuffer;
const char inputString[] = "This is a test demo for RSA Implementation in Objective C";
int len = strlen(inputString);
// TODO: this is a hack since i know inputString length will be less than BUFFER_SIZE
if (len > BUFFER_SIZE) len = BUFFER_SIZE-1;
plainBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));
cipherBuffer = (uint8_t *)calloc(CIPHER_BUFFER_SIZE, sizeof(uint8_t));
decryptedBuffer = (uint8_t *)calloc(BUFFER_SIZE, sizeof(uint8_t));
strncpy( (char *)plainBuffer, inputString, len);
NSLog(#"init() plainBuffer: %s", plainBuffer);
//NSLog(#"init(): sizeof(plainBuffer): %d", sizeof(plainBuffer));
[self encryptWithPublicKey:(UInt8 *)plainBuffer cipherBuffer:cipherBuffer];
NSLog(#"encrypted data: %s", cipherBuffer);
//NSLog(#"init(): sizeof(cipherBuffer): %d", sizeof(cipherBuffer));
[self decryptWithPrivateKey:cipherBuffer plainBuffer:decryptedBuffer];
NSLog(#"decrypted data: %s", decryptedBuffer);
//NSLog(#"init(): sizeof(decryptedBuffer): %d", sizeof(decryptedBuffer));
NSLog(#"====== /second test =======================================");
free(plainBuffer);
free(cipherBuffer);
free(decryptedBuffer);
}
/* Borrowed from:
* https://developer.apple.com/library/mac/#documentation/security/conceptual/CertKeyTrustProgGuide/iPhone_Tasks/iPhone_Tasks.html
*/
- (void)encryptWithPublicKey:(uint8_t *)plainBuffer cipherBuffer:(uint8_t *)cipherBuffer
{
NSLog(#"== encryptWithPublicKey()");
OSStatus status = noErr;
NSLog(#"** original plain text 0: %s", plainBuffer);
size_t plainBufferSize = strlen((char *)plainBuffer);
size_t cipherBufferSize = CIPHER_BUFFER_SIZE;
NSLog(#"SecKeyGetBlockSize() public = %lu", SecKeyGetBlockSize([self getPublicKeyRef]));
// Error handling
// Encrypt using the public.
status = SecKeyEncrypt([self getPublicKeyRef],
PADDING,
plainBuffer,
plainBufferSize,
&cipherBuffer[0],
&cipherBufferSize
);
NSLog(#"encryption result code: %ld (size: %lu)", status, cipherBufferSize);
NSLog(#"encrypted text: %s", cipherBuffer);
}
- (void)decryptWithPrivateKey:(uint8_t *)cipherBuffer plainBuffer:(uint8_t *)plainBuffer
{
OSStatus status = noErr;
size_t cipherBufferSize = strlen((char *)cipherBuffer);
NSLog(#"decryptWithPrivateKey: length of buffer: %lu", BUFFER_SIZE);
NSLog(#"decryptWithPrivateKey: length of input: %lu", cipherBufferSize);
// DECRYPTION
size_t plainBufferSize = BUFFER_SIZE;
// Error handling
status = SecKeyDecrypt([self getPrivateKeyRef],
PADDING,
&cipherBuffer[0],
cipherBufferSize,
&plainBuffer[0],
&plainBufferSize
);
NSLog(#"decryption result code: %ld (size: %lu)", status, plainBufferSize);
NSLog(#"FINAL decrypted text: %s", plainBuffer);
}
- (SecKeyRef)getPrivateKeyRef {
OSStatus resultCode = noErr;
SecKeyRef privateKeyReference = NULL;
// NSData *privateTag = [NSData dataWithBytes:#"ABCD" length:strlen((const char *)#"ABCD")];
// if(privateKey == NULL) {
[self generateKeyPair:512];
NSMutableDictionary * queryPrivateKey = [[NSMutableDictionary alloc] init];
// Set the private key query dictionary.
[queryPrivateKey setObject:(__bridge id)kSecClassKey forKey:(__bridge id)kSecClass];
[queryPrivateKey setObject:privateTag forKey:(__bridge id)kSecAttrApplicationTag];
[queryPrivateKey setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[queryPrivateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
// Get the key.
resultCode = SecItemCopyMatching((__bridge CFDictionaryRef)queryPrivateKey, (CFTypeRef *)&privateKeyReference);
NSLog(#"getPrivateKey: result code: %ld", resultCode);
if(resultCode != noErr)
{
privateKeyReference = NULL;
}
// [queryPrivateKey release];
// } else {
// privateKeyReference = privateKey;
// }
return privateKeyReference;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (void)generateKeyPair:(NSUInteger)keySize {
OSStatus sanityCheck = noErr;
publicKey = NULL;
privateKey = NULL;
// LOGGING_FACILITY1( keySize == 512 || keySize == 1024 || keySize == 2048, #"%d is an invalid and unsupported key size.", keySize );
// First delete current keys.
// [self deleteAsymmetricKeys];
// Container dictionaries.
NSMutableDictionary * privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary * keyPairAttr = [[NSMutableDictionary alloc] init];
// Set top level dictionary for the keypair.
[keyPairAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithUnsignedInteger:keySize] forKey:(__bridge id)kSecAttrKeySizeInBits];
// Set the private key dictionary.
[privateKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecAttrIsPermanent];
[privateKeyAttr setObject:privateTag forKey:(__bridge id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set the public key dictionary.
[publicKeyAttr setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecAttrIsPermanent];
[publicKeyAttr setObject:publicTag forKey:(__bridge id)kSecAttrApplicationTag];
// See SecKey.h to set other flag values.
// Set attributes to top level dictionary.
[keyPairAttr setObject:privateKeyAttr forKey:(__bridge id)kSecPrivateKeyAttrs];
[keyPairAttr setObject:publicKeyAttr forKey:(__bridge id)kSecPublicKeyAttrs];
// SecKeyGeneratePair returns the SecKeyRefs just for educational purposes.
sanityCheck = SecKeyGeneratePair((__bridge CFDictionaryRef)keyPairAttr, &publicKey, &privateKey);
// LOGGING_FACILITY( sanityCheck == noErr && publicKey != NULL && privateKey != NULL, #"Something really bad went wrong with generating the key pair." );
if(sanityCheck == noErr && publicKey != NULL && privateKey != NULL)
{
NSLog(#"Successful");
}
// [privateKeyAttr release];
// [publicKeyAttr release];
// [keyPairAttr release];
}
#end

Resources