-1

I actually have a problem with hashing a password and trying to convert in string to put it in a database.

Currently I have this code

            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            byte[] hash = digest.digest(motsDePasse.getBytes(StandardCharsets.UTF_8));
            String fileString = Base64.getEncoder().encodeToString(hash);

The deal is that it does not give me the good hash. Let's say I try to hash "12345". It should give me 5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf5a9c173cacfc5.

But it actually return WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U=

J. Lev
  • 307
  • 3
  • 19
  • The value WZRHGrsBESr8wYFZ9sx0tPURuZgG2lmzyvWpwXPKz8U= in Base64 is 5994471ABB01112AFCC18159F6CC74B4F511B99806DA59B3CAF5A9C173CACFC5 in Hex. You just need to encode using Hex instead of Base64 – Ali Feb 24 '17 at 02:09

3 Answers3

1

try using a hex encoder

    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    byte[] hash = digest.digest("12345".getBytes(StandardCharsets.UTF_8));

    String hex = DatatypeConverter.printHexBinary(hash);
    System.out.println(hex); 

output

5994471ABB01112AFCC18159F6CC74B4F511B99806DA59B3CAF5A9C173CACFC5

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

You are Base64 encoding it. If you Hex encode it, you will get the output you are looking for.

Ali
  • 1,442
  • 1
  • 15
  • 29
0

You're encoding your bytes in base 64. If you want to encode it in hexadecimal, try here: Java code To convert byte to Hexadecimal. If you're putting into a database as a string though, base64 should be fine for your needs.

Community
  • 1
  • 1
HRoll
  • 36
  • 2