4

我已经使用 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
}
4

0 回答 0