2

我正在尝试从我的服务器端解密一个 RSA 字符串。从本地服务器运行代码时效果很好,但是在将应用程序部署到 GAE 时,该方法返回一个空字符串(非 null)。

(字符串输入是要解密的二进制数据的BASE64表示)

这是我的代码:

private static String decrypt(String pwd) {
    byte[] input = Base64.decode(pwd);


    try {
        rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");
    } catch (NoSuchAlgorithmException e) {
        return null;
    } catch (NoSuchPaddingException e) {
        return null;
    }

    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        return null;
    }

    String modString = "*********";
    String privateExponentString = "*********";

    RSAPrivateKeySpec prvKeySpec = new RSAPrivateKeySpec(new BigInteger(modString), new BigInteger(privateExponentString));
    RSAPrivateKey prvKey;


    try {
        prvKey = (RSAPrivateKey) keyFactory.generatePrivate(prvKeySpec);
    } catch (InvalidKeySpecException e) {
        return null;
    }

    try {
        rsaCipher.init(Cipher.DECRYPT_MODE, prvKey);
    } catch (InvalidKeyException e) {
        return null;
    }
    byte[] cipherText;
    try {
        cipherText = rsaCipher.doFinal(input);
    } catch (IllegalBlockSizeException e) {
        return null;
    } catch (BadPaddingException e) {
        return null;
    }
    return new String(cipherText);
}

我在远程运行时在服务器端做了一些调试。我发现这个功能:

rsaCipher.doFinal(input);

当每个项目都包含“0”时,返回一个字节数组。

请指教,

谢谢你和最好的问候,诺姆科恩

4

2 回答 2

0

我发现了错误,输出字符串始终为 128 位长,所需的未加密字符串位于末尾,而所有其他字节均为(null,ASCII 代码 0)。谷歌日志没有显示所有的字符串,它看起来像是空的。我只是循环输出字符串中的每个字符,并将每个字符复制到我的字符串中,ASCII 码不同于 0。

我希望这会对某人有所帮助,诺姆

于 2013-08-18T09:22:15.533 回答
0

使用new String(byteArray)默认 JVM 编码将字节数组解码为字符串。在 AppEngine 上,奇怪的是 US-ASCII。

如果您的原始内容是 UTF-8,请尝试使用new String(cipherText), "UTF-8"

于 2013-08-08T12:29:23.303 回答