
本文為投稿文章,作者:Panda_iOS。
看到這篇的同學算是幸運的。當年我做 RSA 加密與簽名時,網上資料實在太舊,折騰完實在忍不住寫一篇下來。本文會詳細講解 iOS 端如何實現 RSA 加密與簽名,並保證結果與 Java 完全一致。這是我的第二篇博客,不足之處还请多指教。
什麼是 RSA?它是一種非對稱加密算法,常用於加密傳輸數據;配合數字摘要算法,也可以用來做文本簽名。
RSA 中的 padding 是什麼?padding 即填充方式。RSA 要求待加密的明文長度小於模數,padding 就是通過約定的填充規則把明文限制在合適長度內。後文會介紹幾種模式和分段加密。
加密和加簽有什麼區別?
前者只為保密;後者主要用於防偽造,避免他人模擬我們的客戶端攻擊服務器。
RSA 使用「密鑰對」加解密,操作前需要先準備好公鑰(Public Key)與私鑰(Private Key)。
iOS 的 Security.framework 提供了對 RSA 的支持,但使用前需要處理密鑰對:由 public key 生成證書,由 private key 生成 p12 格式的密鑰。相比之下,Java 可以直接拿字符串加解密,簡單太多了。
Apple 不建議直接用字符串加解密,推薦使用 p12 文件。下面把加密所需的所有文件一次性生成出來,同時也提供給 Java 端使用。以下步驟都在終端完成:
# 生成 1024 位私鑰 openssl genrsa -out private_key.pem 1024 # 生成證書簽名請求文件 openssl req -new -key private_key.pem -out rsaCertReq.csr # 生成證書並指定 3650 天有效期 openssl x509 -req -days 3650 -in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt # 生成 iOS 使用的公鑰(der 格式) openssl x509 -outform der -in rsaCert.crt -out public_key.der # 生成 iOS 使用的私鑰(p12),這裡設置的密碼後續生成 SecKeyRef 時會用到 openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt # 生成 Java 使用的公鑰(pem) openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout # 生成 Java 使用的私鑰(pkcs8 pem) openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt
// 由 p12 數據生成私鑰對應的 SecKeyRef,返回 nil 時請檢查 p12 的生成步驟
- (SecKeyRef)getPrivateKeyRefrenceFromData:(NSData*)p12Data password:(NSString*)password {
SecKeyRef privateKeyRef = NULL;
NSMutableDictionary *options = [[NSMutableDictionary alloc] init];
[options setObject:password forKey:(__bridge id)kSecImportExportPassphrase];
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import((__bridge CFDataRef)p12Data,
(__bridge CFDictionaryRef)options,
&items);
if (securityError == noErr && CFArrayGetCount(items) > 0) {
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
if (securityError != noErr) {
privateKeyRef = NULL;
}
}
CFRelease(items);
return privateKeyRef;
}// 由 der 數據生成公鑰對應的 SecKeyRef
- (SecKeyRef)getPublicKeyRefrenceFromeData:(NSData*)derData {
SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)derData);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;
OSStatus status = SecTrustCreateWithCertificates(myCertificate, myPolicy, &myTrust);
SecTrustResultType trustResult;
if (status == noErr) {
status = SecTrustEvaluate(myTrust, &trustResult);
}
SecKeyRef securityKey = SecTrustCopyPublicKey(myTrust);
CFRelease(myCertificate);
CFRelease(myPolicy);
CFRelease(myTrust);
return securityKey;
}- (NSData*)rsaEncryptData:(NSData*)data {
SecKeyRef key = [self getPublicKey];
size_t cipherBufferSize = SecKeyGetBlockSize(key);
uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
// PKCS1 填充下,單段明文最長為密鑰長度減 11
size_t blockSize = cipherBufferSize - 11;
size_t blockCount = (size_t)ceil([data length] / (double)blockSize);
NSMutableData *encryptedData = [[NSMutableData alloc] init];
for (int i = 0; i < blockCount; i++) {
unsigned long bufferSize = MIN(blockSize, [data length] - i * blockSize);
NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
OSStatus status = SecKeyEncrypt(key, kSecPaddingPKCS1,
(const uint8_t *)[buffer bytes], [buffer length],
cipherBuffer, &cipherBufferSize);
if (status != noErr) {
return nil;
}
NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
[encryptedData appendData:encryptedBytes];
}
if (cipherBuffer) {
free(cipherBuffer);
}
return encryptedData;
}- (NSData*)rsaDecryptData:(NSData*)data {
SecKeyRef key = [self getPrivatKey];
size_t cipherBufferSize = SecKeyGetBlockSize(key);
size_t blockSize = cipherBufferSize;
size_t blockCount = (size_t)ceil([data length] / (double)blockSize);
NSMutableData *decryptedData = [[NSMutableData alloc] init];
for (int i = 0; i < blockCount; i++) {
unsigned long bufferSize = MIN(blockSize, [data length] - i * blockSize);
NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
size_t cipherLen = [buffer length];
void *cipher = malloc(cipherLen);
[buffer getBytes:cipher length:cipherLen];
size_t plainLen = SecKeyGetBlockSize(key);
void *plain = malloc(plainLen);
OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);
if (status != noErr) {
return nil;
}
NSData *decryptedBytes = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];
[decryptedData appendData:decryptedBytes];
}
return decryptedData;
}這也是跨端對接時最容易出問題的地方——iOS 與 Java 兩側的 padding 必須嚴格一致,否則解密必然失敗。
// 對數據做 SHA256 簽名
- (NSData *)rsaSHA256SignData:(NSData *)plainData {
SecKeyRef key = [self getPrivatKey];
size_t signedHashBytesSize = SecKeyGetBlockSize(key);
uint8_t *signedHashBytes = malloc(signedHashBytesSize);
memset(signedHashBytes, 0x0, signedHashBytesSize);
size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH;
uint8_t *hashBytes = malloc(hashBytesSize);
if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) {
return nil;
}
SecKeyRawSign(key,
kSecPaddingPKCS1SHA256,
hashBytes, hashBytesSize,
signedHashBytes, &signedHashBytesSize);
NSData *signedHash = [NSData dataWithBytes:signedHashBytes length:(NSUInteger)signedHashBytesSize];
if (hashBytes) free(hashBytes);
if (signedHashBytes) free(signedHashBytes);
return signedHash;
}// 驗簽成功返回 YES
- (BOOL)rsaSHA256VerifyData:(NSData *)plainData withSignature:(NSData *)signature {
SecKeyRef key = [self getPublicKey];
size_t signedHashBytesSize = SecKeyGetBlockSize(key);
const void *signedHashBytes = [signature bytes];
size_t hashBytesSize = CC_SHA256_DIGEST_LENGTH;
uint8_t *hashBytes = malloc(hashBytesSize);
if (!CC_SHA256([plainData bytes], (CC_LONG)[plainData length], hashBytes)) {
return NO;
}
OSStatus status = SecKeyRawVerify(key,
kSecPaddingPKCS1SHA256,
hashBytes, hashBytesSize,
signedHashBytes, signedHashBytesSize);
return status == errSecSuccess;
}文章到此結束,希望對大家有幫助。想看 demo 的朋友可搜索:XYRSACryptor。