对加密方面不太熟,请大佬帮忙看看
public static String encryptByPublicKey(String source, byte[] key) throws Exception {
byte[] data = source.getBytes("utf-8");
byte[] keyBytes = key;
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
Key publicKey = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(1, publicKey);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
int i = 0;
while (inputLen - offSet > 0) {
byte[] cache;
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 (new String(Base64.encodeBase64(encryptedData), "UTF8")).replaceAll("\r\n", "");
}
1
liprais 2022-10-04 09:36:10 +08:00 via iPhone
RSA/ECB/PKCS1Padding
这不都写了 |
4
wangsongyan 2022-10-04 10:08:49 +08:00
贴出 go 代码和对应的 Java 明文、key 、密文更好解决
|
5
eason1874 2022-10-04 10:16:53 +08:00
很明显是内置标准 RSA 库,但他是分块加密,然后再把结果拼接起来,所以你解密的时候也要分块
MAX_ENCRYPT_BLOCK 是它明文块长度,根据它可以算出密文块有多长,不过代码里应该还有对应的 MAX_DECRYPT_BLOCK 表示密文块有多长,直接看那个就行 |
6
seers OP |
7
lysS 2022-10-04 10:26:26 +08:00
最后对密文算了 base64 的,要用 DecryptPKCS1v15 进行解密
|
9
Bingchunmoli 2022-10-04 11:24:11 +08:00 via Android
@seers 因为不改的话,加密长度问题可能抛异常
|