0

For this question I am asked to:

  1. convert text to hash,

  2. then put it into a byte array,

  3. construct a new byte array 0b, with a zero byte at index 0 then b.

I am able to get the hash of the message c84291b88e8367ef3448899117f8b497f58ac7d43689239783f708ea0092c39b with my code:

MessageDigest md = MessageDigest.getInstance("SHA-256");
    
    //Convert Message to hash
md.update(message1.getBytes());
byte[] digest = md.digest();
String Hash = hexaToString(digest);
System.out.println( "Message 1 in hash is = " + Hash);  

And I am able to convert it into a byte array but I am not sure how to add the zerobyte to the start of the byte array?

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263
  • Does this answer your question? [How can I concatenate two arrays in Java?](https://stackoverflow.com/questions/80476/how-can-i-concatenate-two-arrays-in-java) – Robert Harvey Aug 01 '22 at 19:13
  • Create a new byte array `byte[] temp = new byte[1 + digest.length]` and use `System.arraycopy(digest, 0, temp, 1, digest.length)` – President James K. Polk Aug 01 '22 at 19:16

1 Answers1

2

When computing the digest, you can provide an output array via an overloaded form of digest(). You can allocate an extra byte, and store whatever you like in the extra space at the beginning.

int len = md.getDigestLength();
byte[] digest = new byte[len + 1];
md.digest(digest, 1, len);
erickson
  • 265,237
  • 58
  • 395
  • 493