【问题标题】:RSA and Base64 encoding too many bytesRSA 和 Base64 编码的字节太多
【发布时间】: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


    【解决方案1】:

    您的编码有问题。使用基数 64 而不是基数 256 意味着需要增加 8 位/6 位或 1/3 类似的解码导致 1/4 的下降,例如1248 * 6 / 8 = 936

    问题似乎是您在编码之前将 8 位数据转换为 16 位字符串。这需要 512 * 16 / 6 字节 = ~1365。

    您需要一个使用字节而不是字符/字符串的 Base64 流。

    也许使用 Base64.encode() 是你需要的?

    【讨论】:

    • 你是我的英雄 :) 这确实解决了它。我将 Base64PrintWriter 更改为具有 writeln(byte[] b) 方法。现在可以了。
    • 将其改为Base64OutputStream,并使其以Writer为父级。反过来,创建一个 Base64InputStream 并让它使用 Reader。 Base64 是将字节编码为字符,即使标准定义谈论的是字节到字节。那是因为他们假设 8 位编码。您可以想象到 UTF-16 编码的 XML 的有趣流式传输字节。
    • @owlstead:感谢您的回复我已经提出了另一个问题,并发布了我当前的 Base64OutputStream 解决方案。我会很感激您对这是否正确完成或仍然可以改进的评论? stackoverflow.com/questions/8896237/…
    猜你喜欢
    • 2015-02-23
    • 1970-01-01
    • 2021-02-23
    • 1970-01-01
    • 2011-10-16
    • 1970-01-01
    • 2020-07-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多