Android中的字符串RSA加密

Ull*_*oll 6 string android rsa

情况:

我想要一个使用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);
}
Run Code Online (Sandbox Code Playgroud)

以及我用来加密的函数的代码:

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;
Run Code Online (Sandbox Code Playgroud)

}

PD:代码在桌面应用程序中完美运行,它只是在Android中崩溃.

我真的很感激任何帮助,

非常感谢你.

Jam*_*olk 6

String encrypted = new String(encryptedBytes);

是个bug.加密转换的输出是二进制字节.您无法将它们可靠地存储为字符串.

使用is.available()可能也是一个错误,但在这种情况下我不确定.

最后,这是我的眼中钉之一,当人们使用的默认字符集的版本new String(...)String.getBytes().它很少是正确的事情,尤其是Java声称"一次编写,随处运行".默认字符集在不同平台上是不同的,即使您正确执行其他任何操作,也会触发代码中的错误.您应该始终指定特定的字符集.在我见过的每一种情况下,只需使用UTF-8 Charset(Charset.forName("UTF-8");)就可以有效地工作和表示数据.