终端 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