前几天写了篇文章,关于RSA的加解密,及签名认证(在应用中保存自己的私钥,公钥,这样别人无法得知公私钥,提高数据传输中的安全性)。关于 签名认证的RSA加解密 点这里。
本篇主要写直接使用公钥、私钥来加解密。下面的代码方法中,包括有两个是使用公钥证书(加密)、私钥证书(解密),证书的生成可参考 签名认证的RSA加解密
这里直接上代码,里面的方法有注释:
// RSAEncryptor.h
// RAS签名
//
// Created by user on 16/7/6.
// Copyright © 2016年 user. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface RSA_Encryptor : NSObject
#pragma mark 初始化对象
+(RSA_Encryptor *)sharedRSA_Encryptor;
#pragma mark - 使用 公钥加密、私钥解密
/**
* 私钥 加密
*
* @param string 需加密字符串
* @param publicKeyStr 公钥
*
* @return 公钥加密 后的字符串
*/
- (NSString *)encryptorString:(NSString *)string PublicKeyStr:(NSString *)publicKeyStr;
/**
* 私钥证书 加密
*
* @param string 需加密字符串
* @param path 公钥证书 文件路径
*
* @return 公钥证书 加密 后的字符串
*/
- (NSString *)encryptorString:(NSString *)string PublicKeyPath:(NSString *)path;
// 解密
/**
* 私钥 解密
*
* @param string 公钥 加密的字符串(需要加密字符串)
* @param privateKeyStr 私钥
*
* @return 解密后字符串
*/
- (NSString *)decryptString:(NSString *)string PrivateKeyStr:(NSString *)privateKeyStr;
/**
* 私钥证书 解密
*
* @param string 公钥证书 加密的字符串(需要加密字符串)
* @param path 私钥证书文件路径
* @param p12Passwoerd 私钥证书密码
*
* @return 解密后字符串
*/
- (NSString *)decryptString:(NSString *)string PrivateKeyPath:(NSString *)path PassWord:(NSString *)p12Passwoerd;
#pragma mark - 使用、公钥解密 (注:解密的字符串是使用私钥加密过后的)
- (NSString *)decryptString:(NSString *)string PublicKeyStr:(NSString *)publicKeyStr;
@end
// RSA_Encryptor.m
// RAS签名
//
// Created by user on 16/7/6.
// Copyright © 2016年 user. All rights reserved.
//
#import "RSA_Encryptor.h"
#import <Security/Security.h>
#import "NSData+Base64.h"
// 静态类内部变量
static RSA_Encryptor *rsaEncryptor;
@implementation RSA_Encryptor
{
SecKeyRef publicKey;
SecKeyRef privateKey;
}
-(void)dealloc
{
CFRelease(publicKey);
CFRelease(privateKey);
}
// 初始化对象
+(RSA_Encryptor *)sharedRSA_Encryptor
{
@synchronized (self)
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
rsaEncryptor = [[self alloc]init];
});
}
return rsaEncryptor;
}
-(SecKeyRef) getPublicKey
{
return publicKey;
}
-(SecKeyRef) getPrivateKey
{
return privateKey;
}
- (NSString *)encryptorString:(NSString *)string PublicKeyStr:(NSString *)publicKeyStr
{
NSString *encrypStr;
publicKey = [RSA_Encryptor addPublicKey:publicKeyStr];
if (publicKey)
{
encrypStr = [self rsaEncryptString:string SeckeyRefKey:publicKey];
}
else
{
encrypStr = @"获取公钥失败";
}
return encrypStr;
}
- (NSString *)encryptorString:(NSString *)string PublicKeyPath:(NSString *)path
{
NSString *encrypStr;
[self loadPublicKeyFromFile:path];
if (publicKey)
{
encrypStr = [self rsaEncryptString:string SeckeyRefKey:publicKey];
}
else
{
encrypStr = @"获取公钥失败";
}
return encrypStr;
}
-(void) loadPublicKeyFromFile: (NSString*) derFilePath
{
NSData *derData = [[NSData alloc] initWithContentsOfFile:derFilePath];
[self loadPublicKeyFromData: derData];
}
-(void) loadPublicKeyFromData: (NSData*) derData
{
publicKey = [self getPublicKeyRefrenceFromeData: derData];
NSLog(@"publicKey%@", publicKey);
}
- (NSString *)decryptString:(NSString *)string PrivateKeyStr:(NSString *)privateKeyStr
{
NSString *decryptStr;
privateKey = [RSA_Encryptor addPrivateKey:privateKeyStr];
if (privateKey)
{
decryptStr = [self rsaDecryptString:string SecKeyRefKey:privateKey];
}
else
{
return nil;
}
return decryptStr;
}
- (NSString *)decryptString:(NSString *)string PrivateKeyPath:(NSString *)path PassWord:(NSString *)p12Passwoerd
{
NSString *decryptStr;
privateKey =[self loadPrivateKeyFromFile:path password:p12Passwoerd];
if (privateKey)
{
decryptStr = [self rsaEncryptString:string SeckeyRefKey:privateKey];
}
else
{
decryptStr = @"获取私钥失败";
}
return decryptStr;
}
#pragma mark 私钥加密、公钥解密
- (NSString *)encryptorString:(NSString *)string PrivateKeyStr:(NSString *)privateKeyStr
{
NSString *encrypStr;
privateKey = [RSA_Encryptor addPrivateKey:privateKeyStr];
if (privateKey)
{
encrypStr = [self rsaEncryptString:string SeckeyRefKey:privateKey];
}
else
{
encrypStr = @"获取私钥 失败";
}
return encrypStr;
}
- (NSString *)decryptString:(NSString *)string PublicKeyStr:(NSString *)publicKeyStr
{
NSString *decryptStr;
publicKey = [RSA_Encryptor addPublicKey:publicKeyStr];
if (publicKey)
{
decryptStr = [self rsaDecryptString:string SecKeyRefKey:publicKey];
}
else
{
return nil;
}
return decryptStr;
}
#pragma mark -------------------------------------
-(SecKeyRef) loadPrivateKeyFromFile: (NSString*) p12FilePath password:(NSString*)p12Password
{
NSData *p12Data = [NSData dataWithContentsOfFile:p12FilePath];
return [self loadPrivateKeyFromData: p12Data password:p12Password];
}
-(SecKeyRef) loadPrivateKeyFromData: (NSData*) p12Data password:(NSString*)p12Password
{
return [self getPrivateKeyRefrenceFromData: p12Data password: p12Password];
}
#pragma mark - Private Methods
-(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;
}
-(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);
// NSLog(@"privateKeyRef: %@", privateKeyRef);
return privateKeyRef;
}
#pragma mark 加密
-(NSString*) rsaEncryptString:(NSString*)string SeckeyRefKey:(SecKeyRef)encryptKey
{
NSData* data = [string dataUsingEncoding:NSUTF8StringEncoding];
// NSData* encryptedData = [self rsaEncryptData: data SeckeyRefKey:encryptKey];
NSData *encryptedData = [RSA_Encryptor encryptData:data withKeyRef:encryptKey];
NSString* base64EncryptedString = [encryptedData base64EncodedString];
return base64EncryptedString;
}
// 加密的大小受限于SecKeyEncrypt函数,SecKeyEncrypt要求明文和密钥的长度一致,如果要加密更长的内容,需要把内容按密钥长度分成多份,然后多次调用SecKeyEncrypt来实现
-(NSData*) rsaEncryptData:(NSData*)data SeckeyRefKey:(SecKeyRef)encryptKey
{
SecKeyRef key = encryptKey;
size_t cipherBufferSize = SecKeyGetBlockSize(key);
uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
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++) {NSInteger 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){
NSData *encryptedBytes = [[NSData alloc] initWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
[encryptedData appendData:encryptedBytes];
}
else
{
if (cipherBuffer)
{ free(cipherBuffer);
} return nil;
}
}
if (cipherBuffer)
{
free(cipherBuffer);
}
return encryptedData;
}
#pragma mark - 解密
-(NSString*) rsaDecryptString:(NSString*)string SecKeyRefKey:(SecKeyRef )decryptKey
{
NSData* data = [NSData dataWithBase64EncodedString: string];
// NSData* decryptData = [self rsaDecryptData: data SecKeyRefKey:decryptKey];
NSData* decryptData = [RSA_Encryptor decryptData:data withKeyRef:decryptKey];
NSString* result = [[NSString alloc] initWithData: decryptData encoding:NSUTF8StringEncoding];
return result;
}
+ (NSData *)encryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef
{
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
void *outbuf = malloc(block_size);
size_t src_block_size = block_size - 11;
NSMutableData *ret = [[NSMutableData alloc] init];
for(int idx=0; idx<srclen; idx+=src_block_size)
{
//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
size_t data_len = srclen - idx;
if(data_len > src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyEncrypt(keyRef,kSecPaddingPKCS1, srcbuf + idx,data_len, outbuf, &outlen);
if (status != 0)
{
NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
ret = nil;
break;
}else
{
[ret appendBytes:outbuf length:outlen];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}
+ (NSData *)decryptData:(NSData *)data withKeyRef:(SecKeyRef) keyRef{
const uint8_t *srcbuf = (const uint8_t *)[data bytes];
size_t srclen = (size_t)data.length;
size_t block_size = SecKeyGetBlockSize(keyRef) * sizeof(uint8_t);
UInt8 *outbuf = malloc(block_size);
size_t src_block_size = block_size;
NSMutableData *ret = [[NSMutableData alloc] init];
for(int idx=0; idx<srclen; idx+=src_block_size){
//NSLog(@"%d/%d block_size: %d", idx, (int)srclen, (int)block_size);
size_t data_len = srclen - idx;
if(data_len > src_block_size){
data_len = src_block_size;
}
size_t outlen = block_size;
OSStatus status = noErr;
status = SecKeyDecrypt(keyRef,
kSecPaddingNone,
srcbuf + idx,
data_len,
outbuf,
&outlen
);
if (status != 0) {
NSLog(@"SecKeyEncrypt fail. Error Code: %d", status);
ret = nil;
break;
}else{
//the actual decrypted data is in the middle, locate it!
int idxFirstZero = -1;
int idxNextZero = (int)outlen;
for ( int i = 0; i < outlen; i++ ) {
if ( outbuf[i] == 0 ) {
if ( idxFirstZero < 0 ) {
idxFirstZero = i;
} else {
idxNextZero = i;
break;
}
}
}
[ret appendBytes:&outbuf[idxFirstZero+1] length:idxNextZero-idxFirstZero-1];
}
}
free(outbuf);
CFRelease(keyRef);
return ret;
}
-(NSData*) rsaDecryptData:(NSData*)data SecKeyRefKey:(SecKeyRef )decryptKey
{
SecKeyRef key = decryptKey;
size_t cipherLen = [data length];
void *cipher = malloc(cipherLen);
[data getBytes:cipher length:cipherLen];
size_t plainLen = SecKeyGetBlockSize(key) - 12;
void *plain = malloc(plainLen);
OSStatus status = SecKeyDecrypt(key, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);
if (status != noErr) { return nil; }
NSData *decryptedData = [[NSData alloc] initWithBytes:(const void *)plain length:plainLen];
return decryptedData;
}
#pragma mark 用公私钥加解密
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++] != '\0') return(nil);
return([NSData dataWithBytes:&c_key[idx] length:len - idx]);
}
//credit: http://hg.mozilla.org/services/fx-home/file/tip/Sources/NetworkAndStorage/CryptoUtils.m#l1036
+ (NSData *)stripPrivateKeyHeader:(NSData *)d_key{
// Skip ASN.1 private 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 = 22; //magic byte at offset 22
if (0x04 != c_key[idx++]) return nil;
//calculate length of the key
unsigned int c_len = c_key[idx++];
int det = c_len & 0x80;
if (!det) {
c_len = c_len & 0x7f;
} else {
int byteCount = c_len & 0x7f;
if (byteCount + idx > len) {
//rsa length field longer than buffer
return nil;
}
unsigned int accum = 0;
unsigned char *ptr = &c_key[idx];
idx += byteCount;
while (byteCount) {
accum = (accum << 8) + *ptr;
ptr++;
byteCount--;
}
c_len = accum;
}
// Now make a new NSData from this buffer
return [d_key subdataWithRange:NSMakeRange(idx, c_len)];
}
+ (SecKeyRef)addPublicKey:(NSString *)key{
NSRange spos = [key rangeOfString:@"-----BEGIN PUBLIC KEY-----"];
NSRange epos = [key rangeOfString:@"-----END PUBLIC KEY-----"];
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
// This will be base64 encoded, decode it.
NSData *data = base64_decode(key);
data = [RSA_Encryptor stripPublicKeyHeader:data];
if(!data){
return nil;
}
//a tag to read/write keychain storage
NSString *tag = @"RSAUtil_PubKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *publicKey = [[NSMutableDictionary alloc] init];
[publicKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[publicKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)publicKey);
// Add persistent version of the key to system keychain
[publicKey setObject:data forKey:(__bridge id)kSecValueData];
[publicKey setObject:(__bridge id) kSecAttrKeyClassPublic forKey:(__bridge id)
kSecAttrKeyClass];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
kSecReturnPersistentRef];
CFTypeRef persistKey = nil;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)publicKey, &persistKey);
if (persistKey != nil){
CFRelease(persistKey);
}
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
[publicKey removeObjectForKey:(__bridge id)kSecValueData];
[publicKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[publicKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
[publicKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef = nil;
status = SecItemCopyMatching((__bridge CFDictionaryRef)publicKey, (CFTypeRef *)&keyRef);
if(status != noErr){
return nil;
}
return keyRef;
}
+ (SecKeyRef)addPrivateKey:(NSString *)key{
NSRange spos;
NSRange epos;
spos = [key rangeOfString:@"-----BEGIN RSA PRIVATE KEY-----"];
if(spos.length > 0){
epos = [key rangeOfString:@"-----END RSA PRIVATE KEY-----"];
}else{
spos = [key rangeOfString:@"-----BEGIN PRIVATE KEY-----"];
epos = [key rangeOfString:@"-----END PRIVATE KEY-----"];
}
if(spos.location != NSNotFound && epos.location != NSNotFound){
NSUInteger s = spos.location + spos.length;
NSUInteger e = epos.location;
NSRange range = NSMakeRange(s, e-s);
key = [key substringWithRange:range];
}
key = [key stringByReplacingOccurrencesOfString:@"\r" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\n" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@"\t" withString:@""];
key = [key stringByReplacingOccurrencesOfString:@" " withString:@""];
// This will be base64 encoded, decode it.
NSData *data = base64_decode(key);
data = [RSA_Encryptor stripPrivateKeyHeader:data];
if(!data){
return nil;
}
//a tag to read/write keychain storage
NSString *tag = @"RSAUtil_PrivKey";
NSData *d_tag = [NSData dataWithBytes:[tag UTF8String] length:[tag length]];
// Delete any old lingering key with the same tag
NSMutableDictionary *privateKey = [[NSMutableDictionary alloc] init];
[privateKey setObject:(__bridge id) kSecClassKey forKey:(__bridge id)kSecClass];
[privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
[privateKey setObject:d_tag forKey:(__bridge id)kSecAttrApplicationTag];
SecItemDelete((__bridge CFDictionaryRef)privateKey);
// Add persistent version of the key to system keychain
[privateKey setObject:data forKey:(__bridge id)kSecValueData];
[privateKey setObject:(__bridge id) kSecAttrKeyClassPrivate forKey:(__bridge id)
kSecAttrKeyClass];
[privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)
kSecReturnPersistentRef];
CFTypeRef persistKey = nil;
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)privateKey, &persistKey);
if (persistKey != nil){
CFRelease(persistKey);
}
if ((status != noErr) && (status != errSecDuplicateItem)) {
return nil;
}
[privateKey removeObjectForKey:(__bridge id)kSecValueData];
[privateKey removeObjectForKey:(__bridge id)kSecReturnPersistentRef];
[privateKey setObject:[NSNumber numberWithBool:YES] forKey:(__bridge id)kSecReturnRef];
[privateKey setObject:(__bridge id) kSecAttrKeyTypeRSA forKey:(__bridge id)kSecAttrKeyType];
// Now fetch the SecKeyRef version of the key
SecKeyRef keyRef = nil;
status = SecItemCopyMatching((__bridge CFDictionaryRef)privateKey, (CFTypeRef *)&keyRef);
if(status != noErr){
return nil;
}
return keyRef;
}
@end
// NSData+Base64.h
// RAS签名
//
// Created by user on 16/7/6.
// Copyright © 2016年 user. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface NSData (Base64)
+ (NSData *)dataWithBase64EncodedString:(NSString *)string;
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth;
- (NSString *)base64EncodedString;
@end
// NSData+Base64.m
// RAS签名
//
// Created by user on 16/7/6.
// Copyright © 2016年 user. All rights reserved.
//
#import "NSData+Base64.h"
@implementation NSData (Base64)
+ (NSData *)dataWithBase64EncodedString:(NSString *)string
{
const char lookup[] =
{
99, 99, 99, 99, 99,99, 99, 99, 99, 99,99, 99, 99, 99, 99,99,
99, 99, 99, 99, 99,99, 99, 99, 99, 99,99, 99, 99, 99, 99,99,
99, 99, 99, 99, 99,99, 99, 99, 99, 99,99, 62, 99, 99, 99,63,
52, 53, 54, 55, 56,57, 58, 59, 60, 61,99, 99, 99, 99, 99,99,
99, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,14,
15, 16, 17, 18, 19,20, 21, 22, 23, 24,25, 99, 99, 99, 99,99,
99, 26, 27, 28, 29,30, 31, 32, 33, 34,35, 36, 37, 38, 39,40,
41, 42, 43, 44, 45,46, 47, 48, 49, 50,51, 99, 99, 99, 99,99
};
NSData *inputData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
long long inputLength = [inputData length];
const unsigned char *inputBytes = [inputData bytes];
long long maxOutputLength = (inputLength /4 + 1) * 3;
NSMutableData *outputData = [NSMutableData dataWithLength:maxOutputLength];
unsigned char *outputBytes = (unsigned char *)[outputData mutableBytes];
int accumulator = 0;
long long outputLength =0;
unsigned char accumulated[] = {0,0, 0, 0};
for (long long i = 0; i < inputLength; i++)
{
unsigned char decoded = lookup[inputBytes[i] &0x7F];
if (decoded != 99)
{
accumulated[accumulator] = decoded;
if (accumulator == 3)
{
outputBytes[outputLength++] = (accumulated[0] <<2) | (accumulated[1] >>4);
outputBytes[outputLength++] = (accumulated[1] <<4) | (accumulated[2] >>2);
outputBytes[outputLength++] = (accumulated[2] <<6) | accumulated[3];
}
accumulator = (accumulator +1) % 4;
}
}
//handle left-over data
if (accumulator > 0) outputBytes[outputLength] = (accumulated[0] <<2) | (accumulated[1] >>4);
if (accumulator > 1) outputBytes[++outputLength] = (accumulated[1] <<4) | (accumulated[2] >>2);
if (accumulator > 2) outputLength++;
//truncate data to match actual output length
outputData.length = outputLength;
return outputLength? outputData: nil;
}
- (NSString *)base64EncodedStringWithWrapWidth:(NSUInteger)wrapWidth
{
//ensure wrapWidth is a multiple of 4
wrapWidth = (wrapWidth /4) * 4;
const char lookup[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
long long inputLength = [self length];
const unsigned char *inputBytes = [self bytes];
long long maxOutputLength = (inputLength /3 + 1) * 4;
maxOutputLength += wrapWidth? (maxOutputLength / wrapWidth) *2: 0;
unsigned char *outputBytes = (unsigned char *)malloc(maxOutputLength);
long long i;
long long outputLength =0;
for (i = 0; i < inputLength -2; i += 3)
{
outputBytes[outputLength++] = lookup[(inputBytes[i] &0xFC) >> 2];
outputBytes[outputLength++] = lookup[((inputBytes[i] &0x03) << 4) | ((inputBytes[i +1] & 0xF0) >>4)];
outputBytes[outputLength++] = lookup[((inputBytes[i +1] & 0x0F) <<2) | ((inputBytes[i + 2] & 0xC0) >> 6)];
outputBytes[outputLength++] = lookup[inputBytes[i +2] & 0x3F];
//add line break
if (wrapWidth && (outputLength + 2) % (wrapWidth + 2) == 0)
{
outputBytes[outputLength++] ='\r';
outputBytes[outputLength++] ='\n';
}
}
//handle left-over data
if (i == inputLength - 2)
{
// = terminator
outputBytes[outputLength++] = lookup[(inputBytes[i] &0xFC) >> 2];
outputBytes[outputLength++] = lookup[((inputBytes[i] &0x03) << 4) | ((inputBytes[i +1] & 0xF0) >>4)];
outputBytes[outputLength++] = lookup[(inputBytes[i +1] & 0x0F) <<2];
outputBytes[outputLength++] = '=';
}
else if (i == inputLength -1)
{
// == terminator
outputBytes[outputLength++] = lookup[(inputBytes[i] &0xFC) >> 2];
outputBytes[outputLength++] = lookup[(inputBytes[i] &0x03) << 4];
outputBytes[outputLength++] ='=';
outputBytes[outputLength++] ='=';
}
//truncate data to match actual output length
outputBytes = realloc(outputBytes, outputLength);
NSString *result = [[NSString alloc] initWithBytesNoCopy:outputBytes length:outputLength encoding:NSASCIIStringEncoding freeWhenDone:YES];
#if !__has_feature(objc_arc)
[result autorelease];
#endif
return (outputLength >= 4)? result: nil;
}
- (NSString *)base64EncodedString
{
return [self base64EncodedStringWithWrapWidth:0];
}
@end
下面是一对公私钥:
#define RSA_PUBLIC_KEY @"-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC2IUXzxYudB9+AeVZRoGaRaCkUEpIGAi7pMfDv98/akGoDZXt8LOeGQDLQrXxn78YLPlrC2lBUKuDAOtdkacGZidQwzOeS8IgdU2caN0dq9IFGlZb9Ud+ryIXgyj+mfQB5Df0vsm/DGA7j6vFxqbNfv/To0Dhd0375lb5aj7yr/QIDAQAB\n-----END PUBLIC KEY-----"
#define RSA_PRIVATE_KEY @"MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALYhRfPFi50H34B5VlGgZpFoKRQSkgYCLukx8O/3z9qQagNle3ws54ZAMtCtfGfvxgs+WsLaUFQq4MA612RpwZmJ1DDM55LwiB1TZxo3R2r0gUaVlv1R36vIheDKP6Z9AHkN/S+yb8MYDuPq8XGps1+/9OjQOF3TfvmVvlqPvKv9AgMBAAECgYAScoBRVprzhs6ehqu1jNeWtsQiYlckAKibuhE7XRBShPoX6fl99FZnBK2g8VF+fYzDqscqoU4tmEI3dj5Gz2dqaALz1d1m0H9z8MJyP+/oSDTDlwAq4KHhZYj38Gy0xjGxlpRRoDdWNm4hG3Ysvpx5rmINpB8HJqjbSedn5OSXiQJBAOCKf1BiE0oOGY1H7wzo3vxEEYuH5uxclOxew4nE22CrxAK8RqxywxvFp10GHzxsUO+xSx0i6da6Bgs6HMQH6KsCQQDPpaPhNS2pyHDUdA05P+rCl50FmDt3TN1XoGKxm1+1a1CvZLEBUsD6WDfJuVUsXN/2JWEk+0Gh6G8ToUAs3433AkEAg1zjUN6f1FJdZocv9kiCs+kKrqvKUHt1cLecBAyUH4E9wi/t1NOrC6Nd35FGUu43h5Mck6YqUcIw6P6Nd6380wJAByHOVi7oaZt73KA70AqU+qgQeZ+38yoNtDPLEAShLe8Ir22K8tuvyyl6iRA3j7WE78Rq6MVEhNYh8o+oT6JCEwJBALkEV98syyoQLVfSdxBY5P0dAXy7lQNgJ1enYMlxThD7HxHLN4z7wqfGUvb7V/wHYTc1jxpxKz2WzCJ10TnHBUk="
加解密的使用可以参考:
RSA_Encryptor *rsa = [RSA_Encryptor sharedRSA_Encryptor];
NSString *encryptedString = [rsa encryptorString:@"这是需要RSA加密字符串" PublicKeyStr:RSA_PUBLIC_KEY];
NSLog(@"加密==:%@",encryptedString);
NSString *decryptedString = [rsa decryptString:encryptedString PrivateKeyStr:RSA_PRIVATE_KEY];
NSLog(@"解密==:%@",decryptedString);