0

I am writing a simple java programs to encrypt/decrypt using DES and RSA algorithms using Java. In Java, in order to encrypt and decrypt using the function doFinal, I have to conver the message (plain text) into bytes. I used the function .getBytes to do so. Here is part of the code:

Cipher desCipher
// Create the cipher 
desCipher = Cipher.getInstance("DES/ECB/NoPadding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] textEncrypted = desCipher.doFinal(msgBytes);

Then, return it as:

return new String(base64Cipher);

In this case, I get the cipher text looks in strange characters suc as:

Encrypted Message: °;zRfwجvë    ‏“ëثw‰ڑل7دM#¼7وm‡î¤

In some internet tutorials, they used Base64 encoding before returning the cipher such as this reference: http://techie-experience.blogspot.com/2012/10/encryption-and-decryption-using-aes.html

When I used Base64 as follows:

byte[] textEncrypted = desCipher.doFinal(msgBytes);

// converts to base64 for easier display.
byte[] base64Cipher = Base64.encodeBase64(textEncrypted);
return new String(base64Cipher);

The cipher text appears in alpha and numerical characters as:

Encrypted Message: Xz93ODw3gEKm3hziPr0UJ+ed55nWLGpTR9uHjZjLwtg=

Which method is correct? Does RSA cipher supposed to be in alpha-numeric characters only? If not, why that referee suggests using it ?

user2192774
  • 3,807
  • 17
  • 47
  • 62

1 Answers1

0

Why base64?

base64-encoded text will survive format-induced changes that a binary stream won't -- if your message transits an ASCII-only pipeline, for example. It's also much easier to embed in email, copy and paste, and so on.

Here's a great answer talking about the value of base64.

As to which method is correct -- assuming you're encoding and decoding properly, the byte streams should be equivalent.

Community
  • 1
  • 1
Christian Ternus
  • 8,406
  • 24
  • 39
  • Treating binary data as a string is never correct, and OP might even find that the behavior of his code is platform dependent because it relies on the platform default encoding. – ntoskrnl Oct 27 '13 at 21:15