/* RSA.h @author: ideawu @link: https://github.com/ideawu/Objective-C-RSA */ #import <Foundation/Foundation.h> @interface RSA : NSObject // return base64 encoded string + (NSString *)encryptString:(NSString *)str publicKey:(NSString *)pubKey; // return raw data + (NSData *)encryptData:(NSData *)data publicKey:(NSString *)pubKey; // return base64 encoded string // enc with private key NOT working YET! //+ (NSString *)encryptString:(NSString *)str privateKey:(NSString *)privKey; // return raw data //+ (NSData *)encryptData:(NSData *)data privateKey:(NSString *)privKey; // decrypt base64 encoded string, convert result to string(not base64 encoded) + (NSString *)decryptString:(NSString *)str publicKey:(NSString *)pubKey; + (NSData *)decryptData:(NSData *)data publicKey:(NSString *)pubKey; + (NSString *)decryptString:(NSString *)str privateKey:(NSString *)privKey; + (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey; @end
/* RSA.m @author: ideawu @link: https://github.com/ideawu/Objective-C-RSA */ #import "RSA.h" #import <Security/Security.h> @implementation RSA /* static NSString *base64_encode(NSString *str){ NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding]; if(!data){ return nil; } return base64_encode_data(data); } */ static NSString *base64_encode_data(NSData *data){ data = [data base64EncodedDataWithOptions:0]; NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return ret; } static NSData *base64_decode(NSString *str){ NSData *data = [[NSData alloc] initWithBase64EncodedString:str options:NSDataBase64DecodingIgnoreUnknownCharacters]; return data; } + (NSData *)stripPublicKeyHeader:(NSData *)d_key{ // Skip ASN.1 public key header if (d_key == nil) return(nil); unsigned long len = [d_key length]; if (!len) return(nil); unsigned char *c_key = (unsigned char *)[d_key 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++; // PKCS #1 rsaEncryption szOID_RSA_RSA static unsigned char seqiod[] = { 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00 }; if (memcmp(&c_key[idx], seqiod, 15)) return(nil); idx += 15; if (c_key[idx++] != 0x03) return(nil); if (c_key[idx] > 0x80) idx += c_key[idx] - 0x80 + 1; else idx++; if (c_key[idx++] != '