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

Sign up to request clarification or add additional context in comments.

Comments

6

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 Comments

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".
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?
If required will post the code, as I am not getting the clue.
Thanks to all ..I have solved the problem .. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.