Equivalent JavaScript code to generate SHA256 hash - javascript

I have this code in Java that generates a SHA256 hash:
Hashing.sha256().hashString(value,Charsets.UTF_16LE).toString()
I'm trying to do the same on JavaScript/Node, that having the same value returns the same result.
I tried usind crypto-js but without success (it returns a hash string but different from the one generated with the Java code).
I tried this, for example:
import * as sha256 from 'crypto-js/sha256';
import * as encutf16 from 'crypto-js/enc-utf16';
...
let utf16le = encutf16.parse(key);
let utf16Sha256 = sha256(utf16le);
let utf16Sha256String = utf16Sha256.toString();

Can you try something like this :-
const CryptoJS = require('crypto-js');
let utf16le = CryptoJS.enc.Utf16LE.parse(word);
let utf16Sha256 = CryptoJS.SHA256(utf16le);
return utf16Sha256.toString(CryptoJS.enc.Hex);
Or else if you can give a sample of whats the input and expected output corresponding to JAVA code it will be easier

Related

Convert encryption function from Javascript to Python

I'm trying to convert this code from Javascript to Python3:
import crypto from 'crypto';
const secretKey = 'NgTriSCalcUltAbLoGResOnOuSeAKeSTraLryOuR'
function verifySignature(rawBody) {
const calculatedSignature = crypto
.createHmac('sha256', secretKey)
.update(rawBody, 'utf8')
.digest('base64');
return calculatedSignature;
}
console.log(verifySignature('a'));
With that code I get this output: vC8XBte0duRLElGZ4jCsplsbXnVTwBW4BJsUV1qgZbo=
So I'm trying to convert the same function to Python using this code:
UPDATED
import hmac
import hashlib
message = "a"
key= "NgTriSCalcUltAbLoGResOnOuSeAKeSTraLryOuR"
hmac1 = hmac.new(key=key.encode(), msg=message.encode(), digestmod=hashlib.sha256)
message_digest1 = hmac1.hexdigest()
print(message_digest1)
But I get this error: AttributeError: 'hash' object has no attribute 'digest_size'
Can someone tell me what I am missing to achieve the same output in Python?
Thanks you! :)
You're not getting base64 from the digest() on your return statement. In your javascript code it was also encoded in UTF-8 which should be specified below. The key was also not supplied in your python code.
This code snippet I just tested should generate the same result as your javascript code:
def newhashab(msg, key):
digest = hmac.new(key.encode('UTF-8'), msg.encode('UTF-8'), hashlib.sha256)
return base64.b64encode(digest.digest()).decode('UTF-8')
print(newhashab("a", 'NgTriSCalcUltAbLoGResOnOuSeAKeSTraLryOuR'))
It should return:
'vC8XBte0duRLElGZ4jCsplsbXnVTwBW4BJsUV1qgZbo='

How to get Java DigestUtils.md5() output from Javascript?

Java code that uses
Apache Commons library to generate signature:
byte[] md5 = DigestUtils.md5("test");
String signature = Base64.encodeBase64String(md5);
System.out.println(signature);
// CY9rzUYh03PK3k6DJie09g==
Javascript code I am trying to write to get the same output:
const md5 = CryptoJS.MD5("test");
const signature = btoa(md5);
console.log(signature);
// MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
I know how to get the same output if I change the Java code like this:
String md5 = DigestUtils.md5Hex("test");
String signature = Base64.encodeBase64String(md5.getBytes(StandardCharsets.UTF_8));
System.out.println(signature);
// MDk4ZjZiY2Q0NjIxZDM3M2NhZGU0ZTgzMjYyN2I0ZjY=
But unfortunately I am not allowed to modify Java code, so how can I modify Javascript code instead, to get the same output as Java code?
I think I found the solution by myself:
const md5 = CryptoJS.MD5("test");
const signature = md5.toString(CryptoJS.enc.Base64);
console.log(signature);
// CY9rzUYh03PK3k6DJie09g==

MurmurHash3_32 Java returns negative numbers

