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.
A base64 encoded message to an application may be hashed so the integrity of that message can be verified by the receiver.
The SHA-256 algorithm generates an almost unique, fixed-size 256-bit (32-byte) hash. This is a one-way function, so the result cannot be decrypted back to the original value. Currently, SHA-2 hashing is widely used, as it is considered the most secure hashing algorithm in the cryptographic arena.
The hash size for the SHA256 algorithm is 256 bits.
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))));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With