# Reading bytes from file to compute its SHA256 hash

I need to get text hash (sha 256), so I need to convert file to its type representation. Is this a fast way to get a byte representation of a file?

public byte[] bEad(String FILENAME) {
RandomAccessFile f=null;
try {
f=new RandomAccessFile(FILENAME, "r");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] b=new byte[0];
try {
b=new byte[(int) f.length()];
} catch (IOException e) {
e.printStackTrace();
}
try {
f.close();
} catch (IOException e) {
e.printStackTrace();
}
return b;

}

MessageDigest name=MessageDigest.getInstance("SHA-256");

• Code Review is about improving existing, working code. Code Review is not the site to ask for help in fixing or changing what your code does. Have you tested this code? Does it work for you? It sounds like you are unsure about what your code does. – Simon Forsberg Sep 25 '17 at 17:06
• it's working and run fast, (I share my solution). – sherif Sep 25 '17 at 17:19
• Can you please show your real code, where you are calling the name.update and instantiating the MessageDigest? – Simon Forsberg Sep 25 '17 at 18:05
• Do you want to get feedback on your code, or what exactly is your purpose of posting this here? – Simon Forsberg Sep 25 '17 at 18:05
• I need a feedback – sherif Sep 25 '17 at 18:31

If have no idea what bEad means, or why your function is named that way. Also, it should probably be a static method, since it uses no object state.

By convention, all-caps names, like FILENAME, should be used only for constants.

Your error handling is bad. Suppose the file does not exist… then what? You'll get a NullPointerException after printing a stack trace. The correct thing to do is not to catch any of the exceptions. Just declare that the method throws IOException.

This code could be expressed more succinctly using Files.readAllBytes(): see this Stack Overflow answer:

byte[] b = Files.readAllBytes(Paths.get(filename));
byte[] hash = MessageDigest.getInstance("SHA-256").digest(b);


Note, however, that that solution, as well as your, scales poorly for large files, since you read the entire file into memory. It would be better to compute the message digest by reading, say, 8192 bytes at a time.