Java中的RSA加密

5
我正在尝试使用Java编写RSA加密算法,但是遇到了"javax.crypto.BadPaddingException: Data must start with zero"的错误提示;我不知道这个异常是什么意思。 这是我使用的示例链接
以下是我的代码,请帮忙检查。
public byte[] getEncryptedValue(byte[] bytes, PublicKey key) {
    try {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        return blockCipher(bytes, Cipher.ENCRYPT_MODE);
    } catch (Exception ex) {
        Logger.getLogger(SecurityUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

public byte[] getDecryptedValue(byte[] bytes, PrivateKey key) {
    try {
        cipher.init(Cipher.DECRYPT_MODE, key);
        return blockCipher(bytes, Cipher.DECRYPT_MODE);
    } catch (Exception ex) {
        Logger.getLogger(SecurityUtil.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

private byte[] append(byte[] prefix, byte[] suffix) {
    byte[] toReturn = new byte[prefix.length + suffix.length];
    System.arraycopy(prefix, 0, toReturn, 0, prefix.length);
    System.arraycopy(suffix, 0, toReturn, prefix.length, suffix.length);
    return toReturn;
}

private byte[] blockCipher(byte[] bytes, int mode) throws IllegalBlockSizeException, BadPaddingException {
    byte[] scrambled = new byte[0];
    byte[] toReturn = new byte[0];blocks (because of RSA)
    int length = (mode == Cipher.ENCRYPT_MODE) ? 100 : 128;
    int n = 0;
    byte[] buffer = new byte[length];

    for (int i = 0; i < bytes.length; i++) {
        if ((i > 0) && (i % length == 0)) {
            n = 0;
            scrambled = cipher.doFinal(buffer);
            toReturn = append(toReturn, scrambled);
        }
        buffer[i % length] = bytes[i];
        n++;
    }
    ***scrambled = cipher.doFinal(buffer, 0, n);*** <-- the exception is caught here
    toReturn = append(toReturn, scrambled);
    return toReturn;
}

你在加密或解密时遇到了异常吗? - sinha
1
在发布问题之前,您是否搜索过javax.crypto.BadPaddingException?这看起来可能是thisthis的重复。正确的答案是:您没有正确将十六进制字符串转换回字节数组以进行解密。 - this.josh
称呼我蠢,但变量'cipher'是如何初始化的,它的内容是什么? 似乎没有声明,还是全局的? - bl4ckb0l7
2个回答

2

问题可能是使用套接字发送到网络上的数据由于某些编码问题而损坏。在开发一个简单的客户端/服务器聊天程序时,我遇到了同样的问题,该程序使用非对称密钥加密/解密服务器和客户端之间以及反之的消息,但我将消息作为字节数组而不是字符串发送,这是加密后的消息。


0
  • 检查密钥是否匹配
  • 检查由getEncryptedValue返回的数据是否与传递给getDecryptedValue的数据相同
  • 检查blockCipher方法中循环的正确性

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接