标签:
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 = @"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALgv/syFH337KzC29KvR0p6cP+glRqjDYAQno5ifafXZjgf1EhBjZblKv+HiLAzNBOlYU1PnLuOOkZj6pg1A5HUZLpsbYa5Mwr1bUHALjXLaB3THCpZX51/b5L14erGo52Jv/j/63YljEtMm8ALmkY8S+3fPxFeY7ya+2VXMEtplAgMBAAECgYAguvauZWGpQ37zUy+7cLfa061PlYAu8TkYw+qAbqOnupdQtq4VF3S2LqBWhZiKVcxvovB70nM0oNsisjfb1xJBpyfDBFug7d+y2f8yr6aTOezoY5DBYEF3Svg9Kp9ra+vvAYX/7fh+tHCU0HOvp0z8ikZiRSWZaQ+3A2GiCIJrwQJBAPKVji89hGAMEWLJJFZaPiLBqZUwR2W/rp7Ely5ddKfjcosHhggHfOb71BnrMOm0h4S85Gx6a87n9R2To0c51q0CQQDCX6yYdt/9JGORyNSXfzMfSZyVOrMpIo77R0YwKa3UOwwLA56l2Lc4AYO10/lyAyZCKse2/5D9ZZUB7xoYEmGZAkB8MEJVPuoY/bSc3RqENrjetERsAwZaObJcx4oaC3AgTxmhwV1FmQfBfKTODBDDZE+Ijedm/ZlZmHhtBtstKJgVAkBKma/DgHRtUscIT90QHBjB3F3FhJb4pbPcyzksCQMXXmY73/LG0ktXqnUjlyy4zm6jnIm0OZgrOQ6chGkubfeZAkBMCGF2tPfEJh8XODOvlw5ADnUiq+Qe/abcpKowkiT9zP+rYT9XJAx7QxChjdwTZb6ahnJY1+ny1emEHUOs2fm8"; NSString* public_key_string = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC4L/7MhR99+yswtvSr0dKenD/oJUaow2AEJ6OYn2n12Y4H9RIQY2W5Sr/h4iwMzQTpWFNT5y7jjpGY+qYNQOR1GS6bG2GuTMK9W1BwC41y2gd0xwqWV+df2+S9eHqxqOdib/4/+t2JYxLTJvAC5pGPEvt3z8RXmO8mvtlVzBLaZQIDAQAB"; 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);
4 结果验证(注:公钥加密,每次加密的结果会不一样,但是私钥签名的结果每次都一样)
标签:
原文地址:http://www.cnblogs.com/limicheng/p/5507587.html