2012-01-12 27 views
1

我想用Base64编码实现RSA加密。顺序是:RSA和Base64编码太多字节

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)); 

P.S. Base64PrintWriter是一个PrintWriter,我已经装饰过将每个输出转换为base64,然后写出来。

回答

3

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

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

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

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

+1

你是我的英雄:)这确实解决了它。我将Base64PrintWriter更改为writeln(byte [] b)方法。现在它可以工作。 – lanoxx 2012-01-12 12:19:48

+1

将其更改为Base64OutputStream,并使Writer作为父级。相反,创建一个Base64InputStream并让它使用Reader。即使标准定义将字节转换为字节,Base64仍将字节编码为字符。那是因为他们* 8位编码。您可以将流式传输的字节想象成UTF-16编码的XML。 – 2012-01-13 00:43:32

+0

@owlstead:感谢您的回复我已经打开了另一个关于这个问题,并发布了我当前的Base64OutputStream解决方案。我很感谢您对这是否正确完成或仍然可以改进的意见? http://stackoverflow.com/questions/8896237/java-base64-how-to-write-a-base64outputstream-class-using-decorator-pattern – lanoxx 2012-01-17 14:27:50