user2377971
user2377971

Reputation: 1452

Java SHA-1 to javascript using CryptoJS

i have such a code to generate password written in Java

        MessageDigest messageDigestPassword = MessageDigest.getInstance("SHA1");
        messageDigestPassword .reset();
        byte[] password = "password".getBytes();
        messageDigestPassword .update(password);
        byte[] encryptedPassword = messageDigestPassword .digest();

        String date = "2019-10-22T11:33:13.393Z";
        byte[] dateBytes = date.getBytes(StandardCharsets.UTF_8);

        int offset = 0;
        byte[] outputBytes = new byte[dateBytes.length + encryptedPassword .length];
        System.arraycopy(dateBytes, 0, outputBytes, offset, dateBytes.length);
        offset += dateBytes.length;
        System.arraycopy(encryptedPassword , 0, outputBytes, offset, encryptedPassword .length);

        MessageDigest finalMessageDigeset = MessageDigest.getInstance("SHA-1");
        finalMessageDigeset.reset();
        finalMessageDigeset.update(outputBytes);
        byte[] finalPasswordBytes= finalMessageDigeset .digest();

        String finalBase64Password = new String(Base64.encode(finalPasswordBytes));

and im trying to rewrite it to JavaScript to use it in postman with - CryptoJS So far i have :

function wordArrayToByteArray(wordArray, length) {
if (wordArray.hasOwnProperty("sigBytes") && 
wordArray.hasOwnProperty("words")) {
    length = wordArray.sigBytes;
    wordArray = wordArray.words;
}

var result = [],
    bytes,
    i = 0;
while (length > 0) {
    bytes = wordToByteArray(wordArray[i], Math.min(4, length));
    length -= bytes.length;
    result.push(bytes);
    i++;
}
return [].concat.apply([], result);
}

function stringToBytes ( str ) {
var ch, st, re = [];
for (var i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i);  // get char 
st = [];                 // set up "stack"
do {
  st.push( ch & 0xFF );  // push byte to stack
  ch = ch >> 8;          // shift value down by 1 byte
}  
while ( ch );
// add stack contents to result
// done because chars have "wrong" endianness
re = re.concat( st.reverse() );
}
// return an array of bytes
return re;
}



var dateFixed = "2019-10-22T11:33:13.393Z";
var fixedDateBytes = stringToBytes(dateFixed);
var sha1Password= CryptoJS.SHA1("password");
console.log("sha1Password",sha1Password.toString(CryptoJS.enc.Hex));

var sha1PasswordBytes= wordArrayToByteArray(sha1Password, 20);

var concatedBytes= fixedDateBytes.concat(sha1PasswordBytes);

var finalShaPassWords= CryptoJS.SHA1(concatedBytes); 
console.log("finalShaPassWords",finalShaPassWords.toString(CryptoJS.enc.Hex));

console.log("finalShaPassWords",finalShaPassWords.toString(CryptoJS.enc.Base64));

However unfortunatelly Base64 representations written in those 2 languages doesnt match.

I have checked and bytes from date are equal. Bytes from hashed password are not. So hashing after concat fails in JavaScript.

I have checked first password hashing and generated bytes and both of them are the same. So my guess line var sha1PasswordBytes= wordArrayToByteArray(sha1Password, 20); causes that line var finalShaPassWords= CryptoJS.SHA1(concatedBytes); returns bad value.

Can someone give me some idea what is wrong? Mayby it should be written diffrent ?

Upvotes: 3

Views: 1531

Answers (1)

Topaco
Topaco

Reputation: 49251

Since you are using CryptoJS anyway, you can also use the CryptoJS encoders and the WordArray#concat-method, which considerably simplifies the code:

var CryptoJS = require("crypto-js");

// Input
var inPwd = "password";
var inDate = "2019-10-22T11:33:13.393Z";

// Processing
var pwdHash = CryptoJS.SHA1(inPwd);                                         // hash and convert to WordArray
var date = CryptoJS.enc.Utf8.parse(inDate);                                 // convert to WordArray
var joinedData = date.clone().concat(pwdHash);                              // join date and hashed password
var joinedDataHash = CryptoJS.SHA1(joinedData);                             // hash joined data
var joinedDataHashB64 = CryptoJS.enc.Base64.stringify(joinedDataHash);      // convert to Base64 string

// Output
console.log("Result: " + joinedDataHashB64 );                              // Output: D235TBTZMfpSyB/CDl5MHAjH5fI=

The output of this code is the same as the output of the Java-code: D235TBTZMfpSyB/CDl5MHAjH5fI=

Upvotes: 1

Related Questions