終端 cd Desktop/ 到桌面 執行下面代碼 生成公鑰加密文件,私鑰解密文件。
openssl
OpenSSL> genrsa -out rsa_private_key.pem 1024
OpenSSL> pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM –nocrypt
OpenSSL> rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
將密鑰文件拉到工程中, 調用
-(void)Addencrypt
{
//公鑰加密文件
NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"rsa_public_key.pem" ofType:nil];
publicKey = [NSString stringWithContentsOfFile:publicKeyPath encoding:NSUTF8StringEncoding error:nil];
//私鑰解密文件
NSString * privatePath = [[NSBundle mainBundle] pathForResource:@"rsa_private_key.pem" ofType:nil];
privateKey = [NSString stringWithContentsOfFile:privatePath encoding:NSUTF8StringEncoding error:nil];
}
需要加密的地方:
NSString * phone_publicKey = [Encryption addText:self.worldtext.text addkeypublickey:publicKey]; //加密
NSString * phone_privateKey = [Encryption addText:phone_publicKey addkeyprivatekey:privateKey]; //解密
記得 viewDidLoad 調用
[self Addencrypt];
RSA算法類:
私類:
BPG.h
import <Foundation/Foundation.h>
@interface Encryption : NSObject
+(NSString *)addText:(NSString )textstr addkeypublickey:(NSString )publicKey ;
+(NSString *)addText:(NSString *)textstr addkeyprivatekey:(NSString *)privateKey;
@end
BPG.m
import "Encryption.h"
import "HYEncrypt.h"
@implementation Encryption
+(NSString *)addText:(NSString *)textstr addkeypublickey:(NSString *)publicKey
{
NSString *encryptString = nil;
if (textstr.length)
{
//字符串轉化為data
NSData *plainTextBytes = [textstr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"data --%@",plainTextBytes);
//RSA加密的長度限制
NSString * URLStr = [[NSBundle mainBundle] pathForResource:@"rsa_public_key.pem" ofType:nil];
size_t blockSize = URLStr.length /8 ;//計算塊,后臺匹配
//根據RSA長度限制把data分為N塊進行加密
size_t blockCount = (size_t)ceil([plainTextBytes length] / (double)blockSize);
NSMutableData *encryptedData = [[NSMutableData alloc]init];
//分段加密
for (size_t i = 0; i < blockCount; i++)
{
size_t bufferSize = MIN(blockSize,[plainTextBytes length] - i * blockSize);
// 第一個參數0表示的是從哪里開始截取(數據的下標)
// 第二個參數2表示截取的數據長度是多少
NSData *buffer = [plainTextBytes subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
//加密 返回data
NSData *encryptData = [HYEncrypt encodeByRsaOfData:buffer secretKeyPublic:publicKey];
//拼接加密以后的data
[encryptedData appendData:encryptData];
}
//base64編碼
encryptString = [NSMutableString stringWithString:[encryptedData base64EncodedStringWithOptions:0]];
}
NSLog(@"encryptString---加密--%@",encryptString);
return encryptString;
}
+(NSString *)addText:(NSString *)textstr addkeyprivatekey:(NSString *)privateKey
{
//獲取加密數據,base64編碼數據
NSString *encryptString = textstr;
// NSLog(@"text:%@",textstr);
NSString *decryptString = [HYEncrypt decodeByRsaOfString:encryptString secretKeyPrivate:privateKey];
NSLog(@"decrypt----解密---%@",decryptString);
return decryptString;
}
@end