Code on JS
var base64 = CryptoJS.enc.Base64.stringify(requestContentString);
How do I rewrite it to Kotlin?
I write
val base64 = Base64.encodeToString(requestContentString.toByteArray(), Base64.DEFAULT)
But the answers are different
var base64 = CryptoJS.enc.Base64.stringify(**requestContentString**);
requestContentString is WordAray = CryptoJS.SHA256("String in here")
val base64 = Base64.encodeToString(requestContentString.toByteArray(), Base64.DEFAULT)
Now you have string hashed in SHA-256 and encoded on Base64
Same result in kotlin
First hash string to SHA-256
val bytes = MessageDigest
.getInstance("SHA-256")
.digest(input.toByteArray())
Encode on Base64
val encodedString1 = Base64.encodeToString(bytes,Base64.NO_WRAP)
Related
I'm trying to convert this function from C# to node but I'm getting different results when I try to convert a buffer to a string.
string str = "34924979";
System.Security.Cryptography.SHA512 sha = new System.Security.Cryptography.SHA512Managed();
byte[] ba = System.Text.Encoding.ASCII.GetBytes(str);
byte[] data= sha.ComputeHash(ba);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(data));
>> `?????gV)????∟?Z?s??v$We-??N?"?w????0??\i♠G???
that's what i'm trying to do.
const crypto = require('crypto')
const str = '34924979';
const sha = crypto.createHash('sha512').update(str).digest('utf8');
const hash = sha.toString('utf-8').replace(/\uFFFD/g, '?');
console.log(hash);
>> `????gV)????∟?Z?v$We-??N?"?w????0?\i♠Gߕ?
You're using different encodings in C# and JS.
Try changing the JS code to the following:
const sha = crypto.createHash('sha512').update(str).digest('ascii');
const hash = sha.toString('ascii');
I have a bit string that I want to convert to base64 but it doesn't look like there's a native function to do this and I couldn't find a node module either. ):
Input: 100110110101000110100011011001100010110100011011001100100110100011000001100000110000011000001100001001010100111110000011001111100101010011111010011100010110001001001001100000110100111010010100111110000111001000100000110001001000101100111110011001001001101011010001011001001101001010000011000100100100110000011010011
Output: base64 representation of that equivalent binary value
Maybe a better question is how to convert a bit string into a buffer? Not sure
As you guessed, the main thing is converting the string into something easier to convert to base64 and then converting that to base64.
In the code below, we do these conversion sequences:
bit string -> BigInt -> array of byte-sized ints -> binary string -> base64
base64 -> binary string -> array of byte-sized bit strings -> bit string
const encode = bitstr => {
const bytes = [];
// convert bit string to BigInt
let value = BigInt('0b' + bitstr);
// chop it up into bytes
while (value > 0n) {
bytes.unshift(Number(value & 0xffn));
value >>= 8n;
}
// convert to binary string and encode as base64
return btoa(String.fromCharCode.apply(null, bytes));
};
const decode = b64 => {
// decode base64 to binary string
const bstr = atob(b64);
// convert binary string to bit string
return new Array(bstr.length).fill(0).map(
(_,i) => bstr.charCodeAt(i).toString(2).padStart(8, i ? '0' : '')
).join('');
};
const bitstr = '100110110101000110100011011001100010110100011011001100100110100011000001100000110000011000001100001001010100111110000011001111100101010011111010011100010110001001001001100000110100111010010100111110000111001000100000110001001000101100111110011001001001101011010001011001001101001010000011000100100100110000011010011';
const encoded = encode(bitstr);
const decoded = decode(encoded);
console.log(bitstr);
console.log(encoded);
console.log(decoded);
I am using the crypto-js library to implement the HMACSHA1 for my javascript code
the code looks like this
const hash1 = require("crypto-js");
let signature = "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=6304033672×tamp=1623098533&user[login]=john#mail.com&user[password]=123456789"
let key = "dBV2PdhYMnruSMb"
let hash = hash1.HmacSHA1(signature, key).toString()
console.log(hash)
//which prints
467280c4cb82fc97bd04c51d8a846446ad6e82e1
this obviously is pretty easy in javascript. But then I tried using the same exact string and key in c# and it prints out a completely different string. I am lost and don't know how to solve this issue.
Here is my attempt to implement this in C#
string signSession = "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=6304033672×tamp=1623098533&user[login]=john#mail.com&user[password]=123456789"
string key = "dBV2PdhYMnruSMb="
//convert the session signature string to a byte array
byte[] signature = Encoding.UTF8.GetBytes(signSession.ToString());
var apiKey = Convert.FromBase64String(key);
//Generate a HMACSHA1 signature
using(HMACSHA1 hmac = new HMACSHA1(apiKey))
{
byte[] signatureBytes = hmac.ComputeHash(signature);
string base64Signature = Convert.ToBase64String(signatureBytes);
Console.WriteLine(base64Signature);
session.Signature = base64Signature;
}
//And this prints
sztTnSTv2xvuA7pPXxk2cKMP0Eo=
//which is wrong. It should be the same as the javascript result
Im not sure what im doing wrong here and is my C# implementation right?
Your key is different. While crypto-js expects a string, C# expects a byte array. You shouldn't use FromBase64String() but Encoding.UTF8.GetBytes(). As #jps mentioned in the comment
Of course it's different, your JS implementation has a hex encoded
output but in your C# implementation you're base64 encoding the
result.
you should convert the byte-array to a hex-string like so
string signSession = "application_id=3610&auth_key=aDRceQyTXSYEdJU&nonce=6304033672×tamp=1623098533&user[login]=john#mail.com&user[password]=123456789";
string key = "dBV2PdhYMnruSMb";
//convert the session signature string to a byte array
byte[] signature = Encoding.UTF8.GetBytes(signSession);
var apiKey = Encoding.UTF8.GetBytes(key);
//Generate a HMACSHA1 signature
using (HMACSHA1 hmac = new HMACSHA1(apiKey))
{
byte[] signatureBytes = hmac.ComputeHash(signature);
string hexSignature = BitConverter.ToString(signatureBytes).ToLowerInvariant().Replace("-", "");
Console.WriteLine(hexSignature);
session.Signature = hexSignature;
}
I am converting a base64 String to byte array using atob() function.
I get the base64String from below code:
var dataURL = $("#graph-panel .canvasjs-chart-canvas").get(0).toDataURL();
Contents of dataURL is as follows:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAu4AAAEiCAYAAACm31eYAAAgAElEQVR4nO3d+ZPc5n3n8f5f8D/AWZcrclLeILE2yuGsbG/KjuxNdg2tt7xOrPKqnLVK5dokiMobrx1XjnUgiZIMUhJ4ixSv4QGRw1O8xWvA+xje9zU8vvvD9NN8Go1G90x3D/A8eL+qUEU2Gt1PP0ADn37mwfM0BAAAAEDlNcouAAAAAIDeCO4AAACAAQjuAAAAgAEI7gAAAIABCO4AAACAAQjuAFAgSRJpNBqSJEnrsTRNW495nie+77dt4/u+eJ7X9TV935dGo9FaoigaWfmHKa8uAABzh+AOAD34vi+O47T+r4d1FWbTNBWR9lCfx/O8ttcSEXEcp7U9AADdENwBoA+qZVwFdZ0e5Ita26Mo6tg2S72+WvTW/CiKWu+lt9br2+Q9PwiC3PWq7GqdXu7sewVB0PpRon5kZMuq/1jRX1ffRmT6h4qqC7UAAHrjbAkAfVBBU4VOnd7Kng2pul5daPK6oqjQrJch+3/Vgp9t7VfrVVhX61X5fd9v+yz6uux76durz5dXFyLToV3/nOqHg+I4Ttv/87obAQA6EdwBoE+O43R0c1FUy3RRAPV9f8brgyBoheAoitrePxukRaZDsB6+s+UtKoNqne+2bV5wz75WXplEpO0HRTbwq9Z9AEAxgjsA9CEIglZw11uhlW6BVddPcM++th6g+w3uReE7CIK2MujdVbKt+b2Cu8iz1nMVvNVzsvSwnhfcu/0gAgA8Q3AHgB70LijdusP0E9x79XEfVot7UfjW3yP7I2SmLe469VqzbXEnuANAbwR3AOgh2wc7r696P8FdZDq0Zrf1PE/SNO3ax71b15d+grveip7tA68HaLVutsFdf9+8Pu76axHcAWB2CO4AUKBbK3l2/PV+g7tI54gr2RBbtG42Le76KDR6C3veCDb9Bnf177wRaUSedaHRb5…
The above base64 String is not a complete string I think. Whatever the string that got printed in the console I have pasted it above.
I am passing this base64 String to the following function:
var bytes = b64DecodeUnicode(dataUrl);
function b64DecodeUnicode(str) {
console.log(str);
// Going backwards: from bytestream, to percent-encoding, to original string.
return decodeURIComponent(atob(str).split('').map(function(c) {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
}).join(''));
}
While executing the above code I am getting the following errror:
InvalidCharacterError: String contains an invalid character
[EDIT]
Following is the complete Base64 String:
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAu4AAAEiCAYAAACm31eYAAAgAElEQVR4nO3d+ZPc5n3n8f5f8D/AWZcrclLeILE2yuGsbG/KjuxNdg2tt7xOrPKqnLVK5dokiMobrx1XjnUgiZIMUhJ4ixSv4QGRw1O8xWvA+xje9zU8vvvD9NN8Go1G90x3D/A8eL+qUEU2Gt1PP0ADn37mwfM0BAAAAEDlNcouAAAAAIDeCO4AAACAAQjuAAAAgAEI7gAAAIABCO4AAACAAQjuAFAgSRJpNBqSJEnrs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VGD7uzDe56n/mi4SCzwzDq8oZmVEE+2x+/aFQZ/fPMNLjn3eTKzakAAAAoMpJx3LN9vlXIzU7AlA2kvSZgUuG4aAImFcCLJmDqNka8Hsaz75H94dFtyRsKU1+vv5/68ZItqx7yGQ4SAAAAIiO8OdU0eRMwlY0JmAAAAKAQ3DX93PA6V7qNLQ8AAIB6IhlmJEnSc0SbuVCVHxAAAACoBoI7AAAAYACCOwAAAGAAgjsAAABgAII7AAAAYACCOwAAAGAAgjsAAABggP8PmhrfBzyexNsAAAAASUVORK5CYII=
Looks like you're trying to convert a DataURL using the atob() function, but you have missed a step.
The DataURL contains information about the media type and the encoding like so:
data:[<mediatype>][;base64],<data>
You can try retrieving only the data by using String Split on base64,
Try this:
data = str.split('base64,')[1];
Reference: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
I have achieved the conversion with following code:
var dataURL = $("#graph-panel .canvasjs-chart-canvas").get(0).toDataURL();
var byteArr = b64toArray(dataURL);
function b64toArray(b64Data){
var byteCharacters = atob(b64Data);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
return byteArray;}
I have following security encoding implemented in my c# web api:
string testStr = "test";
ASCIIEncoding encoding = new ASCIIEncoding(); //using System.Text;
byte[] byteData = encoding.GetBytes(testStr);
MD5 md5 = MD5.Create(); //using System.Security.Cryptography;
string hash = md5.ComputeHash(byteData);
string md5Base64 = Convert.ToBase64String(hash);
I bind this md5Base64 string in header and compare it in API request. This works fine when I hit the API from C# code. Now I need to use it in javascript, so will need js equivalent of above code.
I have tried following but it is giving different output:
var testStr = 'test';
var byteData = testStr.split ('').map(function (c) { return c.charCodeAt (0); });
var hash = MD5(value.join(','));
var md5Base64 = btoa(hash);
the MD5 function used here is from https://stackoverflow.com/a/33486055/7519287
Please let me know what is wrong here.
The problem with your JavaScript code is that you're doing unnecessary conversions: MD5 already takes a string. Furthermore, more conversions after hashing are required.
If we have the following C# code:
string tmp = "test";
byte[] bTmp = System.Text.Encoding.UTF8.GetBytes(tmp);
byte[] hashed = null;
using (System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
{
hashed = md5.ComputeHash(bTmp);
}
Console.WriteLine(Convert.ToBase64String(hashed));
Fiddle
then the equivalent JavaScript code is:
var tmp = 'test';
var hashed = hex2a(MD5(tmp)); // md5 src: https://stackoverflow.com/a/33486055/7519287
// src: https://stackoverflow.com/a/3745677/3181933
function hex2a(hexx) {
var hex = hexx.toString();//force conversion
var str = '';
for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str;
}
alert(btoa(hashed));
Fiddle
Because MD5 returns a hex string, you have to convert that to ASCII before you can base64 encode it. I wonder if you need base64 encoding? MD5 is usually represented as a hex string. Perhaps on the C# side, instead of Convert.ToBase64String(hashed), you could use BitConverter.ToString(hashed).Replace("-", "") to get a hex string for the MD5 hash? Then you could simply just use MD5(tmp) in JavaScript.