简体   繁体   中英

SHA-256 Hashing in Java

I was able to encrypt the password using CryptoJS library in Angular project. And want to implement same encryption using java . Can any one suggest the best approach?.

Below is with Angular CryptoJS library implementation

let hash = CryptoJS.SHA256("3456");
let passBase64 = CryptoJS.enc.Base64.stringify(hash);

I have implemeted in the following way in java but the values are different,

Sha256.toHexString(Sha256.getSHA("3456")));

public class Sha256 {
   public static byte[] getSHA(String input) throws NoSuchAlgorithmException
    {
        // Static getInstance method is called with hashing SHA
        MessageDigest md = MessageDigest.getInstance("SHA-256");

        // digest() method called
        // to calculate message digest of an input
        // and return array of byte
        return md.digest(input.getBytes(StandardCharsets.UTF_8));
    }

    public static String toHexString(byte[] hash)
    {
        // Convert byte array into signum representation
        BigInteger number = new BigInteger(1, hash);

        // Convert message digest into hex value
        StringBuilder hexString = new StringBuilder(number.toString(16));

        // Pad with leading zeros
        while (hexString.length() < 64)
        {
            hexString.insert(0, '0');
        }

        return hexString.toString();
    }

In Javacript code, you converting the output to base64 while in the Java code, you are converting the result to an hexadecimal value. That is why you are having different values.

You have to convert the output to the same type in both, either base64 or hexadecimal.

Inyour code JS implementation encodes to Base64 VS Java implementation encodes to Hexadecimal

The results will be different.

My code

JS Code

let hash = CryptoJS.SHA256("grape");
let passBase64 = CryptoJS.enc.Base64.stringify(hash);
console.log(passBase64)

Java Code

System.out.println(HashManager.toBase64Hash("grape", HashAlgorithm.SHA256));

Check/Test full code on https://replit.com/@JomaCorpFX/JavaHashes#Main.java

Output for both Js and Java / SHA-256("grape")

D3j8xIb1MVQY+/CV5xwGde4H0xjlrE0VAFDNjleWZJY=

I have fixed using the following code:

 public static String fileSha256ToBase64(final String clearText) throws NoSuchAlgorithmException {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return new String(
                    Base64.getEncoder().encode(MessageDigest.getInstance("SHA-256").digest(clearText.getBytes(StandardCharsets.UTF_8))));
        }
        return clearText;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM