0%

Android端RSA加密,后端无法解密的情况

2019-10-31 20:11

做BOC支付时,需要对文件进行RSA签名
但是正确的数据,正确的bytes,正确的秘钥
却始终无法得到正确的结果
使用的是给出的RSA工具,其中java环境运行良好,代码如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
/**
* 私钥加密
*
* @param data
* @param PrivateKey
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String PrivateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(PrivateKey);
PKCS8EncodedKeySpec pKCS8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
if (keyFactory == null) {
initKeyFactory(KEY_ALGORITHM);
}
Key privateK = keyFactory.generatePrivate(pKCS8EncodedKeySpec);
if (cipher == null) {
initCipher();
}
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}

其中cache = cipher.doFinal(data, offSet, inputLen - offSet);
返回数据错误
多方查证cipher的正确初始化方法为Cipher cipher = Cipher.getInstance(“RSA/ECB/PKCS1Padding”);