-1

This is my code, I am having trouble with byte encoding. When I get the plaintext string, and hash it, and try to print out the result, it gets messed up. For example, for plaintext = "hi", it prints out: hash: ?????????1?W?p????=?????&

public class HASHME {

private String hash;
private String salt;

public HASHME(String plaintext) 
{
    try {
    System.setProperty("file.encoding", "UTF-8");
    salt = "salt";
    plaintext = plaintext + salt;
    byte[] bytesOfPlain = plaintext.getBytes("UTF8");

    MessageDigest md = MessageDigest.getInstance("SHA-256");
    byte[] hashedBytes = md.digest(bytesOfPlain);
    hash = new String(hashedBytes, "UTF8");
    System.out.println("hash: " + hash);

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
marcoo
  • 821
  • 1
  • 9
  • 25
  • can you print out bytesOfPlain as well as hashedBytes – CodeGuy Apr 01 '13 at 19:49
  • 1
    ***what are you expecting***, it is doing what you ask it to, print un-printable characters, it won't magically hex encode the bytes, which is probably what you are expecting, but we have no idea and can only guess. –  Apr 01 '13 at 19:49
  • 1
    See [http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java](http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java) –  Apr 01 '13 at 19:51

1 Answers1

4

This is the problem:

byte[] hashedBytes = md.digest(bytesOfPlain);
hash = new String(hashedBytes, "UTF8");

The result of hashing is not UTF-8 encoded text - it's just arbitrary binary data. What you're doing here is as meaningless as trying to turn an image file into a string by interpreting it as UTF-8.

If you must convert a hash to text, either use base64 or hex. (Typically arbitrary-size data is transported as base64, but hashes are usually displayed in hex.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194