【发布时间】:2012-01-12 11:54:22
【问题描述】:
我正在尝试使用 Base64 编码实现 RSA 加密。顺序是:
String -> RSA encrypt -> Base64 encoder -> network -> Base64 decoder* -> RSA decrypt > String
我正在通过网络发送带有 a 的 base64 编码字符串,并在另一端将其作为字符串读取,毕竟 Base64 是文本,对吧?
现在由于某种原因,当我解码 Base64 时,我得到的字节数比我最初发送的要多。
在发送方,我的 RSA 字符串是 512 字节。在 Base64 编码后,它的长度为 1248(每次都不同)。 在接收端,我的 Base64 编码接收字符串仍然是 1248 长,但是当我解码它时,我突然得到 936 个字节。然后我无法用 RSA 解密它,因为 ciper.doFinal 方法挂起。
我假设这与字节到 unicode 字符串的转换有关,但我无法弄清楚这是在哪一步发生的以及如何解决它。
发送方代码:
cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, getPublicKey());
byte[] base64byes = loginMessage.getBytes();
byte[] cipherData = cipher.doFinal(base64byes);
System.out.println("RSA: " + cipherData.length); //is 512 long
//4. Send to scheduler
Base64PrintWriter base64encoder = new Base64PrintWriter(out);
base64encoder.writeln(new String(cipherData)); //send string is 1248 long
base64encoder.flush();
接收方代码:
System.out.println("Base 64: " + encodedChallenge.length()); //1248 long
byte[] base64Message = encodedChallenge.getBytes();
byte[] rsaEncodedMessage = Base64.decode(base64Message);
System.out.println("RSA: " + rsaEncodedMessage.length); //936 long
cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
cipherData = cipher.doFinal(rsaEncodedMessage); //hangs up
System.out.println("Ciper: " + new String(cipherData));
附: Base64PrintWriter 是一个 PrintWriter,我已经对其进行了修饰,以在将其写出之前将每个输出转换为 base64。
【问题讨论】:
标签: java encryption base64 rsa