7

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.

2

2 Answers 2

7

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

5

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))));
}
4
  • Better terminology would be creating a Base64 encoded SHA-256 hash. This does not answer the question: "read the file contents and convert it into SHA256 and then convert it into Base64".
    – zaph
    Feb 27, 2017 at 14:52
  • Hi, Thanks for the response. I am trying to read a file content through Java program excluding the last record of the file.The content of the file, except the last record should be encrypted to Sha256 and later i am changing it to base64 (excluding carriage returns and new line feed). But when I am comparing the value returned from Java and to the online tool (hash.online-convert.com/sha256-generator) for instance , the character length is coming proper but the value is differing. Please suggest does the hashing and encryption values the one generated in Java and Oracle11g differs? Mar 8, 2017 at 17:24
  • If required will post the code, as I am not getting the clue. Mar 8, 2017 at 17:28
  • Thanks to all ..I have solved the problem .. :) Mar 9, 2017 at 21:34

Not the answer you're looking for? Browse other questions tagged or ask your own question.