/genKey.m Secret
Created
January 20, 2017 01:40
Generate Key pair sample
This file contains 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
- (void)generateKeyAsync:(NSString *)keyName { | |
CFErrorRef error = NULL; | |
SecAccessControlRef sacObject; | |
// Should be the secret invalidated when passcode is removed? If not then use `kSecAttrAccessibleWhenUnlocked`. | |
sacObject = SecAccessControlCreateWithFlags(kCFAllocatorDefault, | |
kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly, | |
kSecAccessControlTouchIDAny | kSecAccessControlPrivateKeyUsage, &error); | |
// Create parameters dictionary for key generation. | |
NSDictionary *parameters = @{ | |
(id) kSecAttrTokenID: (id) kSecAttrTokenIDSecureEnclave, | |
(id) kSecAttrKeyType: (id) kSecAttrKeyTypeECSECPrimeRandom, | |
(id) kSecAttrKeySizeInBits: @256, | |
(id) kSecAttrLabel: keyName, | |
(id) kSecPrivateKeyAttrs: @{ | |
(id) kSecAttrAccessControl: (__bridge_transfer id) sacObject, | |
(id) kSecAttrIsPermanent: @YES, | |
} | |
}; | |
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ | |
// Generate key pair. | |
NSError *gen_error = nil; | |
id privateKey = CFBridgingRelease(SecKeyCreateRandomKey((__bridge CFDictionaryRef) parameters, (void *) &gen_error)); | |
id publicKey = CFBridgingRelease(SecKeyCopyPublicKey((SecKeyRef)privateKey)); | |
if (privateKey != nil) { | |
// use the private key in your code | |
NSString *message = [NSString stringWithFormat:@"Key: %@ was successfully generated!", keyName]; | |
NSLog(message); | |
} else { | |
NSString *message = [NSString stringWithFormat:@"Key generation error: %@ for key: %@", gen_error, keyName]; | |
NSLog(message); | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment