Sin descripción

RSAEncryptor.m 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. //
  2. // RSAEncryptor.m
  3. // SecTest
  4. //
  5. // Created by ascii on 15/2/10.
  6. // Copyright (c) 2015年 ascii. All rights reserved.
  7. //
  8. #import "RSAEncryptor.h"
  9. #import <Security/Security.h>
  10. #import "NSData+Base64.h"
  11. @implementation RSAEncryptor
  12. {
  13. SecKeyRef publicKey;
  14. SecKeyRef privateKey;
  15. }
  16. -(void)dealloc
  17. {
  18. if (publicKey != NULL) {
  19. CFRelease(publicKey);
  20. }
  21. if (privateKey != NULL) {
  22. CFRelease(privateKey);
  23. }
  24. }
  25. -(SecKeyRef) getPublicKey {
  26. return publicKey;
  27. }
  28. -(SecKeyRef) getPrivateKey {
  29. return privateKey;
  30. }
  31. -(void) loadPublicKeyFromFile: (NSString*) derFilePath
  32. {
  33. NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];
  34. [self loadPublicKeyFromData: derData];
  35. }
  36. -(void) loadPublicKeyFromData: (NSData*) derData
  37. {
  38. publicKey = [self getPublicKeyRefrenceFromeData: derData];
  39. }
  40. -(void) loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password
  41. {
  42. NSData *p12Data = [NSData dataWithContentsOfFile:p12FilePath];
  43. [self loadPrivateKeyFromData: p12Data password:p12Password];
  44. }
  45. -(void) loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password
  46. {
  47. privateKey = [self getPrivateKeyRefrenceFromData: p12Data password: p12Password];
  48. }
  49. #pragma mark - Private Methods
  50. -(SecKeyRef) getPublicKeyRefrenceFromeData: (NSData*)derData
  51. {
  52. SecCertificateRef myCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, (__bridge CFDataRef)derData);
  53. SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
  54. SecTrustRef myTrust;
  55. OSStatus status = SecTrustCreateWithCertificates(myCertificate,myPolicy,&myTrust);
  56. SecTrustResultType trustResult;
  57. if (status == noErr) {
  58. status = SecTrustEvaluate(myTrust, &trustResult);
  59. }
  60. SecKeyRef securityKey = SecTrustCopyPublicKey(myTrust);
  61. CFRelease(myCertificate);
  62. CFRelease(myPolicy);
  63. CFRelease(myTrust);
  64. return securityKey;
  65. }
  66. -(SecKeyRef) getPrivateKeyRefrenceFromData: (NSData*)p12Data password:(NSString*)password
  67. {
  68. SecKeyRef privateKeyRef = NULL;
  69. NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
  70. [options setObject: password forKey:(__bridge id)kSecImportExportPassphrase];
  71. CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
  72. OSStatus securityError = SecPKCS12Import((__bridge CFDataRef) p12Data, (__bridge CFDictionaryRef)options, &items);
  73. if (securityError == noErr && CFArrayGetCount(items) > 0) {
  74. CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
  75. SecIdentityRef identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict, kSecImportItemIdentity);
  76. securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
  77. if (securityError != noErr) {
  78. privateKeyRef = NULL;
  79. }
  80. }
  81. CFRelease(items);
  82. return privateKeyRef;
  83. }
  84. #pragma mark - Encrypt
  85. -(NSString*) rsaEncryptString:(NSString*)string {
  86. NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
  87. NSData* encryptedData = [self rsaEncryptData: data];
  88. NSString* base64EncryptedString = [encryptedData base64EncodedString];
  89. return base64EncryptedString;
  90. }
  91. // 加密的大小受限于SecKeyEncrypt函数,SecKeyEncrypt要求明文和密钥的长度一致,如果要加密更长的内容,需要把内容按密钥长度分成多份,然后多次调用SecKeyEncrypt来实现
  92. -(NSData*) rsaEncryptData:(NSData*)data {
  93. SecKeyRef key = [self getPublicKey];
  94. size_t cipherBufferSize = SecKeyGetBlockSize(key);
  95. uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
  96. size_t blockSize = cipherBufferSize - 11; // 分段加密
  97. size_t blockCount = (size_t)ceil([data length] / (double)blockSize);
  98. NSMutableData *encryptedData = [[NSMutableData alloc] init] ;
  99. for (int i=0; i<blockCount; i++) {
  100. int bufferSize = (int)MIN(blockSize,[data length] - i * blockSize);
  101. NSData *buffer = [data subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
  102. OSStatus status = SecKeyEncrypt(key, kSecPaddingPKCS1, (const uint8_t *)[buffer bytes], [buffer length], cipherBuffer, &cipherBufferSize);
  103. if (status == noErr){
  104. NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
  105. [encryptedData appendData:encryptedBytes];
  106. }else{
  107. if (cipherBuffer) {
  108. free(cipherBuffer);
  109. }
  110. return nil;
  111. }
  112. }
  113. if (cipherBuffer){
  114. free(cipherBuffer);
  115. }
  116. return encryptedData;
  117. }
  118. #pragma mark - Decrypt
  119. -(NSString*) rsaDecryptString:(NSString*)string {
  120. NSData* data = [NSData dataFromBase64String: string];
  121. NSData* decryptData = [self rsaDecryptData: data];
  122. NSString* result = [[NSString alloc] initWithData: decryptData encoding:NSUTF8StringEncoding];
  123. return result;
  124. }
  125. -(NSData*) rsaDecryptData:(NSData*)data {
  126. SecKeyRef key = [self getPrivateKey];
  127. size_t cipherLen = [data length];
  128. void *cipher = malloc(cipherLen);
  129. [data getBytes:cipher length:cipherLen];
  130. size_t plainLen = SecKeyGetBlockSize(key) - 12;
  131. void *plain = malloc(plainLen);
  132. OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);
  133. if (status != noErr) {
  134. return nil;
  135. }
  136. NSData *decryptedData = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];
  137. return decryptedData;
  138. }
  139. #pragma mark - Class Methods
  140. static RSAEncryptor* sharedInstance = nil;
  141. +(void) setSharedInstance: (RSAEncryptor*)instance
  142. {
  143. sharedInstance = instance;
  144. }
  145. +(RSAEncryptor*) sharedInstance
  146. {
  147. return sharedInstance;
  148. }
  149. @end