我使用SecKeyGeneratePair方法生成了RSA密钥对,并使用这些密钥,我可以进行加密/解密,数字签名并在iOS应用程序中进行验证。
现在的挑战是我需要将公钥(SecKeyRef)作为base64string格式发送到Java服务器,在java中我必须使用iOS字符串(base64)重建公钥。
我将SecKeyRef转换为NSData到base64string(总是得到相同的字符串),同时将它转移到服务器。使用base64string我无法在Java中重建公钥。我在下面提到了用于生成RSA公钥和私钥的用过的代码。
static const UInt8 publicKeyIdentifier[] = "com.apple.sample.publickey\0";
static const UInt8 privateKeyIdentifier[]= "com.apple.sample.privatekey\0";
- (void)generateKeyPairPlease{
OSStatus status = noErr;
publicKeyBits=nil;
NSMutableDictionary *privateKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary *publicKeyAttr = [[NSMutableDictionary alloc] init];
NSMutableDictionary *keyPairAttr = [[NSMutableDictionary alloc] init];
publicTag = [NSData dataWithBytes:publicKeyIdentifier length:strlen((const char *)publicKeyIdentifier)];
privateTag = [NSData dataWithBytes:privateKeyIdentifier length:strlen((const char *)privateKeyIdentifier)];
publicKey = NULL;
privateKey = NULL;
[keyPairAttr setObject:(__bridge id)kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[keyPairAttr setObject:[NSNumber numberWithInt:1024] 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);
}
- (NSData *)getPublicKeyBits {
OSStatus sanityCheck = noErr;
CFDataRef keyBits;
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)kSecReturnData];
// Get the key bits.
sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef)queryPublicKey, (CFTypeRef *)&keyBits);
publicKeyBits =(__bridge_transfer NSData*)keyBits;
if (sanityCheck != noErr)
{
publicKeyBits = nil;
}
NSLog(@"Bits are %@",publicKeyBits);
return publicKeyBits;//every time I am getting same data here
}