【问题标题】:String RSA encryption in AndroidAndroid中的字符串RSA加密
【发布时间】: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 中崩溃。

我真的很感激任何帮助,

非常感谢。

【问题讨论】:

    标签: android string rsa


    【解决方案1】:

    String encrypted = new String(encryptedBytes);

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

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

    最后,当人们使用new String(...)String.getBytes() 的默认字符集版本时,这是我最讨厌的事情之一。这很少是正确的做法,尤其是 Java 声称“一次编写,到处运行”。默认字符集在不同的平台上是不同的,即使你做的一切都正确,也会在你的代码中触发一个错误。您应该始终指定特定的字符集。在我见过的每一种情况下,简单地使用 UTF-8 字符集 (Charset.forName("UTF-8");) 将始终有效地表示数据。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-30
      • 1970-01-01
      • 2014-10-29
      • 2014-05-18
      相关资源
      最近更新 更多