IOS中RSA的加密解密

iqinghong 贡献于2015-09-22

作者 Administrator  创建于2013-07-31 05:55:24   修改者  修改于2013-08-06 00:33:33字数5746

文档摘要: .DOS框下输入命令行opensslreq-x509-days3650-new-newkeyrsa:2048-keyoutprivate_key_self_signed_cert.pem-outprivate_key_self_signed_cert.pem生成私钥。接下来就是公司名字,省市,还有名字的一些信息按着给下填就行。2.opensslpkcs12-export-outpkcs.p12-inprivate_key_self_signed_cert.pem生成p12格式的文件。3.opensslx509-inprivate_key_self_signed_cert.pem-informPEM-outpublic_key.der-outformDER生成自签名证书。
关键词:

IOS中RSA的加密解密 1. DOS框下输入命令行openssl req -x509 -days 3650 -new -newkey rsa:2048 -keyout private_key_self_signed_cert.pem -out private_key_self_signed_cert.pem生成私钥。接下来就是公司名字,省市,还有名字的一些信息按着给下填就行。 2. openssl pkcs12 -export -out pkcs.p12 -in private_key_self_signed_cert.pem 生成p12格式的文件。 3. openssl x509 -in private_key_self_signed_cert.pem -inform PEM -out public_key.der -outform DER 生成自签名证书。 4. //证书获取公钥 [cpp] view plaincopy 1 - (OSStatus)extractPublicKeyFromCertificateFile { 2 OSStatus status = -1; 3 if (_publicKey == nil) { 4 SecTrustRef trust; 5 SecTrustResultType trustResult; 6 NSDate *derData = [NSData dataWithContentsOfFile:[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"]]; 7 if (derData) { 8 SecCertificateRef cert = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef)derData); 9 SecPolicyRef policy = SecPolicyCreateBasicX509(); 10 status = SecTrustCreateWithCertificates(cert, policy, &trust); 11 if (status == errSecSuccess && trust) { 12 NSArray *certs = [NSArray arrayWithObject:(id)cert]; 13 status = SecTrustSetAnchorCertificates(trust, (CFArrayRef)certs); 14 if (status == errSecSuccess) { 15 status = SecTrustEvaluate(trust, &trustResult); 16 // 自签名证书可信 17 if (status == errSecSuccess && (trustResult == kSecTrustResultUnspecified || trustResult == kSecTrustResultProceed)) { 18 _publicKey = SecTrustCopyPublicKey(trust); 19 if (_publicKey) { 20 NSLog(@"Get public key successfully~ %@", _publicKey); 21 } 22 if (cert) { 23 CFRelease(cert); 24 } 25 if (policy) { 26 CFRelease(policy); 27 } 28 if (trust) { 29 CFRelease(trust); 30 } 31 } 32 } 33 } 34 } 35 } 36 return status; 37 } 5. 用公钥对数据加密。 [cpp] view plaincopy 38 //加密 39 - (NSMutableData *)encryptWithPublicKey:(NSData *)plainData { 40 // 分配内存块,用于存放加密后的数据段 41 size_t cipherBufferSize = SecKeyGetBlockSize(_publicKey); 42 uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t)); 43 double totalLength = [plainData length]; 44 size_t blockSize = cipherBufferSize - 12; 45 size_t blockCount = (size_t)ceil(totalLength / blockSize); 46 NSMutableData *encryptedData = [NSMutableData data]; 47 // 分段加密 48 for (int i = 0; i < blockCount; i++) { 49 NSUInteger loc = i * blockSize; 50 // 数据段的实际大小。最后一段可能比blockSize小。 51 int dataSegmentRealSize = MIN(blockSize, [plainData length] - loc); 52 // 截取需要加密的数据段 53 NSData *dataSegment = [plainData subdataWithRange:NSMakeRange(loc, dataSegmentRealSize)]; 54 OSStatus status = SecKeyEncrypt(_publicKey, kSecPaddingPKCS1, (const uint8_t *)[dataSegment bytes], dataSegmentRealSize, cipherBuffer, &cipherBufferSize); 55 if (status == errSecSuccess) { 56 NSData *encryptedDataSegment = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize]; 57 // 追加加密后的数据段 58 [encryptedData appendData:encryptedDataSegment]; 59 [encryptedDataSegment release]; 60 } else { 61 if (cipherBuffer) { 62 free(cipherBuffer); 63 } 64 return nil; 65 } 66 } 67 if (cipherBuffer) { 68 free(cipherBuffer); 69 } 70 return encryptedData; 71 } 6. 获取私钥。 //从p12文件中获取私钥 ,密码是你生成私钥的时候生成的 [cpp] view plaincopy 72 - (OSStatus)extractEveryThingFromPKCS12File:(NSString *)pkcsPath passphrase:(NSString *)pkcsPassword { 73 SecIdentityRef identity; 74 SecTrustRef trust; 75 OSStatus status = -1; 76 77 if (_privateKey == nil) { 78 NSData *p12Data = [NSData dataWithContentsOfFile:pkcsPath]; 79 if (p12Data) { 80 CFStringRef password = (CFStringRef)pkcsPassword; 81 const void *keys[] = { 82 kSecImportExportPassphrase 83 }; 84 const void *values[] = { 85 password 86 }; 87 CFDictionaryRef options = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, NULL, NULL); 88 CFArrayRef items = CFArrayCreate(kCFAllocatorDefault, NULL, 0, NULL); 89 status = SecPKCS12Import((CFDataRef)p12Data, options, &items); 90 if (status == errSecSuccess) { 91 CFDictionaryRef identity_trust_dic = CFArrayGetValueAtIndex(items, 0); 92 identity = (SecIdentityRef)CFDictionaryGetValue(identity_trust_dic, kSecImportItemIdentity); 93 trust = (SecTrustRef)CFDictionaryGetValue(identity_trust_dic, kSecImportItemTrust); 94 // certs数组中包含了所有的证书 95 CFArrayRef certs = (CFArrayRef)CFDictionaryGetValue(identity_trust_dic, kSecImportItemCertChain); 96 if ([(NSArray *)certs count] && trust && identity) { 97 // 如果没有下面一句,自签名证书的评估信任结果永远是kSecTrustResultRecoverableTrustFailure 98 status = SecTrustSetAnchorCertificates(trust, certs); 99 if (status == errSecSuccess) { 100 SecTrustResultType trustResultType; 101 // 通常, 返回的trust result type应为kSecTrustResultUnspecified,如果是,就可以说明签名证书是可信的 102 status = SecTrustEvaluate(trust, &trustResultType); 103 if ((trustResultType == kSecTrustResultUnspecified || trustResultType == kSecTrustResultProceed) && status == errSecSuccess) { 104 // 证书可信,可以提取私钥与公钥,然后可以使用公私钥进行加解密操作 105 status = SecIdentityCopyPrivateKey(identity, &_privateKey); 106 if (status == errSecSuccess && _privateKey) { 107 // 成功提取私钥 108 NSLog(@"Get private key successfully~ %@", _privateKey); 109 } 110 } 111 } 112 } 113 } 114 if (options) { 115 CFRelease(options); 116 } 117 } 118 } 119 return 0; 120 } 7.数据解密。 [cpp] view plaincopy 121 - (NSData *)decryptWithPrivateKey:(NSData *)cipherData { 122 // 分配内存块,用于存放解密后的数据段 123 size_t plainBufferSize = SecKeyGetBlockSize(_privateKey); 124 NSLog(@"plainBufferSize = %zd", plainBufferSize); 125 uint8_t *plainBuffer = malloc(plainBufferSize * sizeof(uint8_t)); 126 // 计算数据段最大长度及数据段的个数 127 NSLog(@"totalLength = %d", [cipherData length]); 128 int totalLength = [cipherData length]; 129 NSLog(@"totalLength = %d", totalLength); 130 size_t blockSize = plainBufferSize; 131 size_t blockCount = (size_t)ceil(totalLength / blockSize); 132 NSMutableData *decryptedData = [NSMutableData data]; 133 // 分段解密 134 for (int i = 0; i < blockCount; i++) { 135 NSUInteger loc = i * blockSize; 136 // 数据段的实际大小。最后一段可能比blockSize小。 137 int dataSegmentRealSize = MIN(blockSize, totalLength - loc); 138 // 截取需要解密的数据段 139 NSData *dataSegment = [cipherData subdataWithRange:NSMakeRange(loc, dataSegmentRealSize)]; 140 OSStatus status = SecKeyDecrypt(_privateKey, kSecPaddingPKCS1, (const uint8_t *)[dataSegment bytes], dataSegmentRealSize, plainBuffer, &plainBufferSize); 141 if (status == errSecSuccess) { 142 NSData *decryptedDataSegment = [[NSData alloc] initWithBytes:(const void *)plainBuffer length:plainBufferSize]; 143 [decryptedData appendData:decryptedDataSegment]; 144 [decryptedDataSegment release]; 145 } else { 146 if (plainBuffer) { 147 free(plainBuffer); 148 } 149 return nil; 150 } 151 } 152 if (plainBuffer) { 153 free(plainBuffer); 154 } 155 return decryptedData; 156 }

下载文档到电脑,查找使用更方便

文档的实际排版效果,会与网站的显示效果略有不同!!

需要 6 金币 [ 分享文档获得金币 ] 0 人已下载

下载文档