Hex to Windows-1251 with JavaScript - javascript

I'm trying to convert a hexadecimal string to string with Windows-1251 encoding. I need to use JavaScript. I've tried using this sample that someone posted:
var win1251 = new TextDecoder("windows-1251");
for (var i = 0x00; i < 0xFF; i++) {
var hex = (i <= 0x0F ? "0" : "") + i.toString(16).toUpperCase();
decodeMap[hex] = win1251.decode(Uint8Array.from([i]));
}
but I can't seem to make it work. Can someone please help out?

Propably you're using it in incorrect way.
The code in you post creates dictionary (hex => windows-1251).
So, to translate hex string to windows-1251 string you have to:
split your hex string into array with 2-hex elements
Translate every element to windows-1251
Join result array into string
var decodeMap = {};
var win1251 = new TextDecoder("windows-1251");
for (var i = 0x00; i < 0xFF; i++) {
var hex = (i <= 0x0F ? "0" : "") + i.toString(16).toUpperCase();
decodeMap[hex] = win1251.decode(Uint8Array.from([i]));
}
var number = "3230313830363131313535303435303831";
var hexarr = number.toUpperCase().match(/[0-9A-F]{2}/g)
var win1251arr = hexarr.map(el=> decodeMap[el]);
console.log(win1251arr.join(""))
You can also do it in much shorter way (directly translate your hex string without creating dictionary):
var win1251 = new TextDecoder("windows-1251");
var number = "3230313830363131313535303435303831";
var arr = number.toUpperCase().match(/[0-9A-F]{2}/g).map(el=>"0x"+el);
var uarr = Uint8Array.from(arr);
console.log(win1251.decode(uarr));
If your browser doesn't support TextDecoder, you can use dictionary from first snippet:
var decodeMap = getHexToWin1251Dictionary();
var number = "3230313830363131313535303435303831";
var hexarr = number.toUpperCase().match(/[0-9A-F]{2}/g)
var win1251arr = hexarr.map(el=> decodeMap[el]);
console.log(win1251arr.join(""))
// function below returns content of decodeMap from first snippet
function getHexToWin1251Dictionary(){
return {"10":"\u0010","11":"\u0011","12":"\u0012","13":"\u0013","14":"\u0014","15":"\u0015","16":"\u0016","17":"\u0017","18":"\u0018","19":"\u0019","20":" ","21":"!","22":"\"","23":"#","24":"$","25":"%","26":"&","27":"'","28":"(","29":")","30":"0","31":"1","32":"2","33":"3","34":"4","35":"5","36":"6","37":"7","38":"8","39":"9","40":"#","41":"A","42":"B","43":"C","44":"D","45":"E","46":"F","47":"G","48":"H","49":"I","50":"P","51":"Q","52":"R","53":"S","54":"T","55":"U","56":"V","57":"W","58":"X","59":"Y","60":"`","61":"a","62":"b","63":"c","64":"d","65":"e","66":"f","67":"g","68":"h","69":"i","70":"p","71":"q","72":"r","73":"s","74":"t","75":"u","76":"v","77":"w","78":"x","79":"y","80":"Ђ","81":"Ѓ","82":"‚","83":"ѓ","84":"„","85":"…","86":"†","87":"‡","88":"€","89":"‰","90":"ђ","91":"‘","92":"’","93":"“","94":"”","95":"•","96":"–","97":"—","98":"","99":"™","00":"\u0000","01":"\u0001","02":"\u0002","03":"\u0003","04":"\u0004","05":"\u0005","06":"\u0006","07":"\u0007","08":"\b","09":"\t","0A":"\n","0B":"\u000b","0C":"\f","0D":"\r","0E":"\u000e","0F":"\u000f","1A":"\u001a","1B":"\u001b","1C":"\u001c","1D":"\u001d","1E":"\u001e","1F":"\u001f","2A":"*","2B":"+","2C":",","2D":"-","2E":".","2F":"/","3A":":","3B":";","3C":"<","3D":"=","3E":">","3F":"?","4A":"J","4B":"K","4C":"L","4D":"M","4E":"N","4F":"O","5A":"Z","5B":"[","5C":"\\","5D":"]","5E":"^","5F":"_","6A":"j","6B":"k","6C":"l","6D":"m","6E":"n","6F":"o","7A":"z","7B":"{","7C":"|","7D":"}","7E":"~","7F":"","8A":"Љ","8B":"‹","8C":"Њ","8D":"Ќ","8E":"Ћ","8F":"Џ","9A":"љ","9B":"›","9C":"њ","9D":"ќ","9E":"ћ","9F":"џ","A0":" ","A1":"Ў","A2":"ў","A3":"Ј","A4":"¤","A5":"Ґ","A6":"¦","A7":"§","A8":"Ё","A9":"©","AA":"Є","AB":"«","AC":"¬","AD":"­","AE":"®","AF":"Ї","B0":"°","B1":"±","B2":"І","B3":"і","B4":"ґ","B5":"µ","B6":"¶","B7":"·","B8":"ё","B9":"№","BA":"є","BB":"»","BC":"ј","BD":"Ѕ","BE":"ѕ","BF":"ї","C0":"А","C1":"Б","C2":"В","C3":"Г","C4":"Д","C5":"Е","C6":"Ж","C7":"З","C8":"И","C9":"Й","CA":"К","CB":"Л","CC":"М","CD":"Н","CE":"О","CF":"П","D0":"Р","D1":"С","D2":"Т","D3":"У","D4":"Ф","D5":"Х","D6":"Ц","D7":"Ч","D8":"Ш","D9":"Щ","DA":"Ъ","DB":"Ы","DC":"Ь","DD":"Э","DE":"Ю","DF":"Я","E0":"а","E1":"б","E2":"в","E3":"г","E4":"д","E5":"е","E6":"ж","E7":"з","E8":"и","E9":"й","EA":"к","EB":"л","EC":"м","ED":"н","EE":"о","EF":"п","F0":"р","F1":"с","F2":"т","F3":"у","F4":"ф","F5":"х","F6":"ц","F7":"ч","F8":"ш","F9":"щ","FA":"ъ","FB":"ы","FC":"ь","FD":"э","FE":"ю"};
}

