我想使用java标准库,并且据我所知,其功能输入是有限的。所以我为此实现了两种方法。在这里,他们是:RSA加密和解密java中的长消息
private byte[] RSAenc(String in) throws Exception {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.ENCRYPT_MODE, privKey);
int l = in.length();
byte[] part;
byte[] result = new byte[(int)(64*java.lang.Math.ceil(l/20.0))];
int i = 0;
while(i*20+20<l) {
part = c.doFinal(in.substring(i*20,i*20+19).getBytes("UTF-8"));
System.arraycopy(part, 0, result, i*64, part.length);
i = i+1;
}
part = c.doFinal(in.substring(i*20,l-1).getBytes("UTF-8"));
System.arraycopy(part, 0, result, i*64, part.length);
return result;
}
private String RSAdec(byte [] in) throws Exception {
Cipher c = Cipher.getInstance("RSA");
c.init(Cipher.DECRYPT_MODE, privKey);
String result = "";
byte[] part = new byte[64];
int l = in.length;
int i = 0;
while(i+64<=l) {
System.arraycopy(in, i, part, 0, part.length);
result = result + new String(c.doFinal(part), "UTF-8");
i= i+64;
}
return result;
}
他们以这种方式工作:加密我打破字符串最多,20种大小子,然后用密码加密它们。对于解密,我将字节数组分成64字节块,并对它们应用密码解密。 有没有这样做的功能?或者至少有没有更好的解决方案?我的方法有多安全?在JRE的所有发行版上加密结果长度(result.length
)始终为64?
Thanx,
另请参见[如何使用非对称加密,例如RSA来加密任意长度的明文?](http://crypto.stackexchange.com/questions/14/how-can-i-use-asymmetric -cryption-such-as-rsa-to-encrypt-an-any-length)在crypto.stackexchange.com上。 –