RSA.m 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. /*
  2. @author: ideawu
  3. @link: https://github.com/ideawu/Objective-C-RSA
  4. */
  5. #import "RSA.h"
  6. #import <Security/Security.h>
  7. @implementation RSA
  8. /*
  9. static NSString *base64_encode(NSString *str){
  10. NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
  11. if(!data){
  12. return nil;
  13. }
  14. return base64_encode_data(data);
  15. }
  16. */
  17. static NSString *base64_encode_data(NSData *data){
  18. data = [data base64EncodedDataWithOptions:0];
  19. NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  20. return ret;
  21. }
  22. static NSData *base64_decode(NSString *str){
  23. NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
  24. return data;
  25. }
  26. + (NSData *)stripPublicKeyHeader:(NSData *)d_key{
  27. // Skip ASN.1 public key header
  28. if (d_key == nil) return(nil);
  29. unsigned long len = [d_key length];
  30. if (!len) return(nil);
  31. unsigned char *c_key = (unsigned char *)[d_key bytes];
  32. unsigned int idx = 0;
  33. if (c_key[idx++] != 0x30) return(nil);
  34. if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
  35. else idx++;
  36. // PKCS #1 rsaEncryption szOID_RSA_RSA
  37. static unsigned char seqiod[] =
  38. { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
  39. 0x01, 0x05, 0x00 };
  40. if (memcmp(&c_key[idx], seqiod, 15)) return(nil);
  41. idx += 15;
  42. if (c_key[idx++] != 0x03) return(nil);
  43. if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1;
  44. else idx++;
  45. if (c_key[idx++] != '\0') return(nil);
  46. // Now make a new NSData from this buffer
  47. return([NSData dataWithBytes:&c_key[idx] length:len - idx]);
  48. }
  49. //credit: http://hg.mozilla.org/services/fx-home/file/tip/Sources/NetworkAndStorage/CryptoUtils.m#l1036
  50. + (NSData *)stripPrivateKeyHeader:(NSData *)d_key{
  51. // Skip ASN.1 private key header
  52. if (d_key == nil) return(nil);
  53. unsigned long len = [d_key length];
  54. if (!len) return(nil);
  55. unsigned char *c_key = (unsigned char *)[d_key bytes];
  56. unsigned int idx = 22; //magic byte at offset 22
  57. if (0x04 != c_key[idx++]) return nil;
  58. //calculate length of the key
  59. unsigned int c_len = c_key[idx++];
  60. int det = c_len & 0x80;
  61. if (!det) {
  62. c_len = c_len & 0x7f;
  63. } else {
  64. int byteCount = c_len & 0x7f;
  65. if (byteCount + idx > len) {
  66. //rsa length field longer than buffer
  67. return nil;
  68. }
  69. unsigned int accum = 0;
  70. unsigned char *ptr = &c_key[idx];
  71. idx += byteCount;
  72. while (byteCount) {
  73. accum = (accum << 8) + *ptr;
  74. ptr++;
  75. byteCount--;
  76. }
  77. c_len = accum;
  78. }
  79. // Now make a new NSData from this buffer
  80. return [d_key subdataWithRange:NSMakeRange(idx, c_len)];
  81. }
  82. + (SecKeyRef)addPublicKey:(NSString *)key{
  83. NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
  84. NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
  85. if(spos.location != NSNotFound && epos.location != NSNotFound){
  86. NSUInteger s = spos.location + spos.length;
  87. NSUInteger e = epos.location;
  88. NSRange range = NSMakeRange(s, e-s);
  89. key = [key substringWithRange:range];
  90. }
  91. key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  92. key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  93. key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
  94. key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
  95. // This will be base64 encoded, decode it.
  96. NSData *data = base64_decode(key);
  97. data = [RSA stripPublicKeyHeader:data];
  98. if(!data){
  99. return nil;
  100. }
  101. //a tag to read/write keychain storage
  102. NSString *tag = @"RSAUtil_PubKey";
  103. NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
  104. // Delete any old lingering key with the same tag
  105. NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
  106. [publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
  107. [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
  108. [publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
  109. SecItemDelete((__bridge CFDictionaryRef)publicKey);
  110. // Add persistent version of the key to system keychain
  111. [publicKey setObject:data forKey:(__bridge id)kSecValueData];
  112. [publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
  113. kSecAttrKeyClass];
  114. [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
  115. kSecReturnPersistentRef];
  116. CFTypeRef persistKey = nil;
  117. OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
  118. if (persistKey != nil){
  119. CFRelease(persistKey);
  120. }
  121. if ((status != noErr) && (status != errSecDuplicateItem)) {
  122. return nil;
  123. }
  124. [publicKey removeObjectForKey:(__bridge id)kSecValueData];
  125. [publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
  126. [publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
  127. [publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
  128. // Now fetch the SecKeyRef version of the key
  129. SecKeyRef keyRef = nil;
  130. status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
  131. if(status != noErr){
  132. return nil;
  133. }
  134. return keyRef;
  135. }
  136. + (SecKeyRef)addPrivateKey:(NSString *)key{
  137. NSRange spos;
  138. NSRange epos;
  139. spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
  140. if(spos.length > 0){
  141. epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];
  142. }else{
  143. spos = [key rangeOfString:@"-----BEGIN PRIVATE KEY-----"];
  144. epos = [key rangeOfString:@"-----END PRIVATE KEY-----"];
  145. }
  146. if(spos.location != NSNotFound && epos.location != NSNotFound){
  147. NSUInteger s = spos.location + spos.length;
  148. NSUInteger e = epos.location;
  149. NSRange range = NSMakeRange(s, e-s);
  150. key = [key substringWithRange:range];
  151. }
  152. key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  153. key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  154. key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
  155. key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
  156. // This will be base64 encoded, decode it.
  157. NSData *data = base64_decode(key);
  158. data = [RSA stripPrivateKeyHeader:data];
  159. if(!data){
  160. return nil;
  161. }
  162. //a tag to read/write keychain storage
  163. NSString *tag = @"RSAUtil_PrivKey";
  164. NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
  165. // Delete any old lingering key with the same tag
  166. NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];
  167. [privateKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
  168. [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
  169. [privateKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
  170. SecItemDelete((__bridge CFDictionaryRef)privateKey);
  171. // Add persistent version of the key to system keychain
  172. [privateKey setObject:data forKey:(__bridge id)kSecValueData];
  173. [privateKey setObject:(__bridge id) kSecAttrKeyClassPrivate forKey:(__bridge id)
  174. kSecAttrKeyClass];
  175. [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
  176. kSecReturnPersistentRef];
  177. CFTypeRef persistKey = nil;
  178. OSStatus status = SecItemAdd((__bridge CFDictionaryRef)privateKey, &persistKey);
  179. if (persistKey != nil){
  180. CFRelease(persistKey);
  181. }
  182. if ((status != noErr) && (status != errSecDuplicateItem)) {
  183. return nil;
  184. }
  185. [privateKey removeObjectForKey:(__bridge id)kSecValueData];
  186. [privateKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
  187. [privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
  188. [privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
  189. // Now fetch the SecKeyRef version of the key
  190. SecKeyRef keyRef = nil;
  191. status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);
  192. if(status != noErr){
  193. return nil;
  194. }
  195. return keyRef;
  196. }
  197. /* START: Encryption & Decryption with RSA private key */
  198. + (NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef isSign:(BOOL)isSign {
  199. const uint8_t *srcbuf = (const uint8_t *)[data bytes];
  200. size_t srclen = (size_t)data.length;
  201. size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
  202. void *outbuf = malloc(block_size);
  203. size_t src_block_size = block_size - 11;
  204. NSMutableData *ret = [[NSMutableData alloc] init];
  205. for(int idx=0; idx<srclen; idx+=src_block_size){
  206. //NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
  207. size_t data_len = srclen - idx;
  208. if(data_len > src_block_size){
  209. data_len = src_block_size;
  210. }
  211. size_t outlen = block_size;
  212. OSStatus status = noErr;
  213. if (isSign) {
  214. status = SecKeyRawSign(keyRef,
  215. kSecPaddingPKCS1,
  216. srcbuf + idx,
  217. data_len,
  218. outbuf,
  219. &outlen
  220. );
  221. } else {
  222. status = SecKeyEncrypt(keyRef,
  223. kSecPaddingPKCS1,
  224. srcbuf + idx,
  225. data_len,
  226. outbuf,
  227. &outlen
  228. );
  229. }
  230. if (status != 0) {
  231. NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
  232. ret = nil;
  233. break;
  234. }else{
  235. [ret appendBytes:outbuf length:outlen];
  236. }
  237. }
  238. free(outbuf);
  239. CFRelease(keyRef);
  240. return ret;
  241. }
  242. + (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey{
  243. NSData *data = [RSA encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] privateKey:privKey];
  244. NSString *ret = base64_encode_data(data);
  245. return ret;
  246. }
  247. + (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey{
  248. if(!data || !privKey){
  249. return nil;
  250. }
  251. SecKeyRef keyRef = [RSA addPrivateKey:privKey];
  252. if(!keyRef){
  253. return nil;
  254. }
  255. return [RSA encryptData:data withKeyRef:keyRef isSign:YES];
  256. }
  257. + (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
  258. const uint8_t *srcbuf = (const uint8_t *)[data bytes];
  259. size_t srclen = (size_t)data.length;
  260. size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
  261. UInt8 *outbuf = malloc(block_size);
  262. size_t src_block_size = block_size;
  263. NSMutableData *ret = [[NSMutableData alloc] init];
  264. for(int idx=0; idx<srclen; idx+=src_block_size){
  265. //NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
  266. size_t data_len = srclen - idx;
  267. if(data_len > src_block_size){
  268. data_len = src_block_size;
  269. }
  270. size_t outlen = block_size;
  271. OSStatus status = noErr;
  272. status = SecKeyDecrypt(keyRef,
  273. kSecPaddingNone,
  274. srcbuf + idx,
  275. data_len,
  276. outbuf,
  277. &outlen
  278. );
  279. if (status != 0) {
  280. NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
  281. ret = nil;
  282. break;
  283. }else{
  284. //the actual decrypted data is in the middle, locate it!
  285. int idxFirstZero = -1;
  286. int idxNextZero = (int)outlen;
  287. for ( int i = 0; i < outlen; i++ ) {
  288. if ( outbuf[i] == 0 ) {
  289. if ( idxFirstZero < 0 ) {
  290. idxFirstZero = i;
  291. } else {
  292. idxNextZero = i;
  293. break;
  294. }
  295. }
  296. }
  297. [ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
  298. }
  299. }
  300. free(outbuf);
  301. CFRelease(keyRef);
  302. return ret;
  303. }
  304. + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey{
  305. NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
  306. data = [RSA decryptData:data privateKey:privKey];
  307. NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  308. return ret;
  309. }
  310. + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{
  311. if(!data || !privKey){
  312. return nil;
  313. }
  314. SecKeyRef keyRef = [RSA addPrivateKey:privKey];
  315. if(!keyRef){
  316. return nil;
  317. }
  318. return [RSA decryptData:data withKeyRef:keyRef];
  319. }
  320. /* END: Encryption & Decryption with RSA private key */
  321. /* START: Encryption & Decryption with RSA public key */
  322. + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey{
  323. NSData *data = [RSA encryptData:[str dataUsingEncoding:NSUTF8StringEncoding] publicKey:pubKey];
  324. NSString *ret = base64_encode_data(data);
  325. return ret;
  326. }
  327. + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey{
  328. if(!data || !pubKey){
  329. return nil;
  330. }
  331. SecKeyRef keyRef = [RSA addPublicKey:pubKey];
  332. if(!keyRef){
  333. return nil;
  334. }
  335. return [RSA encryptData:data withKeyRef:keyRef isSign:NO];
  336. }
  337. + (NSString *)decryptString:(NSString *)str publicKey:(NSString *)pubKey{
  338. NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters];
  339. data = [RSA decryptData:data publicKey:pubKey];
  340. NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  341. return ret;
  342. }
  343. + (NSData *)decryptData:(NSData *)data publicKey:(NSString *)pubKey{
  344. if(!data || !pubKey){
  345. return nil;
  346. }
  347. SecKeyRef keyRef = [RSA addPublicKey:pubKey];
  348. if(!keyRef){
  349. return nil;
  350. }
  351. return [RSA decryptData:data withKeyRef:keyRef];
  352. }
  353. /* END: Encryption & Decryption with RSA public key */
  354. @end