0

我正在编写用于跟踪密码的 Java 程序的 Android 版本。

我有以下函数用于解码一行加密数据:

public String decrypt(String text) {
    byte[] decryptedText = null;
    String rtn = "";
    String[] byteValues = text.substring(1, text.length() - 1).split(",");
    byte[] bytes = new byte[byteValues.length];
    for (int i=0, len=bytes.length; i<len; i++) {
        bytes[i] = Byte.valueOf(byteValues[i].trim());     
    }
    try {
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        decryptedText = cipher.doFinal(bytes);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    if (decryptedText != null) {
        try {
            rtn = new String(decryptedText, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    return rtn;
}

算法设置为:

public static final String ALGORITHM = "RSA";

输入文本看起来像这样(有 128 个值):

[12, -27, -31, 2, -65, -119, -104, -9, -42, 6, -32, -116, 35, 14, -30, -51, 117, 21, -33, -98, 21, 41, -11, 118, 85, -46, -67, -19, 47, -10, -42, -18, -116, 87, 49, 76, 25, 114, 88, -100, 41, 74, -70, 73, -103, 78, 117, 123, 127, -4, 98, -6, -124, -69, -112, -51, 27, 46, -83, 5, -84, 22, -64, -92, 15, -85, 34, -44, -50, 28, -69, 28, 106, -75, -7, 63, 112, 22, 112, -85, -28, 29, 97, -51, 112, -52, -2, 60, -55, -57, 41, 78, -90, -55, -1, -128, 12, 10, 73, -95, -105, 38, -125, 123, 89, 35, 63, 100, 124, 64, -4, 11, -50, -100, -81, -66, -64, 94, -93, -72, 67, 3, 22, -126, -125, 24, 127, -74]

当我将此函数作为 Java 程序(Java 1.6 和 1.7)的一部分运行时,我得到了我期望的原始字符串。但是,当我将它作为我的 Android 应用程序的一部分运行时,decryptedText 数组的长度不是大约 30,而是始终为 127。生成的返回字符串在前面有各种垃圾字符,但最后一部分字符串是正确解码的文本。

我应该doFinal在 Android 上调用不同于 Java 的调用吗?

4

1 回答 1

1

问题是算法的设置。当我将其更改为:

public static final String ALGORITHM = "RSA/ECB/PKCS1Padding";

一切正常。

于 2013-11-12T21:09:57.660 回答