我有一个由 java 使用以下代码生成的 base64 公钥:
RSAPublicKeySpec rsaKS = new RSAPublicKeySpec(modulus, pubExponent);
RSAPublicKey rsaPubKey = (RSAPublicKey) kf.generatePublic(rsaKS);
byte[] encoded = rsaPubKey.getEncoded();
String base64 = Base64.encodeToString(encoded, Base64.DEFAULT);
Log.e(null, "base64: " + base64);
这会生成 Base64 字符串。
在 OSX 中,我可以使用以下代码获取 SecKeyRef:
// Create the SecKeyRef using the key data
CFErrorRef error = NULL;
CFMutableDictionaryRef parameters = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, NULL, NULL);
CFDictionarySetValue(parameters, kSecAttrKeyType, kSecAttrKeyTypeRSA);
CFDictionarySetValue(parameters, kSecAttrKeyClass, kSecAttrKeyClassPublic);
SecKeyRef keyRef = SecKeyCreateFromData(parameters, (__bridge CFDataRef)[pubKey base64DecodedData], &error);
然而在iOS中没有SecKeyCreateFromData
method.
我可以在 iOS 中使用 Base64 字符串这段代码 http://blog.flirble.org/2011/01/05/rsa-public-key-openssl-ios/它将它添加到钥匙串中,然后再次检索它作为SecKeyRef
不过,我宁愿不必将证书添加到钥匙串中,只是为了能够检索它并使用它一次。
做了一些研究,看来我应该能够使用SecCertificateCreateWithData
从我拥有的 Base64 字符串创建一个在 iOS 中使用的证书,但是在使用此代码时我总是得到一个 NULL 证书:
NSString* pespublicKey = @"MIGfMA0GCSqGSIb3....DCUdz/y4B2sf+q5n+QIDAQAB";
NSData* certData = [pespublicKey dataUsingEncoding:NSUTF8StringEncoding];
SecCertificateRef cert;
if ([certData length]) {
cert = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)certData);
if (cert != NULL) {
CFStringRef certSummary = SecCertificateCopySubjectSummary(cert);
NSString* summaryString = [[NSString alloc] initWithString:(__bridge NSString*)certSummary];
NSLog(@"CERT SUMMARY: %@", summaryString);
CFRelease(certSummary);
} else {
NSLog(@" *** ERROR *** trying to create the SSL certificate from data located at %@, but failed", pespublicKey);
}
}