Convert encryption function from Javascript to Python - javascript

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='

Related

is it possible to Python decode base64 string to Solana Transaction Object?

This is how it is done in JS:
const obj = Transaction.from(Buffer.from(base64string, 'base64'));
this is how I think it could be done in Python:
import base64
base64string = "<some jibberish>"
decode = base64.b64decode(code)
it produces a byte type thus far. I'm not sure if I'm on the right track here... I've tried using picke.loads to no avail.

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==

End2End encryption IOException: algid parse error, not a sequence

I'm generating the Public and Private key by using the Native Browser crypto API as below:
export const generateKeyPair = async (): Promise<CryptoKeyPair> => {
return await window.crypto.subtle.generateKey(
{
name: "ECDH",
namedCurve: "P-384",
},
true,
["deriveKey", "deriveBits"],
);
};
Then I'll export the publicKey by using the exportKey function under the window.crypto.subtle as below:
const keyPair: CryptoKeyPair = yield generateKeyPair();
const publicKeyArrayBuffer: ArrayBuffer = yield window.crypto.subtle.exportKey("raw", keyPair.publicKey);
const publicKeyAsBase64 = arrayBufferToBase64(publicKeyArrayBuffer);
If you have any suggestions, please let me know and help me to fix this issue.
Both codes use different curves, the Java code secp256r1 (aka P-256), the JavaScript code P-384. To make both codes compatible, the JavaScript code must apply the same curve as the Java code, i.e. P-256 (s. also here).
The Java code exports a public EC key in X.509/SPKI format, which is Base64 encoded. The JavaScript code exports the public key in uncompressed format 0x04|<x>|<y>. The export in X.509/SPKI format is possible with spki as 1st parameter, s. here and here.

Equivalent JavaScript code to generate SHA256 hash

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

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