-3

I'm trying to generate hash with same algorithm (sha256) for same input in Java and Go. Interestingly I'm getting two values. Any Explanation is appreciated and I need to generate same hash generated in Java in Go.

Java code:

public byte[] sha256Hash(byte[] content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-256");
            return digest.digest(content);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e.getMessage(),e);
        }
    }
byte[] to ="AA".getBytes();
byte[] shaed = sha256Hash(to);
System.out.println(Arrays.toString(shaed));

Java Output:[88, -69, 17, -100, 53, 81, 58, 69, 29, 36, -36, 32, -17, 14, -112, 49, -20, -123, -77, 91, -4, -111, -99, 38, 62, 126, 93, -104, 104, -112, -100, -75]

Go:

fmt.Println(sha256.Sum256([]byte("AA")))

Go Output:[88 187 17 156 53 81 58 69 29 36 220 32 239 14 144 49 236 133 179 91 252 145 157 38 62 126 93 152 104 144 156 181]

  • 1
    What do you mean different? The printed decimal bytes? – icza Oct 20 '20 at 08:32
  • 1
    If you print a byte array in Java you don't get anything useful. You get `[B@` followed by a hashcode. It doesn't tell you the **contents** of the byte array, which is what's significant. – khelwood Oct 20 '20 at 08:33
  • 5
    And also Java's `byte` is signed while Go's `byte` is unsigned: see in [this answer](https://stackoverflow.com/questions/47797100/java-vs-golang-for-hotp-rfc-4226/47797161#47797161). Print them as hexadecimal values, and then they should match. – icza Oct 20 '20 at 08:34
  • 1
    @khelwood I have used Arrays.tostring() to print java output which I forget to post. Even with this its different – Damitha Dayananda Oct 20 '20 at 08:49
  • Do include your outputs. Also have you read my linked answer? – icza Oct 20 '20 at 08:51
  • @khelwood added output – Damitha Dayananda Oct 20 '20 at 08:55
  • 4
    Then this is what I suspected: it's a duplicate of [this](https://stackoverflow.com/questions/47797100/java-vs-golang-for-hotp-rfc-4226/47797161#47797161). – icza Oct 20 '20 at 09:04
  • yep thanks, @khelwood you are correct. sadly I already got minus rating eventhough this is valid question – Damitha Dayananda Oct 20 '20 at 09:09

1 Answers1

1

you are not converting byte to hexadecimal.

  import javax.xml.bind.DatatypeConverter;
 class GetHash{

public static String generateHash(String pass) throws NoSuchAlgorithmException{
    
    MessageDigest sha=MessageDigest.getInstance("SHA-256");
    
    byte[] b=sha.digest(pass.getBytes());
    
    return DatatypeConverter.printHexBinary(b);

 }}

use DatatypeConverter.printHexBinary(b) method to convert byte to hexadecimal string

or use this link for more methods How do you convert a byte array to a hexadecimal string, and vice versa?