Crypto hmac conversion from Python to Javascript - javascript

I'm trying to convert the following function from Python to Javascript.
Currently concentrating on the generation of the signature.
def prepare_url(self, segments, params={}):
if self.token is not None:
sig = hmac.new(self.token.key.encode(), digestmod=hashlib.sha1)
sig.update(self.method.lower().encode())
sig.update(self.service.lower().encode())
ts = self.get_timestamp(self.token.server_offset)
sig.update(ts.encode())
params["timestamp"] = ts
sig.update(self.token.identifier.lower().encode())
params["signature-method"] = "auth"
params["signature-version"] = self.version
params["signature"] = base64.standard_b64encode(sig.digest())
self.url = "%s/%s/%d/" % (self.base_path, self.service, self.version)
self.url += "/".join([urllib.parse.quote(s) for s in segments])
if params:
self.url += "?%s" % urllib.parse.urlencode(params)
In Javascript I'm using the crypto library and have the following code:
import crypto from 'crypto';
const KEY = '5d016f32-452f-4b9b-8e81-641e14d4d98c';
const METHOD = 'get';
const SERVICE = 'data';
const date = (new Date()).toISOString().slice(0, 19);
const encoded = crypto.createHash('sha1')
.update(KEY)
.update(METHOD.toLowerCase())
.update(SERVICE.toLowerCase())
.update(date)
.digest('hex');
console.log(encoded);
const baseEncoded = btoa(encoded);
console.log(baseEncoded);
However the end codes are not comparable.
Python generates using the given inputs: b'oV4RJ6pAz+hxZsxeQthx8gZrhAY='
Javascript generates: YTZjMmIyYjQzOGEwZGUxZTU1YTNjMWVlYjA3MTA3NTFmODc0MDM3ZQ==
I googled around but could not find what to change to make this work.
In python the digest is hashlib.sha1, this is not available in crypto.
Any pointers?
Below are the codes Python generates at each of the update steps.
-----> key: b'bnAcIlriz+t4hTQLBrnjI1aeXBI='
-----> method: b'rc1Y6wKZo8pDKHmhjVNDkhcVNKM='
-----> Service: b'/urBh6Yqk6QI39JhYtSMI9P9QS8='
-----> Time: 5d016f32-452f-4b9b-8e81-641e14d4d98c
-----> Identifier: b'oV4RJ6pAz+hxZsxeQthx8gZrhAY='
-----> FINAL: b'oV4RJ6pAz+hxZsxeQthx8gZrhAY='
Solution:
const encoded = crypto.createHmac('sha1', key)
.update(METHOD.toLowerCase())
.update(SERVICE.toLowerCase())
.update(date)
.update(identify)
.digest('base64');

Based on the feedback from #PresidentJamesK.Polk I was able to figure this out.
const encoded = crypto.createHmac('sha1', key)
.update(METHOD.toLowerCase())
.update(SERVICE.toLowerCase())
.update(date)
.update(identify)
.digest('base64');

Related

TripleDES Java Encryprion to Javascript Decryption

I am using Java to encrypt a text payload with Triple DES. First I create an ephemeral key that I will use for encrypting the payload:
private byte[] createEphemeralKey() throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(168);
return keygen.generateKey().getEncoded();
}
Then I encrypt my payload with said key:
private String encryptTripleDES(byte[] ephemeralKey, String payload) throws Exception {
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(ephemeralKey, "DESede"));
byte[] plainTextBytes = payload.getBytes();
byte[] cipherText = cipher.doFinal(plainTextBytes);
return Base64.getEncoder().encodeToString(cipherText);
}
Also need a padding function to ensure the data length is divisable by 8:
private String adjustPadding(String input, int blockSize) {
int len = input.length() % blockSize;
int paddingLength = (len == 0) ? 0 : (blockSize - len);
while (paddingLength > 0) {
input += "F";
paddingLength--;
}
return input;
}
And here is my process end to end:
String data = "Marnus"
byte[] = ephemeralKey = createEphemeralKey();
String adjustedData = adjustPadding (data,8);
String encryptedPayload = encryptTripleDES(ephemeralKey, adjustedData);
String encodedKey = Base64.getEncoder().encodeToString(ephemeralKey)
So I take the 2 variables encryptedPayload and encodedKey, that are both Base64 encoded string, and send it off via HTTP to node express app.
In the Javascript side of things, I use node-forge - Here is the part of my express app that does the decryption:
let nodeBuffer = Buffer.from(data, 'base64')
let input = forge.util.createBuffer(nodeBuffer.toString('binary'))
// 3DES key and IV sizes
let keySize = 24;
let ivSize = 8;
let derivedBytes = forge.pbe.opensslDeriveBytes(ephemeralKey, null, keySize + ivSize);
let buffer = forge.util.createBuffer(derivedBytes);
let key = buffer.getBytes(keySize)
let iv = buffer.getBytes(ivSize)
let decipher = forge.cipher.createDecipher('3DES-ECB', key)
decipher.start({iv: iv})
decipher.update(input)
console.log('decipher result', decipher.finish())
let decryptedResult = decipher.output.data;
Here is an Triples DES example in the node-forge docs:
A few notes:
I create a node-forge buffer from a regular buffer since I don't have a input file like the examples gives. Here is how the docs states one should create one buffer from the other:
*I use base64 as that is what I used in the java side to encode the data that was sent.
Then, I dont have a salt so I left the 2'nd param null in opensslDeriveBytes as specified in the docs I should do.
Thirdly, I am also not sure if my keysize of 24 is correct?
My results
So doing an end to end test yields the following:
In my Java app, the test data was "Marnus", the encryptedPayload was ez+RweSAd+4= and the encodedKey was vCD9mBnWHPEBiQ0BGv7gc6GUCOoBgLCu.
Then in my javascript code data was obviously ez+RweSAd+4=(encryptedPayload) and the ephemeralKey was vCD9mBnWHPEBiQ0BGv7gc6GUCOoBgLCu(encodedKey).
After the decryption ran, the value of decryptedResult was ©ýÕ?µ{', which is obviously just garbage since it was not encoded yet, but I cant figure out which encoding to use?
I tried using forge.util.encode64(decipher.output.data), but that just gave me qf3VP7UYeyc=, which is not right.
For what it's worth, here is the type that decipher.output
With a lot more tweaking and testing different options, I got it working - and the good news is I managed to get it all working with the built in crypto library in nodejs (v12.18.4).
First things first, the JAVA side just needs a change to the key size (from 168 to 112), the rest remains the same - see below example as one single method (should be split up in final implementation of course for testability and usability):
//Some data:
String payload = "{\"data\":\"somedata\"}";
// Create Key
KeyGenerator keygen = KeyGenerator.getInstance("DESede");
keygen.init(112);
byte[] ephemeralKey = keygen.generateKey().getEncoded();
// Adjust the data, see adjustPadding method in the question for details.
String data = adjustPadding (payload,8);
// Wil now be "{"data":"somedata"}FFFFF", can just chop off extra in JS if need be. When sending JSON one knows the end of the object will always be "}"
// Do Encrypt
Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(ephemeralKey, "DESede"));
byte[] plainTextBytes = data.getBytes();
byte[] cipherText = cipher.doFinal(plainTextBytes);
String encryptedPayload = Base64.getEncoder().encodeToString(cipherText);
//Lastly, Base64 the key so you can transport it too
String encodedKey = Base64.getEncoder().encodeToString(ephemeralKey)
on the Javascript side of things we keep it simple:
// I'm using TS, so change the import if you do plain JS
import crypto = require('crypto')
//need bytes from the base64 payload
let buff = Buffer.from(ephemeralKey, 'base64')
const decipher = crypto.createDecipheriv('des-ede3', buff, null)
decipher.setAutoPadding(false)
let decrypted = decipher.update(data, 'base64', 'utf8')
decrypted += decipher.final('utf8')
console.log(decrypted)
//{"data":"somedata"}FFFFF"

Python body.encode( ) Javascript alternative

I'm trying to verify a webhook coming from Plaid in NodeJS by calculating the Sha256 of the webhook body and I'm following a Python code here where the code is showing :
# Compute the has of the body.
m = hashlib.sha256()
m.update(body.encode())
body_hash = m.hexdigest()
What's the alternative of body.encode() in Javascript before passing it to the Sha256 function please ? Note that the body I'm getting is an object containing the following data :
{ error: null, item_id: '4zAGyokJ1XiWP63QNl1RuLZV76o55nudVXzNG',
new_transactions: 0, webhook_code: 'DEFAULT_UPDATE', webhook_type:
'TRANSACTIONS' }
However I'm trying to get this hash :
b05ef560b59e8d8e427433c5e0f6a11579b5dfe6534257558b896f858007385a
So, if the body is JSON (NOT JSON STRING) then you need to stringify it and put it in the .update function As the m.body takes a string. If you have your body as STRING then just put it in as is.
This is from the Crypto Example here:
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
const stringBody = JSON.stringify(body);
hash.update(stringBody);
console.log(hash.digest('hex'));
Edit:
If the hash is not same then maybe you need to correct the newlines or whitespaces. You need to make both bodies exactly the same. Here In the below example I am using same exact string and encoding using Python AND NodeJS.
import hashlib
body = '{"error":null,"item_id":"4zAGyokJ1XiWP63QNl1RuLZV76o55nudVXzNG","new_transactions":0,"webhook_code":"DEFAULT_UPDATE","webhook_type":"TRANSACTIONS"}'
m = hashlib.sha256()
m.update(body.encode())
body_hash = m.hexdigest()
print(body_hash)
Output:
python3 file.py
26f1120ccaf99a383b7462b233e18994d0c06d4585e3fe9a91a449e97a1c03ba
And Using NodeJS:
const crypto = require('crypto');
const hash = crypto.createHash('sha256');
const body = {
error: null,
item_id: '4zAGyokJ1XiWP63QNl1RuLZV76o55nudVXzNG',
new_transactions: 0,
webhook_code: 'DEFAULT_UPDATE',
webhook_type: 'TRANSACTIONS'
}
const stringBody = JSON.stringify(body);
hash.update(stringBody);
console.log(hash.digest('hex'));
Output:
node file.js
26f1120ccaf99a383b7462b233e18994d0c06d4585e3fe9a91a449e97a1c03ba

verify js pbkdf2-sha256 hash with python passlib

I encrypt a random string in python file and hashit in javascript using pbkdf2-sha256 but some how the verification fails with python passlib . any idea why?
my python code is :
from passlib.hash import pbkdf2_sha256
import os,random,string
t = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in
range(7))
h = os.popen('node
D:/mojtaba/repos/restaurant_app/frontend/node_modules/a.js '+t).read()[:-2]
a = pbkdf2_sha256.verify(t,h)
print(a)
and js file contains :
var pbkdf2 = require('pbkdf2-sha256');
var salt = 'WitFCKH03htDKAVA6L3Xmg';
var algorithm = "pbkdf2-sha256";
var iterations = 29000;
var hashed = pbkdf2(process.argv[2], new Buffer(salt), iterations,
32).toString('base64');
var finalPass = '$'+algorithm +'$'+ iterations +'$'+ salt +'$'+ hashed;
console.log(finalPass)
and result is always false

Progressive HMAC SHA256 in Objective-C

I need to generate a hash using HMAC SHA256. I am using the following code in JavaScript. I need an equivalent code in Objective-C.
function serialize( obj ) {
return Object.keys(obj).reduce(function(a,k){a.push(k+'='+encodeURIComponent(obj[k]));return a},[]).join('&')
}
var query = {
Action : 'MyAction',
SignatureMethod : 'HmacSHA256',
};
var hmac = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, 'MYVALUE');
var queryString = ['POST', 'm.service.it', '/api/v2', serialize(sorted)].join('\n');
hmac.update(queryString);
query.Signature = CryptoJS.enc.Base64.stringify(hmac.finalize());
How implement this in Objective-C?
HMAC-SHA256 sample code:
+ (NSData *)hmacSha256:(NSData *)dataIn
key:(NSData *)key
{
NSMutableData *macOut = [NSMutableData dataWithLength:CC_SHA256_DIGEST_LENGTH];
CCHmac( kCCHmacAlgSHA256,
key.bytes,
key.length,
dataIn.bytes,
dataIn.length,
macOut.mutableBytes);
return macOut;
}
Notes:
Add Security.framework to the project
Common Crypto must be included:
#import <CommonCrypto/CommonCrypto.h>
This is data in and out, add any conversions to desired representations before and after.
Conversions could be string to data on input and data to Base64 on output:
NSData *data = [#"string" dataUsingEncoding:NSUTF8StringEncoding];
NSString *string = [data base64EncodedStringWithOptions:0];

Generate Hmac in Javascript from python code

I am trying to generate an hmac hash in javascript.
here is some python code I want to replicate in Javascript:
mac = hmac.new("33fsfsdgvwrg2g223f4f42gf4f34f43f", digestmod=hashlib.sha1)
mac.update(method)
mac.update(url)
mac.update(data)
mac.update(str(timestamp))
r = requests.request(method, url, data=data, headers={
'Content-Type': 'application/json',
'Authorization': " signature="'mac.hexdigest()'" ",
})
This is what I have so far, and it does not seem to be what I need:
var message = "shah me";
var secret = "33fsfsdgvwrg2g223f4f42gf4f34f43f";
var crypto = CryptoJS.HmacSHA1(message, secret).toString(CryptoJS.enc.Base64);
var shaObj = new jsSHA('shah me', "ASCII");
var jssha = shaObj.getHMAC('33fsfsdgvwrg2g223f4f42gf4f34f43f', "ASCII", "SHA-1", "B64");
It looks like your "current solution" is just a copy paste of jsSHA, CryptoJS and OpenSSL libraries giving different results with your key substituted in.
Anyways, you don't need to use both CryptoJS and jsSHA. You should pick one and stick with it.
According to the docs, the python mac.update function is equivalent to appending data to the message. I believe this is the key to your problems, since neither CryptoJS nor jsSHA have an equivalent update function but instead expect you to have the full message to begin with.
The following Python code and the Javascript code that follows it are equivalent:
import hashlib
import hmac
method = 'method'
url = 'url'
data = 'data'
timestamp = 'timestamp'
mac = hmac.new("33fsfsdgvwrg2g223f4f42gf4f34f43f", digestmod=hashlib.sha1)
mac.update(method)
mac.update(url)
mac.update(data)
mac.update(timestamp)
print mac.hexdigest()
Here is the Javascript:
<script src="sha.js"></script>
<script>
var secret = '33fsfsdgvwrg2g223f4f42gf4f34f43f';
var message = 'methodurldatatimestamp';
var shaObj = new jsSHA(message, "ASCII");
document.write(shaObj.getHMAC(secret, "ASCII", "SHA-1", "HEX"));
</script>
Note that the Javascript code puts the full message ('methodurldatatimestamp') in the jsSHA constructor. I believe this is the key to your problem. Hope this helps!

Categories

Resources