解决方案RSA/None/NoPadding
好吧,所以我让它工作,但没有填充。这部分真的让我感到沮丧,我把它留给其他人来尝试帮助。也许我最终会在github上发布我作为库的东西,一个用于Obj-C,一个用于Java。以下是我迄今为止的发现。
TL;DR:使用最少的属性将密钥保存到钥匙串中,以使检索更简单。使用 进行加密,但使用 。使用BouncyCastle和算法在Java端解密。SecKeyEncrypt
kSecPaddingNone
RSA/None/NoPadding
将 RSA 公钥从 Java 发送到 iOS
使用 X.509 证书
我想验证直接发送公钥,剥离ASN.1标头并保存是否确实在做它应该做的事情。因此,我考虑将公钥作为证书发送过来。我想感谢David Benko提供了一个加密库(https://github.com/DavidBenko/DBTransitEncryption),帮助我进行了证书转换。我实际上并没有使用他的图书馆,因为1。我已经在使用/用于我的AES加密和2。他没有Java端组件,所以我需要在那里编写自己的AES解密,我不想这样做。对于那些有兴趣并希望采用这种方法的人,以下是我的代码,用于在Java端创建证书,然后将该证书转换为iOS上的公钥:RNCryptor
JNCryptor
* 重要提示:请替换为真实的日志记录语句。我只用它来测试,而不是在生产中。e.printStackTrace()
爪哇:
public static X509Certificate generateCertificate (KeyPair newKeys) {
Security.addProvider(new BouncyCastleProvider());
Date startDate = new Date();
Date expiryDate = new DateTime().plusYears(100).toDate();
BigInteger serialNumber = new BigInteger(10, new Random());
try {
ContentSigner sigGen = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(newKeys
.getPrivate());
SubjectPublicKeyInfo subjectPublicKeyInfo = new SubjectPublicKeyInfo(ASN1Sequence.getInstance(newKeys
.getPublic().getEncoded()
));
X500Name dnName = new X500Name("CN=FoodJudge API Certificate");
X509v1CertificateBuilder builder = new X509v1CertificateBuilder(dnName,
serialNumber,
startDate, expiryDate,
dnName,
subjectPublicKeyInfo);
X509CertificateHolder holder = builder.build(sigGen);
return new JcaX509CertificateConverter().setProvider("BC").getCertificate(holder);
}
catch (OperatorCreationException e) {
e.printStackTrace();
}
catch (CertificateException e) {
e.printStackTrace();
}
return null;
}
Obj-C:
- (SecKeyRef)extractPublicKeyFromCertificate:(NSData *)certificateBytes {
if (certificateBytes == nil) {
return nil;
}
SecCertificateRef certificate = SecCertificateCreateWithData(kCFAllocatorDefault, ( __bridge CFDataRef) certificateBytes);
if (certificate == nil) {
NSLog(@"Can not read certificate from data");
return false;
}
SecTrustRef trust;
SecPolicyRef policy = SecPolicyCreateBasicX509();
OSStatus returnCode = SecTrustCreateWithCertificates(certificate, policy, &trust);
// release the certificate as we're done using it
CFRelease(certificate);
// release the policy
CFRelease(policy);
if (returnCode != errSecSuccess) {
NSLog(@"SecTrustCreateWithCertificates fail. Error Code: %d", (int)returnCode);
return nil;
}
SecTrustResultType trustResultType;
returnCode = SecTrustEvaluate(trust, &trustResultType);
if (returnCode != errSecSuccess) {
// TODO log
CFRelease(trust);
return nil;
}
SecKeyRef publicKey = SecTrustCopyPublicKey(trust);
CFRelease(trust);
if (publicKey == nil) {
NSLog(@"SecTrustCopyPublicKey fail");
return nil;
}
return publicKey;
}
使用 RSA 公钥
请务必注意,您不需要将公钥作为证书发送。实际上,在发现公钥保存不正确(见下文)后,我还原了此代码并将公钥保存到我的设备中。您需要按照其中一篇博客文章中提到的条带去标题。该代码在此处重新发布(为清楚起见,已格式化)。ASN.1
+ (NSData *)stripPublicKeyHeader:(NSData *)keyBits {
// Skip ASN.1 public key header
if (keyBits == nil) {
return nil;
}
unsigned int len = [keyBits length];
if (!len) {
return nil;
}
unsigned char *c_key = (unsigned char *)[keyBits bytes];
unsigned int idx = 0;
if (c_key[idx++] != 0x30) {
return nil;
}
if (c_key[idx] > 0x80) {
idx += c_key[idx] - 0x80 + 1;
}
else {
idx++;
}
if (idx >= len) {
return nil;
}
if (c_key[idx] != 0x30) {
return nil;
}
idx += 15;
if (idx >= len - 2) {
return nil;
}
if (c_key[idx++] != 0x03) {
return nil;
}
if (c_key[idx] > 0x80) {
idx += c_key[idx] - 0x80 + 1;
}
else {
idx++;
}
if (idx >= len) {
return nil;
}
if (c_key[idx++] != 0x00) {
return nil;
}
if (idx >= len) {
return nil;
}
// Now make a new NSData from this buffer
return([NSData dataWithBytes:&c_key[idx] length:len - idx]);
}
所以我会像这样简单地保存密钥:
- (void)storeServerPublicKey:(NSString *)serverPublicKey {
if (!serverPublicKey) {
return;
}
SecKeyWrapper *secKeyWrapper = [SecKeyWrapper sharedWrapper];
NSData *decryptedServerPublicKey = [[NSData alloc] initWithBase64EncodedString:serverPublicKey options:0];
NSData *strippedServerPublicKey = [SecKeyWrapper stripPublicKeyHeader:decryptedServerPublicKey];
if (!strippedServerPublicKey) {
return;
}
[secKeyWrapper savePublicKeyToKeychain:strippedServerPublicKey tag:@"com.sampleapp.publickey"];
}
将 RSA 公钥保存到钥匙串
这太疯狂了。事实证明,即使我保存了钥匙串的钥匙,我检索到的也不是我放入的!当我将保存的 base64 密钥与用于加密 AES 密钥的 base64 密钥进行比较时,我偶然发现了这一点。因此,我发现最好简化保存密钥时使用的NSDictionary。以下是我最终得到的结果:
- (void)savePublicKeyToKeychain:(NSData *)key tag:(NSString *)tagString {
NSData *tag = [self getKeyTag:tagString];
NSDictionary *saveDict = @{
(__bridge id) kSecClass : (__bridge id) kSecClassKey,
(__bridge id) kSecAttrKeyType : (__bridge id) kSecAttrKeyTypeRSA,
(__bridge id) kSecAttrApplicationTag : tag,
(__bridge id) kSecAttrKeyClass : (__bridge id) kSecAttrKeyClassPublic,
(__bridge id) kSecValueData : key
};
[self saveKeyToKeychain:saveDict tag:tagString];
}
- (void)saveKeyToKeychain:(NSDictionary *)saveDict tag:(NSString *)tagString {
OSStatus sanityCheck = SecItemAdd((__bridge CFDictionaryRef) saveDict, NULL);
if (sanityCheck != errSecSuccess) {
if (sanityCheck == errSecDuplicateItem) {
// delete the duplicate and save again
sanityCheck = SecItemDelete((__bridge CFDictionaryRef) saveDict);
sanityCheck = SecItemAdd((__bridge CFDictionaryRef) saveDict, NULL);
}
if (sanityCheck != errSecSuccess) {
NSLog(@"Problem saving the key to keychain, OSStatus == %d.", (int) sanityCheck);
}
}
// remove from cache
[keyCache removeObjectForKey:tagString];
}
要检索我的密钥,我使用以下方法:
- (SecKeyRef)getKeyRef:(NSString *)tagString isPrivate:(BOOL)isPrivate {
NSData *tag = [self getKeyTag:tagString];
id keyClass = (__bridge id) kSecAttrKeyClassPublic;
if (isPrivate) {
keyClass = (__bridge id) kSecAttrKeyClassPrivate;
}
NSDictionary *queryDict = @{
(__bridge id) kSecClass : (__bridge id) kSecClassKey,
(__bridge id) kSecAttrKeyType : (__bridge id) kSecAttrKeyTypeRSA,
(__bridge id) kSecAttrApplicationTag : tag,
(__bridge id) kSecAttrKeyClass : keyClass,
(__bridge id) kSecReturnRef : (__bridge id) kCFBooleanTrue
};
return [self getKeyRef:queryDict tag:tagString];
}
- (SecKeyRef)getKeyRef:(NSDictionary *)query tag:(NSString *)tagString {
SecKeyRef keyReference = NULL;
OSStatus sanityCheck = SecItemCopyMatching((__bridge CFDictionaryRef) query, (CFTypeRef *) &keyReference);
if (sanityCheck != errSecSuccess) {
NSLog(@"Error trying to retrieve key from keychain. tag: %@. sanityCheck: %li", tagString, sanityCheck);
return nil;
}
return keyReference;
}
在一天结束时,我只能让它工作而不填充。我不确定为什么不能删除填充,所以如果有人有任何见解,请告诉我。BouncyCastle
这是我的加密代码(从David Benko修改):
- (NSData *)encryptData:(NSData *)content usingPublicKey:(NSString *)publicKeyTag {
SecKeyRef publicKey = [self getKeyRef:publicKeyTag isPrivate:NO];
NSData *keyBits = [self getKeyBitsFromKey:publicKey];
NSString *keyString = [keyBits base64EncodedStringWithOptions:0];
NSAssert(publicKey != nil,@"Public key can not be nil");
size_t cipherLen = SecKeyGetBlockSize(publicKey); // convert to byte
void *cipher = malloc(cipherLen);
size_t maxPlainLen = cipherLen - 12;
size_t plainLen = [content length];
if (plainLen > maxPlainLen) {
NSLog(@"content(%ld) is too long, must < %ld", plainLen, maxPlainLen);
return nil;
}
void *plain = malloc(plainLen);
[content getBytes:plain
length:plainLen];
OSStatus returnCode = SecKeyEncrypt(publicKey, kSecPaddingNone, plain,
plainLen, cipher, &cipherLen);
NSData *result = nil;
if (returnCode != errSecSuccess) {
NSLog(@"SecKeyEncrypt fail. Error Code: %d", (int)returnCode);
}
else {
result = [NSData dataWithBytes:cipher
length:cipherLen];
}
free(plain);
free(cipher);
return result;
}
以下是我在Java端解密的方式:
private Response authenticate (String encryptedSymmetricString) {
byte[] encryptedSymmetricKey = Base64.decodeBase64(encryptedSymmetricKeyString);
String privateKey = Server.getServerPrivateKey();
byte[] decryptedSymmetricKey = KeyHandler.decryptMessage(encryptedSymmetricKey, privateKey,
KeyHandler.ASYMMETRIC_CIPHER_ALGORITHM);
}
public static byte[] decryptMessage (byte[] message, String privateKeyString, String algorithm) {
if (message == null || privateKeyString == null) {
return null;
}
PrivateKey privateKey = getPrivateKey(privateKeyString);
return decryptMessage(message, privateKey, algorithm);
}
public static byte[] decryptMessage (byte[] message, PrivateKey privateKey, String algorithm) {
if (message == null || privateKey == null) {
return null;
}
Cipher cipher = createCipher(Cipher.DECRYPT_MODE, privateKey, algorithm, true);
if (cipher == null) {
return null;
}
try {
return cipher.doFinal(message);
}
catch (IllegalBlockSizeException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return null;
}
catch (BadPaddingException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
return null;
}
}