Related

Java SHA-1 to javascript using CryptoJS

i have such a code to generate password written in Java
MessageDigest messageDigestPassword = MessageDigest.getInstance("SHA1");
messageDigestPassword .reset();
byte[] password = "password".getBytes();
messageDigestPassword .update(password);
byte[] encryptedPassword = messageDigestPassword .digest();
String date = "2019-10-22T11:33:13.393Z";
byte[] dateBytes = date.getBytes(StandardCharsets.UTF_8);
int offset = 0;
byte[] outputBytes = new byte[dateBytes.length + encryptedPassword .length];
System.arraycopy(dateBytes, 0, outputBytes, offset, dateBytes.length);
offset += dateBytes.length;
System.arraycopy(encryptedPassword , 0, outputBytes, offset, encryptedPassword .length);
MessageDigest finalMessageDigeset = MessageDigest.getInstance("SHA-1");
finalMessageDigeset.reset();
finalMessageDigeset.update(outputBytes);
byte[] finalPasswordBytes= finalMessageDigeset .digest();
String finalBase64Password = new String(Base64.encode(finalPasswordBytes));
and im trying to rewrite it to JavaScript to use it in postman with - CryptoJS
So far i have :
function wordArrayToByteArray(wordArray, length) {
if (wordArray.hasOwnProperty("sigBytes") &&
wordArray.hasOwnProperty("words")) {
length = wordArray.sigBytes;
wordArray = wordArray.words;
}
var result = [],
bytes,
i = 0;
while (length > 0) {
bytes = wordToByteArray(wordArray[i], Math.min(4, length));
length -= bytes.length;
result.push(bytes);
i++;
}
return [].concat.apply([], result);
}
function stringToBytes ( str ) {
var ch, st, re = [];
for (var i = 0; i < str.length; i++ ) {
ch = str.charCodeAt(i); // get char
st = []; // set up "stack"
do {
st.push( ch & 0xFF ); // push byte to stack
ch = ch >> 8; // shift value down by 1 byte
}
while ( ch );
// add stack contents to result
// done because chars have "wrong" endianness
re = re.concat( st.reverse() );
}
// return an array of bytes
return re;
}
var dateFixed = "2019-10-22T11:33:13.393Z";
var fixedDateBytes = stringToBytes(dateFixed);
var sha1Password= CryptoJS.SHA1("password");
console.log("sha1Password",sha1Password.toString(CryptoJS.enc.Hex));
var sha1PasswordBytes= wordArrayToByteArray(sha1Password, 20);
var concatedBytes= fixedDateBytes.concat(sha1PasswordBytes);
var finalShaPassWords= CryptoJS.SHA1(concatedBytes);
console.log("finalShaPassWords",finalShaPassWords.toString(CryptoJS.enc.Hex));
console.log("finalShaPassWords",finalShaPassWords.toString(CryptoJS.enc.Base64));
However unfortunatelly Base64 representations written in those 2 languages doesnt match.
I have checked and bytes from date are equal. Bytes from hashed password are not. So hashing after concat fails in JavaScript.
I have checked first password hashing and generated bytes and both of them are the same. So my guess line var sha1PasswordBytes= wordArrayToByteArray(sha1Password, 20); causes that line var finalShaPassWords= CryptoJS.SHA1(concatedBytes); returns bad value.
Can someone give me some idea what is wrong? Mayby it should be written diffrent ?
Since you are using CryptoJS anyway, you can also use the CryptoJS encoders and the WordArray#concat-method, which considerably simplifies the code:
var CryptoJS = require("crypto-js");
// Input
var inPwd = "password";
var inDate = "2019-10-22T11:33:13.393Z";
// Processing
var pwdHash = CryptoJS.SHA1(inPwd); // hash and convert to WordArray
var date = CryptoJS.enc.Utf8.parse(inDate); // convert to WordArray
var joinedData = date.clone().concat(pwdHash); // join date and hashed password
var joinedDataHash = CryptoJS.SHA1(joinedData); // hash joined data
var joinedDataHashB64 = CryptoJS.enc.Base64.stringify(joinedDataHash); // convert to Base64 string
// Output
console.log("Result: " + joinedDataHashB64 ); // Output: D235TBTZMfpSyB/CDl5MHAjH5fI=
The output of this code is the same as the output of the Java-code: D235TBTZMfpSyB/CDl5MHAjH5fI=

