我写了一些聊天内容,消息是类似的对象
{type="message",sender="userA",content="plaintextmessage",recipient="userB"}
发送到服务器,服务器将其传播给所有注册用户。我想加密消息对象的明文消息部分
{type="message",sender="userA",content="bHJg67&GghjGZuf/zdu=",recipient="userB"}
我已经在服务器和客户端上构建了 RSA key 对。
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 。这是我的新目标吗?
最佳答案
是的,它被称为混合密码系统。即使如此,您可能想了解 Bleichenbacher 攻击、身份验证加密的使用、如何获得对公钥的信任等。
因此,您的目标是要么更详细地研究该领域,要么更少了解有关部署 TLS 1.2 或 1.3 的知识。因为实现传输模式安全需要很多细节。
如果您想继续,至少看一下 OAEP 模式下的 RSA 和 GCM 模式下的 AES。
关于对于长度超过 512 字节的数据,Java IllegalBlockSizeException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48722993/