1

I got a code snippet from another SO question and modified it a bit but I can't seem to get it to work. Can anyone figure out why? it's currently printing [B@405e70bc or similar values. All I'm trying to do is store a password in an encrypted form just for the sole purpose of keeping it away from curious eyes, is there a better way to do that?

String secret = "1234567812345678";
Key key = new SecretKeySpec(secret.getBytes(), "AES");

// Encrypt
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal("helloworld".getBytes());

// Decrypt
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(encryptedData);
System.out.println(decryptedData.toString());
Qwertyzw
  • 458
  • 3
  • 11
  • See [here](http://stackoverflow.com/questions/4712139/java-object-default-tostring?s=5|1.0960) – Jens Feb 13 '15 at 19:04
  • 1
    decryptedDate is a byte[] - that's how byte[].toString() looks like. Not what you expected? Convert it to a String! – Alexander Feb 13 '15 at 19:06

3 Answers3

0

Thanks Alexander.

This worked

String secret = "1234567812345678";
Key key = new SecretKeySpec(secret.getBytes(), "AES");

// Encrypt
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal("helloworld".getBytes());

// Decrypt
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(encryptedData);
System.out.println(new String(decryptedData, "UTF-8"));
Qwertyzw
  • 458
  • 3
  • 11
0

There is nothing wrong with your encryption / decryption logic. The problem is with you calling .toString() on a byte [].

Use this output statement instead:

System.out.println(new String(decryptedData));
0

Please don't use this for anything critical. The standard Java AES code makes use of a fixed-length block cipher which can result in identical encrypted byte data. The upshot is a gradual leakage of plaintext information.

You should look into Cipher Block Chaining and Initialisation Vectors if you want your code to be more robust. http://www.javamex.com/tutorials/cryptography/block_modes.shtml

It may be overkill for your needs, but just thought i'd mention it.

kingBenny
  • 21
  • 5