Encoding utf16 with sha256

Hello,

I’m stuck with a piece of code in a prerequest script. i need to sha256 crypt a string (a password) the same way of my c# methode. i tried all i know but can’t succeed .

result excepted :

"Azerty123!" ==>  "6e+FpD3ksBVgmMDgPLOPr98ZQGyhORmUARKxjX9mlT8=" 

C# code

string encryptedPassWord = "";
using (var sha = SHA256.Create())
     {
        var computedHash = sha.ComputeHash(Encoding.Unicode.GetBytes(password));
            encryptedPassWord = Convert.ToBase64String(computedHash);
      }

return Ok(encryptedPassWord);

The result is the same as on SHA256 - Online Tools , with input type =“UTF-16LE” and output type =“Base64”


what i tried :

function strToUtf16Bytes(str) {
  const bytes = [];
  for (ii = 0; ii < str.length; ii++) {
    const code = str.charCodeAt(ii); // x00-xFFFF
    bytes.push(code & 255, code >> 8); // low, high
       //bytes.push('0'); // low, high

        console.log("ii = " + ii + " " + code + ' ' + bytes.length); // 'My Message or Password'

  }

for (ii = 0; ii < bytes.length; ii++) {
    console.log("ii bytes = " + bytes[ii]); // 'My Message or Password'
}

  console.log(bytes.length)
  return bytes;
}

console.clear();

--pm.globals.set("email", encodeURIComponent("postmanrodrigue1234@yopmail.com"));


var clearP = 'Azerty123!';

// Azerty123!
// 6e+FpD3ksBVgmMDgPLOPr98ZQGyhORmUARKxjX9mlT8=
   

//var te = TextEncoder.Unicode();
//var rr = strToUtf16Bytes("abc");

var clearPutf = strToUtf16Bytes(clearP.toString(CryptoJS.enc.Utf16LE))



  console.log(clearPutf[18])

var sha256Hash =  CryptoJS.SHA256(clearPutf);
console.log("sha256Hash :: " + sha256Hash)
var p64 = sha256Hash.toString(CryptoJS.enc.Base64);
console.log("p64 = " + p64); // 'My Message or Password'

i created strToUtf16Bytes function, to check the bytes array, i seems to me that the arrays are the same in c# and script.
Perhaps the pb is in the CryptoJS.SHA256(clearPutf) but i can’t see what to do here.

console result are


sha256Hash :: 4ea5c508a6566e76240543f8feb06fd457777be39549c4016436afda65d2330e
 
p64 = TqXFCKZWbnYkBUP4/rBv1Fd3e+OVScQBZDav2mXSMw4=

wich is definitly not the same of “6e+FpD3ksBVgmMDgPLOPr98ZQGyhORmUARKxjX9mlT8=” :pensive:

UTF-16LE vs UTF16BE.

let Crypto = require('crypto-js');
let utf16le = Crypto.enc.Utf16LE.parse("Azerty123!");
let hash = Crypto.SHA256(utf16le);
let base64 = Crypto.enc.Base64.stringify(hash);
console.log(base64);

image

1 Like

Thanks Mike ! Exactly what i was looking for :+1:

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.