Printing SecKeyRef reference using NSLog in Objective-C - ios

I am retrieving public key from a certificate with the following code.
- (SecKeyRef) extractPublicKeyFromCertificate: (SecIdentityRef) identity {
// Get the certificate from the identity.
SecCertificateRef myReturnedCertificate = NULL;
OSStatus status = SecIdentityCopyCertificate (identity,
&myReturnedCertificate);
if (status) {
NSLog(#"SecIdentityCopyCertificate failed.\n");
return NULL;
}
SecKeyRef publickey;
SecCertificateCopyPublicKey(myReturnedCertificate, &publickey);
NSLog(#"%#", publickey);
return publickey;
}
I am trying to print the "publickey" variable to see the contents. I am getting runtime error. I would like to know how to print the contents of the "publickey" variable?

Related

OSX Generated key can't encrypt (SecKeyCreateRandomKey & SecKeyCreateEncryptedData)

I am basically follow this guide to generated a private key, copy the public key, and then encrypt a message. However, it gives me the error (OSStatus error -67712 - CSSM Exception: -2147415791 CSSMERR_CSP_INVALID_KEY_REFERENCE).
Initially, I thought I set the attributes incorrectly. However, if I create the public key (with the same attributes) by the SecKeyGeneratePair() function, everything works perfectly. Is it weird?
void TestEncryptDecrpt() {
OSStatus status;
NSData* tag = [#"com.example.keys.mykey" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* attributes =
#{ (id)kSecAttrKeyType: (id)kSecAttrKeyTypeRSA,
(id)kSecAttrKeySizeInBits: #1024,
(id)kSecPrivateKeyAttrs:
#{ (id)kSecAttrIsPermanent: #YES,
(id)kSecAttrApplicationTag: tag,
},
};
CFErrorRef error = NULL;
SecKeyRef privateKey = SecKeyCreateRandomKey((__bridge CFDictionaryRef)attributes, &error);
SecKeyRef publicKey = SecKeyCopyPublicKey(privateKey);
// *** it will work if I generate the key by SecKeyGeneratePair ***
// status = SecKeyGeneratePair( (__bridge CFDictionaryRef)attributes, &publicKey, &privateKey );
// start encrypt and decrypt a message
static char const kMessage[] = "This is a secret!\n";
SecKeyAlgorithm algorithm = kSecKeyAlgorithmRSAEncryptionRaw;
BOOL canEncrypt = SecKeyIsAlgorithmSupported(publicKey, kSecKeyOperationTypeEncrypt, algorithm);
NSData* plainData = [NSData dataWithBytes:kMessage length:sizeof(kMessage)];
canEncrypt &= ([plainData length] < (SecKeyGetBlockSize(publicKey)-130));
NSData* cipherText = nil;
if (canEncrypt) {
CFErrorRef error = NULL;
cipherText = (NSData*)CFBridgingRelease( SecKeyCreateEncryptedData(publicKey, algorithm, (__bridge CFDataRef)plainData, &error));
if (!cipherText) {
NSError *err = CFBridgingRelease(error); // ARC takes ownership
// Handle the error. . .
NSLog(#"error = %#, %#", [err userInfo], [err localizedDescription]);
}
}
}
Problem solved. You need the "kSecAttrIsPermanent" property as well in the public key setting.
Not sure why this is not mentioned in the example.

Get public/private key from certificate

I try to get public or private key from certificate saved on device.
I'm using this method:
- (SecKeyRef)publicKeyFromFile:(NSString *)path
{
NSData * certificateData = [[NSData alloc] initWithData:[[NSFileManager defaultManager] contentsAtPath:path]];
if (certificateData != nil && certificateData.bytes != 0) {
CFDataRef cfDataPath = CFDataCreate(NULL, [certificateData bytes], [certificateData length]);
SecCertificateRef certificateFromFile = SecCertificateCreateWithData(NULL, cfDataPath);
if (certificateFromFile) {
SecPolicyRef secPolicy = SecPolicyCreateBasicX509();
SecTrustRef trust;
SecTrustCreateWithCertificates( certificateFromFile, secPolicy, &trust);
SecTrustResultType resultType;
SecTrustEvaluate(trust, &resultType);
SecKeyRef publicKeyObj = SecTrustCopyPublicKey(trust);
return publicKeyObj;
}
}
return nil;
}
There is data in cfDataPath, but certificateFromFile is always nil...
Does anyone know where's the problem?
Apple doc refers:
Obtaining a SecKeyRef Object for Public Key Cryptography
Extracting Keys from the Keychain If you are using existing public and private keys from your keychain, read Certificate, Key, and Trust Services Programming Guide to learn how to retrieve a SecKeychainItemRef object for that key.
Once you have obtained a SecKeychainItemRef, you can cast it to a SecKeyRef for use with this API.
Importing Existing Public and Private Keys Importing and exporting public and private key pairs is somewhat more complicated than generating new keys because of the number of different key formats in common use.
This example describes how to import and export a key pair in PEM (Privacy Enhanced Mail) format.
Read more : https://developer.apple.com/library/mac/documentation/Security/Conceptual/SecTransformPG/SigningandVerifying/SigningandVerifying.html and https://developer.apple.com/library/mac/documentation/Security/Conceptual/CertKeyTrustProgGuide/01introduction/introduction.html#//apple_ref/doc/uid/TP40001358
Try with this:
-(BOOL)trustCertFromChallenge:(NSURLAuthenticationChallenge *)challenge
{
SecTrustResultType trustResult;
SecTrustRef trust = challenge.protectionSpace.serverTrust;
OSStatus status = SecTrustEvaluate(trust, &trustResult);
//DLog(#"Failed: %#",error.localizedDescription);
//DLog(#"Status: %li | Trust: %# - %li",(long)status,trust,(long)trustResult);
if (status == 0 && (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed)) {
SecKeyRef serverKey = SecTrustCopyPublicKey(trust);
NSString *certPath = [[NSBundle mainBundle] pathForResource:#"MYCert" ofType:#"der"];
NSData *certData = [NSData dataWithContentsOfFile:certPath];
SecCertificateRef localCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)certData);
SecKeyRef localKey = NULL;
SecTrustRef localTrust = NULL;
SecCertificateRef certRefs[1] = {localCertificate};
CFArrayRef certArray = CFArrayCreate(kCFAllocatorDefault, (void *)certRefs, 1, NULL);
SecPolicyRef policy = SecPolicyCreateBasicX509();
OSStatus status = SecTrustCreateWithCertificates(certArray, policy, &localTrust);
if (status == errSecSuccess)
localKey = SecTrustCopyPublicKey(localTrust);
CFRelease(localTrust);
CFRelease(policy);
CFRelease(certArray);
if (serverKey != NULL && localKey != NULL && [(__bridge id)serverKey isEqual:(__bridge id)localKey])
return YES;
else
return NO;
}
//DLog(#"Failed: %#",error.localizedDescription);
return NO;
}
Follow the accepted answer for more details: Objective-C / C pulling private key (modulus) from SecKeyRef

RSA/ECB/PKCS1Padding iOS encryption

I am currently stuck at a problem which involves encryption in iOS.
My client has given me the public key,
"-----BEGIN PUBLIC KEY-----
xxxx
-----END PUBLIC KEY-----"
The padding strategy that needs to be used is RSA/ECB/PKCS1Padding.
With android, it seems pretty straight forward
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
return encryptedBytes;
I dont see any direct methods to do this in iOS. Any of the common pods used like Commoncrypto doesnt allow me to force PKCS1 padding scheme. Being a pretty inexperienced guy with RSA and encryption, it would be very much appreciated if you could help me understand on how to approach this and guide me through this.
Using standard Security Framework - SecKeyEncrypt with kSecPaddingPKCS1 parameter
My issue was solved using non padding :
kSecPaddingNone
-(SecKeyRef)getPublicKeyForEncryption
{
NSString *thePath = [MAuthBundle pathForResource:#"certificate" ofType:#"der"];
//2. Get the contents of the certificate and load to NSData
NSData *certData = [[NSData alloc]
initWithContentsOfFile:thePath];
//3. Get CFDataRef of the certificate data
CFDataRef myCertData = (__bridge CFDataRef)certData;
SecCertificateRef myCert;
SecKeyRef aPublicKeyRef = NULL;
SecTrustRef aTrustRef = NULL;
//4. Create certificate with the data
myCert = SecCertificateCreateWithData(NULL, myCertData);
//5. Returns a policy object for the default X.509 policy
SecPolicyRef aPolicyRef = SecPolicyCreateBasicX509();
if (aPolicyRef) {
if (SecTrustCreateWithCertificates((CFTypeRef)myCert, aPolicyRef, &aTrustRef) == noErr) {
SecTrustResultType result;
if (SecTrustEvaluate(aTrustRef, &result) == noErr) {
//6. Returns the public key for a leaf certificate after it has been evaluated.
aPublicKeyRef = SecTrustCopyPublicKey(aTrustRef);
}
}
}
return aPublicKeyRef;
}
-(NSString*) rsaEncryptString:(NSString*) string
{
SecKeyRef publicKey = [self getPublicKeyForEncryption];
NSData* strData = [string dataUsingEncoding:NSUTF8StringEncoding];
CFErrorRef err ;
NSData * data = CFBridgingRelease(SecKeyCreateEncryptedData(publicKey, kSecKeyAlgorithmRSAEncryptionPKCS1, ( __bridge CFDataRef)strData, &err));
NSString *base64EncodedString = [data base64EncodedStringWithOptions:0];
return base64EncodedString;
}

How to recover RSA from file?

I want to recover a public key from a file. Here is the Java code that works:
PublicKey readPubKeyFromFile(AssetFileDescriptor cle) throws IOException {
// read RSA public key
byte[] encodedKey = new byte[(int) cle.getDeclaredLength()];
cle.createInputStream().read(encodedKey);
// create public key
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
PublicKey pk = null;
try {
KeyFactory kf = KeyFactory.getInstance("RSA");
pk = kf.generatePublic(publicKeySpec);
} catch(Exception e) {
Logger.getInstance().logError("KeyUtils", e.toString());
}
return pk;
}
And here is the iOS code that doesn't work:
-(SecKeyRef)readPublicKeyFromFile:(NSString*)filename andExtension:(NSString*)extension {
NSString* filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSData* encodedKey = [NSData dataWithContentsOfFile:filePath];
CFDataRef myCertData = (CFDataRef)encodedKey;
SecCertificateRef cert = SecCertificateCreateWithData (kCFAllocatorSystemDefault, myCertData);
CFArrayRef certs = CFArrayCreate(kCFAllocatorDefault, (const void **) &cert, 1, NULL);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
OSStatus check = SecTrustCreateWithCertificates(certs, policy, &trust);
if (check != noErr)
{
NSLog(#"Problem extracting public key from file: %#", filename);
return nil;
}
SecTrustResultType trustResult;
SecTrustEvaluate(trust, &trustResult);
SecKeyRef pub_key_leaf = SecTrustCopyPublicKey(trust);
return pub_key_leaf;
}
Any idea of what is wrong in my iOS code?
I've tested your code and there is nothing wrong with it. The problem seems to be related with the format of the certificates that you are trying to get the public key.
The function SecCertificateCreateWithData() assumes that the certificate that you are providing is in DER format. Most certificates that you find are encoded in base64 like the famous .pem format. I've tested your code with a correctly formatted DER certificate (the certificate form developer.apple.com converted to DER with openssl) and the public key is correctly extracted.
To convert a .pem certificate to DER simply use openssl in terminal:
openssl x509 -in developer.apple.com.pem -outform der -out cert.der
After that the output certificate file should work with no problems with your code.
But you can convert the certificate on the application itself, you only need to grab de x509 base64 encoded certificate (assuming that you are using .pem encoded certificates) and convert it to binary.
There is an example how you can do it:
This code will assume that the certificate is encoded in the following standard:
-----BEGIN CERTIFICATE-----
< your base64 encoded certificate goes here >
-----END CERTIFICATE-----
The code to convert this certificate to binary DER is:
-(NSData *)getBinaryCertificateFromPemEncodedFile:(NSString *)filename andExtension:(NSString *)extension
{
NSString* filePath = [[NSBundle mainBundle] pathForResource:filename ofType:extension];
NSString *pemCert = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
//The header and footer conforms to .pem specificatio
NSString *header = #"-----BEGIN CERTIFICATE-----";
NSString *footer = #"-----END CERTIFICATE-----";
NSString *base64Cert;
NSScanner *scanner = [NSScanner scannerWithString:pemCert];
//First we ignore the header part
[scanner scanString:header intoString:nil];
//Then we copy the base64 string excluding the footer
[scanner scanUpToString:footer intoString:&base64Cert];
//The reason I'm using NSDataBase64DecodingIgnoreUnknownCharacters is to exclude possible line breaks in the encoding
NSData *binaryCertificate = [[NSData alloc] initWithBase64EncodedString:base64Cert options:NSDataBase64DecodingIgnoreUnknownCharacters];
return binaryCertificate;
}
Then a small adaptation in your perfectly functional code does the trick:
-(SecKeyRef)readPublicKeyFromCertificate:(NSData *)binaryCertificate {
NSData *encodedKey = binaryCertificate;
CFDataRef myCertData = (CFDataRef)CFBridgingRetain(encodedKey);
SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorSystemDefault, myCertData);
SecPolicyRef policy = SecPolicyCreateBasicX509();
SecTrustRef trust;
//If you only have one certificate you don't need to put it inside an array
OSStatus check = SecTrustCreateWithCertificates(cert, policy, &trust);
if (check != noErr)
{
NSLog(#"Problem extracting public key from certificate");
return nil;
}
SecTrustResultType trustResult;
SecTrustEvaluate(trust, &trustResult);
SecKeyRef pub_key_leaf = SecTrustCopyPublicKey(trust);
return pub_key_leaf;
}
Then just call it:
NSData *data = [self getBinaryCertificateFromPemEncodedFile:#"developer" andExtension:#"pem"];
SecKeyRef key = [self readPublicKeyFromCertificate:data];
NSLog(#"%#", key);
And if your certificate is "valid" you should see:
2014-09-15 21:52:13.275 cert[15813:60b] <SecKeyRef algorithm id: 1,
key type: RSAPublicKey, version: 2, block size: 2048 bits, exponent: {hex: 10001, decimal: 65537},
modulus: BE19E30F47F2D31F27D576CF007B3E615F986D14AFD0D52B825E01E90BA3E1CBB6F3A472E6AECDC28BC13D0B6E58FC497ACF61D80F274E4799602DA4F819E54ADDE2FBFA89FC4EB2172501DDED8DE0FBDDBC5550CC018C73E1FD8152C905DE850862B8D57596025DE1908D8337E95637AF0F52C4A11DA178FF737DCE09471BC0A49DAD7DB39F1BA1B693D3A12F9CA50EF388B50292C73076BF1EEE412A5CFA940E99D4CF07F17FAC87F0D0E2FC8FA3ACDDEEFCCE8AFEC407B94536FCB1E4ACF34773728D189F85EAE4347E0BF868D25C7CE89F8A29B4E6865C68F4F915DFA540549EE9333007145D367FE2852622AAD776F3E5D505A02E5155CC8646A01C1031,
addr: 0x9a48200>
For testing I've used the certificate from developer.apple.com, you can check the public key in the log and compare it.

get SecKeyRef from base64 coded string

I'm working on an iOS app and I get a base64 coded public key such as:
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3gn+tJ1+PbP0GHa6hmM35WsVyibpypWAwRuBYY4MGfh3VWoXgiyiLo5HJTW1eR9BUFq3z+yOG1rwzSabZ8I4zneWm0kH7xErSjNrMbmjirbL7e6TQNa1ujP/x4x9XVbqf3vIsNVs19kn/qSX/HGzd5Ct3TGAo0AT0T4JwkCfciwIDAQAB
I'd like to encode some text with this public key, but I cannot find a way to convert this string to a useful public key.
What do I need to do?
First, you must base64 decode your NSString to NSData:
See this answer for solutions. If you are developing for iOS 7, you can use initWithBase64EncodedString::options.
Once you have the string decoded as NSData, you can attempt to create a certificate from it. The format of the certificate you received matters - you can use DER (which is common) or PKCS12. You're likely to be getting it as DER, so that's what I'll assume you need guidance on.
Create a certificate and policy:
SecCertificateRef cert = NULL;
SecPolicyRef policy = NULL;
cert = SecCertificateCreateWithData(kCFAllocatorDefault, data);
policy = SecPolicyCreateBasicX509();
If the cerificate data was in an incorrect format when passed to SecCertificateCreateWithData you will get a NULL result.
At this point you have the certificate, but not the public key. To obtain the public key you must create a trust reference and evaluate the trust of the certificate.
OSStatus status = noErr;
SecKeyRef *publicKey = NULL;
SecTrustRef trust = NULL;
SecTrustResultType trustType = kSecTrustResultInvalid;
if (cert != NULL){
SecCertificateRef certArray[1] = {cert};
certs = CFArrayCreate(kCFAllocatorDefault, (void *)certArray, 1, NULL);
status = SecTrustCreateWithCertificates(certs, policy, &trust);
if (status == errSecSuccess){
status = SecTrustEvaluate(trust, &trustType);
// Evaulate the trust.
switch (trustType) {
case kSecTrustResultInvalid:
case kSecTrustResultConfirm:
case kSecTrustResultDeny:
case kSecTrustResultUnspecified:
case kSecTrustResultFatalTrustFailure:
case kSecTrustResultOtherError:
break;
case kSecTrustResultRecoverableTrustFailure:
*publicKey = SecTrustCopyPublicKey(trust);
break;
case kSecTrustResultProceed:
*publicKey = SecTrustCopyPublicKey(trust);
break;
}
}
}
If everything went well, you should now have a populated SecKeyRef with the public key. If it didn't go well, you will have a NULL SecKeyRef and an OSStatus indicating what went wrong. SecBase.h in the Security framework gives more detailed information on those error codes.
Now that you have a SecKeyRef with a public key, using it to encrypt data with a corresponding private key is covered well by the programming guide.
Note that you will have to release the things you allocated above (policy, certs) using ARC or CFRelease.

Resources