【问题标题】:Java IllegalBlockSizeException for data longer than 512 bytes超过 512 字节的数据的 Java IllegalBlockSizeException
【发布时间】:2018-07-21 05:41:12
【问题描述】:

我写了一点聊天和消息是对象

{type="message",sender="userA",content="plaintextmessage",recipient="userB"}

发送到服务器,然后将其传播给所有注册用户。我想加密消息对象看起来像的纯文本消息部分

{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。这是我的新目标吗?

【问题讨论】:

  • 是的,您不使用非对称加密来加密通用数据。

标签: java encryption


【解决方案1】:

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

因此,您的目标要么是更详细地研究该领域,要么是少了解有关部署 TLS 1.2 或 1.3 的知识。因为实现传输模式安全需要很多细节。

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

【讨论】:

  • 它仅供私人使用,我想我不会成为加密专家,所以是的,我会继续。但是我应该继续不对称的方式吗?
  • 在这种情况下,混合模式也显示在另一个答案中:加密随机 AES 密钥,加密数据,同时发送。然后进行解密:解密 AES 密钥,然后解密数据。以防万一你还没有得到它:让它工作!=让它安全。
  • 我知道,但我所知道的人只是邻居之类​​的,所以可以对他们稍微“安全一点”;P 谢谢
猜你喜欢
  • 1970-01-01
  • 2020-06-10
  • 2012-04-17
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2013-02-01
  • 1970-01-01
相关资源
最近更新 更多