iOS RSA 加密解密及签名验证!
1.首先要下载openssl。这个不用说,直接官网下载或者用brew install openssl下载。
2.终端生成私钥**。
2.1生成私钥
openssl genrsa -out rsa_private_key.pem 1024
2.2生成**
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
2.3将RSA私钥转换为pkcs8 格式
openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_private_key.pem
私钥及**地址在根目录文件 rsa_private_key.pem rsa_public_key.pem
问价可通过右键文件编辑器打开查看
也可以通过终端命令cat rsa_private_key.pem 及 cat rsa_pubilic_key.pem 查看私钥**字符串
3.导入openssl ,导入HBRSAHandler 文件夹。
小技巧:拖进去后:librarySearchpath:会自动设置,然后拷贝路径到headSearchpath,后边添加/include。
4.使用:
两种方式导入**然后调用响相应的方法即可。
NSString* private_key_string = @"MIICdQIBA.......";
NSString* public_key_string = @"MIGfMA0GC.......";
NSString *publicKeyFilePath = [[NSBundle mainBundle] pathForResource:@"rsa_public_key.pem" ofType:nil];
NSString *privateKeyFilePath = [[NSBundle mainBundle] pathForResource:@"rsa_private_key.pem" ofType:nil];
HBRSAHandler* handler = [HBRSAHandler new];
//两种方式导入
// [handler importKeyWithType:KeyTypePublic andPath:publicKeyFilePath];
//[handler importKeyWithType:KeyTypePrivate andPath:privateKeyFilePath];
[handler importKeyWithType:KeyTypePrivate andkeyString:private_key_string];
[handler importKeyWithType:KeyTypePublic andkeyString:public_key_string];
NSString* sig = [handler signString:@"签名字符串"];
NSString* sigMd5 = [handler signMD5String:@"签名字符串"];
NSLog(@"%@%@",sig,sigMd5);
BOOL isMatch = [handler verifyString:@"签名字符串" withSign:sig];
BOOL isMatchMd5 = [handler verifyMD5String:@"签名字符串
NSLog(@"%d%d",isMatch,isMatchMd5);
NSString* enString = [handler encryptWithPublicKey:@"加密字符串"];
NSString* deString = [handler decryptWithPrivatecKey:enString];
NSLog(@"%@",deString);
5.结果验证(注:公钥加密,每次加密的结果会不一样,但是私钥签名的结果每次都一样)