Generating compatible SHA512 Hash between Java and JavaScript using CryptoJS

While working on the development of a secure way for authenticating a remote web application with the Ambient Dynamix Framework, I needed to generate a SHA512 of a salt and token which the web application could transmit to the framework via a dynamically generated QR Code. The Dynamix instance running on the android device can then use this hash to verify the authenticity of any further HTTP requests.

Generating SHA512 Hash in JavaScript :

The CryptoJS library provides a multitude of cryptography related features and what I needed to use was the SHA512 Hasher.

To be able to use the hasher, include:

    <script type="text/javascript" src=""></script>
    <script type="text/javascript" src=""></script>

and then :

var hashWordArray = CryptoJS.SHA512('saltedToken');
//replace saltedToken with the relevant data.

This returns the SHA512 Hash in a word array which is an array of 32-bit words. Now, to be able to transfer the hash, I encoded the array into a Base64 String so that I could use the same encoding in Java to generate the hash. There are other options too such as encoding into a Hex String.

CryptoJS also provides the encoding feature.

Include :

<script src="" type="text/javascript">

and then :

var base64HashString = hashWordArray.toString(CryptoJS.enc.Base64);

Generating SHA512 Hash in Java :

Now, to be able to verify the authenticity in Java, for a given String I should be able to generate the same SHA512 Hash and this can be done using the following code :

MessageDigest md = null;
String saltedToken = "saltedToken";
try {
    md = MessageDigest.getInstance("SHA-512");
    byte byteData[] = md.digest();
    String base64 = Base64.encodeToString(byteData, Base64.NO_WRAP);
} catch (NoSuchAlgorithmException e) {
    Log.w(TAG, "Could not load MessageDigest: SHA-512");
    return false;

The important thing to note here is the Base64.NO_WRAP flag which ensures that while encoding, the encoder should omit all line terminators which is exactly what the JS encoder does.

Cheers! 😀

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s