0

I'm here:

    String password = "123";
    byte passwordByte[] = password.getBytes();
    MessageDigest md = MessageDigest.getInstance("SHA-512");
    byte passwortHashByte[] = md.digest(passwordByte);

The passwortHashByte-Array contains only a lot of numbers. I want to convernt this numbers to one String which contains the hash-code as plaintext. How i do this?

3
  • string s = ""; for( int i = 0; i < passwordHashByte.length; ++i ) s = s + passwordHashByte[i]; Commented Dec 24, 2013 at 18:13
  • can you provide more context? like.....why? Commented Dec 24, 2013 at 18:14
  • What's the expected output? Commented Dec 24, 2013 at 18:15

3 Answers 3

3

I want to convernt this numbers to one String which contains the hash-code as plaintext.

The hash isn't plain-text. It's binary data - arbitrary bytes. That isn't plaintext any more than an MP3 file is.

You need to work out what textual representation you want to use for the binary data. That in turn depends on what you want to use the data for. For the sake of easy diagnostics I'd suggest a pure-ASCII representation - probably either base64 or hex. If you need to easily look at individual bytes, hex is simpler to read, but base64 is a bit more compact.

It's also important to note that MD5 isn't a particularly good way of hashing passwords... and it looks like you're not even salting them. It may be good enough for a demo app which will never be released into the outside world, but you should really look into more secure approaches. See Jeff Atwood's blog post on the topic for an introduction, and ideally get hold of a book about writing secure code.

Sign up to request clarification or add additional context in comments.

Comments

2

Here is how I did it for my website.

private static byte[] fromHex(String hex) {
   byte[] bytes = new byte[hex.length() / 2];
   for (int i = 0; i < hex.length() / 2; i++) {
      bytes[i] = (byte)(Character.digit(hex.charAt(i * 2), 16) * 16 + Character.digit(hex.charAt(i * 2 + 1), 16) - 128);
   }
   return bytes;
}

private static String toHex(byte[] bytes) {
   String hex = new String();
   for (int i = 0; i < bytes.length; i++) {
      String c = Integer.toHexString(bytes[i] + 128);
      if (c.length() == 1) c = "0" + c;
      hex = hex + c;
   }
   return hex;
}

That'll allow you to convert your byte array to and from a hex string.

Comments

0

Well, byte passwortHashByte[] = md.digest(passwordByte); can contain some controll characters, which will broke your String. Consider encoding passwortHashByte[] to Base64 form, if you really need String from it. You can use Apache Commons Codecs for making base64 form.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.