【发布时间】: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