We need to read the file contents and convert it into SHA256 and then convert it into Base64.
Any pointer or sample code will suffice , as I am new to this encryption mechanism.
Thanks in advance.
We need to read the file contents and convert it into SHA256 and then convert it into Base64.
Any pointer or sample code will suffice , as I am new to this encryption mechanism.
Thanks in advance.
With Java 8 :
public static String fileSha256ToBase64(File file) throws NoSuchAlgorithmException, IOException {
byte[] data = Files.readAllBytes(file.toPath());
MessageDigest digester = MessageDigest.getInstance("SHA-256");
digester.update(data);
return Base64.getEncoder().encodeToString(digester.digest());
}
BTW : SHA256 is not encryption, it's hashing. Hashing doesn't need a key, encryption does. Encryption can be reversed (using the key), hashing can't. More on Wikipedia : https://en.wikipedia.org/wiki/Hash_function
You can use MessageDigest
to convert to SHA256, and Base64
to convert it to Base64:
public static String encode(final String clearText) throws NoSuchAlgorithmException {
return new String(
Base64.getEncoder().encode(MessageDigest.getInstance("SHA-256").digest(clearText.getBytes(StandardCharsets.UTF_8))));
}