Java中的RSA加密

Mag*_*eed 5 java security encryption rsa

我试图在Java中使用RSA编写加密算法,我得到一个"javax.crypto.BadPaddingException:数据必须从零开始"; 我不知道这个例外是什么.这是我在这里使用的例子

这是我的代码; 请帮忙.

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

moh*_*gdy 2

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