How to build a binary-array from hex strings

I'm new to the concept of working with data on the binary level and am hoping someone can give me a hand here...
I'd like to build a binary buffer out of a series of hex numbers that are represented as strings.
For example,
suppose I have "xFCx40xFF" and I want to turn this into an array that looks like: 111111000100000011111111.
What's the best way to do this?
My best attempt seems to not be working:
var raw = "xFCx40xFF"
var end = raw.length-2;
var i = 1;
var j = 0;
var myArray = new Uint8Array(raw.len);
while (i < end) {
var s = raw.substr(i,2);
var num = parseInt(s,16);
i += 3;
myArray[j] = num;
j += 8;
}
Each 3 characters in string will represent 1 number in Uint8Array. Each number in Uint8Array will represent 8 bits. Your code was creating Uint8Array larger than needed and then placing values are wrong locations.
I have simplified the code to use a singe index i which represents the location in the Uint8Array. Corresponding location in string can be easily computed from i.
var raw = "xFCx40xFF"
var myArray = new Uint8Array(raw.length / 3);
for (var i = 0; i < raw.length / 3; i++) {
var str = raw.substr(3 * i + 1, 2);
var num = parseInt(str, 16);
myArray[i] = num;
}
Remove the 'x' character of your hex string and call parseInt() with the radix 16 and toString() with the radix 2 to get the binary string.
var raw = "xFCx40xFF";
var bin = parseInt(raw.split('x').join(''), 16).toString(2);
document.body.textContent = bin;
and if you need an array, just add .split('') at the end.
parseInt(raw.split('x').join(''), 16).toString(2).split('');
or iterate through each character.

Select 2 characters after a particular substring in javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.
.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle
I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know
indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);
Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.
There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

Split url into tab in javascript

input:
"/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
javascript:
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
var parts = parmeters.split('[&=]');
output of my js code:
0: "passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false"
length: 1
i want to split my url into a map with key:value like this
output:
origin:THR
destination:TDR
goDate:2015-01-09
passengers:STANDARD:1
returnDate:2015-01-10
max:0
withThac:false
My code not do exactly what i want in output, what is wrong ?
You should split with
var params = parmeters.split('&')
and then split all the values you get
for (var i = 0,len = params.length; i<len;i++){
var data = params[i].split("=", 2); // Max 2 elements
var key = data[0];
var value = data[1];
...
}
i think your wrong ' characters
var params = {};
var paramDelim = link.indexOf('?');
var parmeters = link.substring(paramDelim + 1, link.length);
/*--> i think used regexp. Clear ' Char. --> */var parts = parmeters.split(/[&=]/);
use this like..
good luck
A possible solution using ECMA5 methods and assuming that your string is always the same pattern.
var src = '/desh/HRTY/THR/TDR/2015-01-09?passengers=STANDARD:1&returnDate=2015-01-10&max=0&withThac=false',
slice = src.split(/[\/|?|&]/).slice(3),
data = slice.reduce(function (output, item) {
var split = item.split('=');
output[split.shift()] = split.shift();
return output;
}, {
origin: slice.shift(),
destination: slice.shift(),
goDate: slice.shift()
});
document.body.appendChild(document.createTextNode(JSON.stringify(data)));

How could I possibly shorten this script than how I am doing it?

Trying to loop through every possible combination of characters. I've tried mixing various arrays, takes about three lines but then I can't concatenate. Or maybe there's a better way to concatenate as well? Where I have the +''+letters in between the quotes should be a line break but stackoverflow doesn't allow :P Sorry If I'm too vague I just shortened this script and altered it in a way it works the same but stackoverflow allows?
function go() {
var letters = ('abcdefghijklmnopqrstuvwxyz').split('');
var p1 = '';
var p2 = '';
for (var i = 0;i < 27; i++) {
var p1 = p1+''+letters[i];
var p2 = p2+''+letters[0]+letters[i];
var p3 = p3+''+letters[1]+letters[i];
var p4 = p4+''+letters[2]+letters[i];
var p5 = p5+''+letters[3]+letters[i];
var p6 = p6+''+letters[4]+letters[i];
var p7 = p7+''+letters[5]+letters[i];
var p8 = p8+''+letters[6]+letters[i];
var p9 = p9+''+letters[7]+letters[i];
var p10 = p10+''+letters[8]+letters[i];
var p11 = p11+''+letters[9]+letters[i];
var p12 = p12+''+letters[10]+letters[i];
var p13 = p13+''+letters[11]+letters[i];
var p14 = p14+''+letters[12]+letters[i];
var p15 = p15+''+letters[13]+letters[i];
var p16 = p16+''+letters[14]+letters[i];
var p17 = p17+''+letters[15]+letters[i];
var p18 = p18+''+letters[16]+letters[i];
var p19 = p19+''+letters[17]+letters[i];
var p20 = p20+''+letters[18]+letters[i];
var p21 = p21+''+letters[19]+letters[i];
}
}
Generally, for creating combinations of characters, You may use recursion (or just a stack) like this:
function handleString(str) {
if (str is valid combination of characters by Your rules) {
doSomething(str);
}
for each character c that may be added to incomplete str by Your rules {
handleString(str + c);
}
}
You must be careful not to create endless recursion, all this depends on Your rules. For example, to create all possible 3-character strings out of alphabet "abcdefgh", it may look like this:
function handleString(str, alphabet, length) {
// just in case...
if (str.length > length)
return;
// if the string has desired length (my rule), use it as a valid combination
if (str.length === length) {
console.log(str);
return;
}
// string doesn't have desired length yet, try adding
// each one of possible characters from the alphabet (my rule)
for (var i = 0; i < alphabet.length; i++)
handleString(str + alphabet.charAt(i), alphabet, length);
}
handleString("", "abcdefgh", 3);

Categories

Resources