Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a Base64 encoded SHA-256 hash in Java [closed]

Tags:

java

oracle11g

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.

like image 910
Mayank Tiwary Avatar asked Feb 27 '17 13:02

Mayank Tiwary


People also ask

Is Base64 encoding a hash?

A base64 encoded message to an application may be hashed so the integrity of that message can be verified by the receiver.

What is SHA256 in Java?

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.

How long is SHA256 hash?

The hash size for the SHA256 algorithm is 256 bits.


2 Answers

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

like image 155
lbndev Avatar answered Oct 19 '22 23:10

lbndev


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))));
}
like image 26
Florent Bayle Avatar answered Oct 19 '22 23:10

Florent Bayle