【发布时间】:2011-03-05 20:00:15
【问题描述】:
情况:
我想要一个使用 RSA 加密字符串的应用程序。我将公钥存储在 res/raw 中,由于密钥为 1024 位,因此生成的字符串必须为 128 字节长。但是加密后得到的字符串是124长,导致解密崩溃。
我用来恢复公钥的函数是:
private PublicKey getPublicKey() throws Exception {
InputStream is = getResources().openRawResource(R.raw.publickey);
DataInputStream dis = new DataInputStream(is);
byte [] keyBytes = new byte [(int) is.available()];
dis.readFully(keyBytes);
dis.close();
X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePublic(spec);
}
以及我用来加密的函数代码:
private String rsaEncrypt (String plain) {
byte [] encryptedBytes;
Cipher cipher = Cipher.getInstance("RSA");
PublicKey publicKey = getPublicKey();
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
encryptedBytes = cipher.doFinal(plain.getBytes());
String encrypted = new String(encryptedBytes);
return encrypted;
}
P.D.:该代码在桌面应用程序中运行良好,只是在 Android 中崩溃。
我真的很感激任何帮助,
非常感谢。
【问题讨论】: