RSA和Base64编码太多字节

我正在尝试使用Base64编码实现RSA加密。 顺序是:

String -> RSA encrypt -> Base64 encoder -> network -> Base64 decoder* -> RSA decrypt > String 

我将通过网络发送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)); 

PS Base64PrintWriter是一个PrintWriter,我把它装饰成在写出之前将每个输出转换为base64。

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

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

你需要一个Base64流,它取字节而不是字符/字符串。

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