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.

Community
  • 1
  • 1
Mayank Tiwary
  • 81
  • 1
  • 1
  • 4
  • Sounds like you want to do this http://stackoverflow.com/questions/3103652/hash-string-via-sha-256-in-java and then this http://stackoverflow.com/questions/13109588/base64-encoding-in-java – domsson Feb 27 '17 at 13:15
  • To convert to SHA256 : http://stackoverflow.com/questions/5531455/how-to-hash-some-string-with-sha256-in-java To convert to Base64 : http://stackoverflow.com/questions/19743851/base64-java-encode-and-decode-a-string – yalpsid eman Feb 27 '17 at 13:27

2 Answers2

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

lbndev
  • 781
  • 6
  • 14
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))));
}
Florent Bayle
  • 11,520
  • 4
  • 34
  • 47
  • 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 '17 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 (http://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? – Mayank Tiwary Mar 08 '17 at 17:24
  • If required will post the code, as I am not getting the clue. – Mayank Tiwary Mar 08 '17 at 17:28
  • Thanks to all ..I have solved the problem .. :) – Mayank Tiwary Mar 09 '17 at 21:34