I am trying to replicate the file hashing of MobileSheetsPro, an Android app, where there is a hashcodes.txt which includes a hash for each file, as well as the path, last modified date and filesize. We'll just focus on the hashing part.
So for the random song I uploaded here if you want to try it for yourself, I am using the murmurhash-native npm package to convert it to a buffer and then hash it like so:
const fs = require("fs");
const { promisify } = require("util");
const { murmurHash } = require("murmurhash-native");
const readFileAsync = promisify(fs.readFile);
async function hashcodeObjFromFilePath(filepath) {
const buf = await readFileAsync(filepath);
const h = murmurHash(buf);
console.log(h);
}
This prints out a hash of 4275668817 when using the default seed of 0 and 3020822739 when using the seed 0xc58f1a7b as a second argument.
The problem: the app seems to calculate it differently. The developer wrote the following, but I don't see that exact function in the code he linked:
Check this out: github link
Those are the classes I've utilized. I call
Hashing.goodFast32Hash(HASH_KEY)) where HASH_KEY is equal to
0xC58F1A7B.
EDIT I've got more infos from the dev:
I call Files.hash(file, Hashing.goodFast32Hash(HASH_KEY)); Using the
return value from that, I call "asInt()" on the HashCode object that
is returned. So it's a signed integer value (negative values are just
fine). And yes, HASH_KEY is the seed value passed to the function.
Since I'm not good at Java I still have no idea to replicate this in node-js...
That's all the info I have, folks.
Anyone see where I'm going wrong?
Found it! The asInt() function in the Java lib returns a signed int32 *in little endian byte order
The following is probably not the easiest way but the code
const h = murmurHash(buf, "buffer", 0xc58f1a7b);
// console.log(parseInt(h, 16).toString(2));
const fromHashFile = Buffer.alloc(4);
fromHashFile.writeInt32BE(-1274144557);
console.log(fromHashFile);
console.log(h);
console.log(h.readInt32BE());
console.log("hash from hashcodes file: -1274144557");
Prints out the following to console:
<Buffer b4 0e 18 d3>
<Buffer b4 0e 18 d3>
-1274144557
hash from hashcodes file: -1274144557

CryptoJS : key.clamp is not a function

TypeError: key.clamp is not a function
at Object.init (path/node_modules/crypto-js/hmac.js:58:18)
The error above occurs when I try to create JWT in Javascript with the relevant code below.
const CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256(token.join("."), secret);
crypto-js/hmac.js:58:18 has key.clamp(); and I'm not sure what would be the best approach. I tried with HmacSHA512 but it returns the same error.
I'm running with npm 6.1.0 node v6.10.3 crypto-js ^3.1.9-1.
From their samples, secret (or key as they call it), should be a string.
As such, using CryptoJS like this should work just fine:
const token = "a,b"; // fake token
const secret = CryptoJS.enc.Utf8.parse("mySecret"); //encode mySecret into UTF-8 as suggested in the comments
const CryptoJS = require('crypto-js');
var hash = CryptoJS.HmacSHA256(token.split(","), secret);
console.log(hash);

What's the encoding should I use to "gzuncompress()" in node.js?

I'm converting my code from PHP to node.js, and I need to convert a part of my code where there's the gzuncompress() function.
For that I'm using zlib.inflateSync. But I don't know which encoding I should use to create the buffer and so to have the same result of php
Here's what I do with php to decompress a string:
gzuncompress(substr($this->raw, 8))
and here's what I've tried in node.js
zlib.inflateSync(new Buffer(this.raw.substr(8), "encoding"))
So what encoding should I use to make zlib.inflateSync returns the same data as gzuncompress ?
I am not sure about what would be exact encoding here however this repo has some PHP translations for node.js (https://github.com/gamalielmendez/node-fpdf/blob/master/src/PHP_CoreFunctions.js). According to this repo, the following could work:
const gzuncompress = (data) => {
const chunk = (!Buffer.isBuffer(data)) ? Buffer.from(data, 'binary') : data
const Z1 = zlib.inflateSync(chunk)
return Z1.toString('binary')//'ascii'
}

Categories