简体   繁体   中英

Get hash of a String as String

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM