0

I need to add a digital signature to a picture using the RSA method. To do this, I first need to hash the file with SHA256. But how can this be done? As I understand it, I should get an array of byte hash[] with hashed bytes.

For example in c# example MD5 there is such a way: byte[] hash = MD5.Create.ComputeHash(bytesOfFile); I tried like this, but how can I get an array of hashes and how can I change the size of the final one?

MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
byte[] array = Files.readAllBytes(Path.of("C:\\Users\\User\\IdeaProjects\\CryptoLab1\\src\\crypto\\dino.png"));
sha256.digest(array);

System.out.println(Arrays.toString(sha256.digest()));

1 Answer 1

3

You're almost there. sha256.digest(array) itself returns the result, your next digest call wouldn't work anymore. The API of MessageDigest is: Send as many bytes as you want in chunks via the update method, and then do a final call with a digest method. Purely as a convenience, digest(byteArr) is identical to update(byteArr); digest();.

So, replace your last 2 lines with just System.out.println(Arrays.toString(sha256.digest(array));.

A few more notes:

  • This code eats a ton of memory if the file is large, and there is absolutely no need for it; you can just repeatedly read a smallish byte array, send it to the MessageDigest object via an update method. Imagine this file is 4GB large; such a setup can easily do it in a tiny memory footprint, whereas your code would require 4GB worth of memory.
  • A hash's size is what it is, you can't "resize" it, that doesn't make sense. Because bytes are annoying to show, various solutions exist. There is no one unified standard. Whatever tool gives you the supposed hash will have picked a way to turn a bunch of bytes (the hash) into string form. The common candidates are hex-nibbles, which looks like a sequence of symbols where each symbol is 0-9 or A-F, and all the letters are either all uppercased, or all lowercased. Or, base64, which is a mix of letters and digits.

To turn a byte array to hex-nibble form in java, follow this guide. To turn a byte array into base64, it's simply Base64.getEncoder().encodeToString(byteArr).

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

2 Comments

And by what logic did you get 32 from a file of 990 bytes?
32 isn't mentioned anywhere in this question. Hashes are fixed size regardless of input size. That means the hash will even be larger than in the input for extremely tiny input. SHA-256 will always emit 256 bits (32 bytes), are you referring to that? In hex-nibble form, that'll always be 64 characters. In base64 form, that'll be 43 characters and an equals sign or two.

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.