一、首先需要公钥、私钥, 以及传递给 java后端的私钥,
我们在这里使用openSSL在终端生成所需要的公私钥, 步骤如下:
- 操作1:
生成本地私钥, 用于本地解密
1024位 = 128字节 (即最多一次可以加密128-1 字节的数据, 也可以是2048位)
// #!/usr/bin/env bash
// echo "Generating RSA key pair ..."
// echo "1024 RSA key: private_key.pem"
终端输入:
openssl genrsa -out private_key.pem 1024```
- 操作2:
echo "create certification require file: rsaCertReq.csr"
openssl req -new -key private_key.pem -out rsaCertReq.csr```
操作3:秘钥有效期10年
echo "create certification using x509: rsaCert.crt"
openssl x509 -req -days 3650 -in rsaCertReq.csr -signkey private_key.pem -out rsaCert.crt
操作4:iOS本地用于加密的der文件
echo "create public_key.der For IOS"
> ```
openssl x509 -outform der -in rsaCert.crt -out public_key.der```
操作5:本地用于解密的私钥 p12文件
echo "create private_key.p12 For IOS. Please remember your password. The password will be used in iOS."
> ```
openssl pkcs12 -export -out private_key.p12 -inkey private_key.pem -in rsaCert.crt```
操作6:
echo "create rsa_public_key.pem For Java"
> ```
openssl rsa -in private_key.pem -out rsa_public_key.pem -pubout```
操作7: 此秘钥发给后台用于解密
echo "create pkcs8_private_key.pem For Java"
> ```openssl pkcs8 -topk8 -in private_key.pem -out pkcs8_private_key.pem -nocrypt```
到此生成证书和公司要的步骤结束 -->||
--- ---
--- ---
二、下载加密类文件
[点击下载iOS加密类文件 + Base64编码库](https://github.com/initKing/Base64_Code_Lib/tree/master)
## 仔细阅读链接的README文件,有具体的使用方法!
* 生成加密类实例
```RSAEncryptor * rsa = [[RSAEncryptor alloc] init];```
获取公钥路径(注意拖拽公钥的时候,记得将“添加到目标”选项打钩,否则通过[Bundle mainBundle]查询不到公钥的路径)
```NSString * publicKeyPath = [[NSBundle mainBundle] pathForResource:@“public_key”ofType:@“der”];```
* 加载公钥
```[rsa loadPublicKeyFromFile:publicKeyPath];```
```NSString * parm1 = @“need to encript string”;```
* 对参加加密
```NSString * encParam1 = [rsa rsaEncryptString:parm1];```
#### 关于待机密数据过长问题-分段加密-分段解析实施思路
> 1. 然后将加密后的密文传递给后台
> 2. 如果需要加密的数据长度过长(超过128字节),那么会导致数据加密不完全,无法完全解析
> 3. 解决办法就是:对待加密的数据进行'分段加密'
```NSString *param = @"this is a long string, or other kind of objects, in the final analysis this is a long long string or object neet to encript, more than 128 byte";```
* 分割字符串:
NSString *segment1 = @"this is a long string, or other kind of objects,";
NSString *segment2 = @" in the final analysis this is a long long string or object neet to encript, more than 128 byte";
* 然后分别加密:
```NSString *encString1 = [rsa rsaEncryptString:segment1];```
```NSString *encString2 = [rsa rsaEncryptString:segment2];```
* 然后将加密后的密文拼接,中间可以加个空格,方便后台根据空格分割密文,进行分段解析
NSString *result = [NSString stringWithFormat:@"%@ %@",encString1, encString2];