对于长度超过512字节的数据,Java IllegalBlockSizeException

时间:2018-02-10 16:32:04

标签: java encryption

我写了一个小聊天,消息就像

这样的对象
{type="message",sender="userA",content="plaintextmessage",recipient="userB"}
发送给服务器的

将其传播给所有注册用户。我想加密消息对象看起来像

的plaintextmessage-part
{type="message",sender="userA",content="bHJg67&GghjGZuf/zdu=",recipient="userB"}

我已经在服务器和客户端上构建了我的RSA密钥对。

KeyPair keyPair = buildKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

然后我将服务器公钥编码为字节数组,并将此数组编码为base64编码字符串并将其发送给客户端。

byte[] encodedPublicKey = publicKey.getEncoded();
String b64PublicKey = Base64.getEncoder().encodeToString(encodedPublicKey);

客户端和服务器都实现了功能

public static byte[] encrypt(PublicKey othersPubKey, String message) throws Exception {       
    Cipher cipher = Cipher.getInstance("RSA");  
    cipher.init(Cipher.ENCRYPT_MODE, othersPubKey);  
    return cipher.doFinal(message.getBytes());        
}

public static byte[] decrypt(PrivateKey privateKey, byte [] encrypted) throws Exception {   
    Cipher cipher = Cipher.getInstance("RSA");  
    cipher.init(Cipher.DECRYPT_MODE, privateKey);        
    return cipher.doFinal(encrypted);
}

当我尝试加密客户端上的邮件时,将其发送到服务器并在那里解密我收到错误

javax.crypto.IllegalBlockSizeException: Data must not be longer than 512 bytes

这是否意味着此加密方法不适合我的邮件?我找到了Java/JCE: Decrypting "long" message encrypted with RSA。这是我的新目标吗?

1 个答案:

答案 0 :(得分:1)

是的,它被称为混合密码系统。即便如此,您可能想要了解Bleichenbacher攻击,使用经过身份验证的加密,如何获得对公钥的信任等。

因此,您的目标是在更多更多详细信息中研究该字段,或者更少地了解有关部署TLS 1.2或1.3的信息。因为实现传输模式安全性需要很多细节。

如果您想继续,请至少查看OAEP模式下的RSA和GCM模式下的AES。