我有一个Base64公钥,是使用Java代码生成的:
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
方法。
我可以使用这段代码在iOS中使用Base64字符串,将其添加到密钥链中,然后再次检索它作为SecKeyRef
,但我非常不想只为了使用一次就将证书添加到密钥链中。
经过一些研究,似乎我应该能够使用SecCertificateCreateWithData
从我拥有的Base64字符串创建一个在iOS中使用的证书,但是当我使用此代码时,我总是得到一个空的证书:
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);
}
}
SecKeyRef
而不是一个SecCertificateRef
?SecCertificateCreateWithData
要求数据是“X.509证书的DER(Distinguished Encoding Rules)表示”。 - Joshua-[SecKeyWrapper addPeerPublicKey:keyBits:]
方法。 - JoshuaNSData *certData = [[NSData alloc] initWithBase64EncodedString:pespublickey options:0];
。 - jrtc27