convert a text to hash in node js - javascript

I want to convert a text to hash id of numbers using node js. Already have a java program to convert but same kind of implementation to be done using node js.
Java Code
public static long generateId(String text) {
byte[] buffer = null;
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA1");
md.reset();
buffer = text.getBytes(Charsets.UTF_8);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
md.update(buffer);
byte[] digest = md.digest();
String hexStr = "";
for (int i = 0; i < digest.length; i++) {
hexStr += Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1);
}
long hashid = 0;
for (int i = 0; i < hexStr.length(); i++)
hashid += Math.abs((long) Math.pow(27, 10 - i) * ('a' - (1 + hexStr.charAt(i))));
return hashid;
}
I was able to convert into nodejs upto digest after this I am unable to proceed.
function generateHashCode()
{
var text = '9/01/2017'+'xx'+'405'+''+'SDD'+'MDD'+'9';
var crypto = require('crypto');
console.log(crypto.createHash('SHA1').update(text).digest("hex"));
var hexDigest = crypto.createHash('SHA1').update(text).digest("hex");
var hexStr;
}
Kindly help me on this

function generateHashCode(text)
{
// assuming text is UTF-8 encoded
var crypto = require('crypto');
var hexDigest = crypto.createHash('SHA1').update(text).digest(); // this should be .digest() not .digest('hex')
var hexStr = "";
for (var i = 0; i < hexDigest.length; i++) {
hexStr += (((hexDigest[i] - 0x100) & 0xff) + 0x100).toString(16).substr(1); // fixed some math issues here
}
var hashid = 0;
var a = 'a'.charCodeAt(0); // or just var a = 97;
for (var i = 0; i < hexStr.length; i++)
hashid += Math.abs(Math.pow(27, 10 - i) * (a - (1 + hexStr.charCodeAt(i))));
return hashid;
}
console.log(generateHashCode("batman"));

Related

Javascript Vernam Cipher - ensure output between unicode 32 and 126

I've implemented the below as mask for some data:
function jEncryptDecrypt(data,key) {
let jKey = ''
let bytKey = [];
let bytData = [];
for (let i = 1; i < (data.length/key.length) +1; i++) {
jKey = jKey + key;
}
let str = jKey.substring(0, data.length);
for (let i = 0; i < str.length; ++i) {
var code = str.charCodeAt(i);
bytKey = bytKey.concat([code & 0xff, code / 256 >>> 0]);
}
let str2 = data
for (let i = 0; i < str2.length; ++i) {
var code = str2.charCodeAt(i);
bytData = bytData.concat([code & 0xff, code / 256 >>> 0]);
}
for (let i = 0; i < bytData.length; ++i) {
bytData[i] = bytData[i] ^ bytKey[i];
}
str3 = String.fromCharCode(...bytData)
str3 = str3.replace(/\0/g, '');
return str3;
}
For some outputs the bytes in bytData map to escape characters - depending on where I run the code I either get the character (JSFiddle) or I get \uXXXX (third party application). The output could end up being dealt with on different platforms/languages, so ideally I'd like to avoid special characters and just have characters in the 32 to 126 unicode range?
Is this possible? The application I'm implementing this in is pretty restrictive, so I can't use any libraries, just pure JS.
Edit
I've changed the code to the below, which outputs an array of numbers on the encrypt, and accepts them as an input on the decrypt
function jEncryptDecrypt(data,key) {
let jKey = ''
let bytKey = [];
let bytData = [];
//expand key to cover length of input
for (let i = 1; i < (data.length/key.length) +1; i++) {
jKey = jKey + key;
}
//shorten key to same lenght as input
let str = jKey.substring(0, data.length);
//loop over key to create array of numbers from unicode value
for (let i = 0; i < str.length; ++i) {
var code = str.charCodeAt(i);
bytKey = bytKey.concat([code & 0xff, code / 256 >>> 0]);
}
//if data input is array no need to do anything
if (Array.isArray(data)) {
bytData = data;
//otherwise loop over data to create array of numbers from unicode value
} else {
let str2 = data
for (let i = 0; i < str2.length; ++i) {
var code = str2.charCodeAt(i);
bytData = bytData.concat([code & 0xff, code / 256 >>> 0]);
}
}
//XOR each data value with each key value in turn
for (let i = 0; i < bytData.length; ++i) {
bytData[i] = (bytData[i] ^ bytKey[i]);
}
//if input was array return string, otherwise return array
if (Array.isArray(data)) {
str3 = String.fromCharCode(...bytData)
str3 = str3.replace(/\0/g, '');
return str3;
} else {
return bytData;
}
}
It's clunky and hacky but works for my needs. If there is an answer to the original question that would still be much appreciated!

Browse is slowing down for a JavaScript code

I'm working on a JavaScript library for me. This library will help you to convert a binary number into a decimal number. The default JavaScript function can only convert before point (integers). But this code will convert floating numbers also (hopefully).
In order to test this when I ran this code on Firefox returned,
This page is slowed down your browser.
& Google Chrome returned nothing but just loading.
So I want to know what is the problem??
Here is my code
var x = "101.11";
var r = 0;
var ra = 0;
for (var i = 0; i < x.length; ++i) {
if (x.charAt(i) == ".") {
var Ap = i;
}
}
for (var j = 0; j < (x.length - Ap); ++j) {
var a = x.charAt(j);
r = r + a * Math.pow(2, ((x.length - Ap - 1) - j));
}
for (var k = Ap + 1;
(x.length - Ap) < k; ++k) {
var b = x.charAt(k);
ra = ra + b * Math.pow(2, (Ap - k));
}
document.write(r);
if (ra <= 0) {
document.write("." + ra);
}
Here is the solution. I'm very much thankful to you people.
/*
It's a dumb library for converting binary fraction number into a desimal number.
Created by : Adib Rahman
Last update : 12:36 30/01/2020
*/
function print(something)
{
document.write(something);
}
var x = "010101010.111";
var r = 0;
var ra = 0;
for(var i=0;i<x.length;++i)
{
if(x.charAt (i)== ".")
{
var Ap=i;
}
}
var beforePoint = (x.length-(x.length-Ap-1))-1;
var afterPoint = x.length-Ap-1;
for(var j=0;j<beforePoint;++j)
{
r = r+(x.charAt(j))*Math.pow(2,(beforePoint-j-1));
}
for(var k=Ap+1;k<x.length;++k)
{
var ra = ra+(x.charAt(k))*Math.pow(2,(Ap-k));
}
//Final Result
if(ra >=0)
{
print(r+ra);
}
else
{
print(r);
}

Equivalent JavaScript syntax

I am new to javascript and wondering what is the equivalent javascript syntax for below Java Code.
public static void crcValue(byte[] value) {
byte crc = 0;
for (int i = 0; i < 15; i++) {
crc = (byte) (value[i] + crc);
}
value[15] = (byte) (crc & 255);
}
I have tried the below code.
var cmd = new ArrayBuffer(16);
function crcValue(cmd){
var crc;
for (var i = 0; i < 15; i++) {
crc = cmd[i] + crc;
}
cmd[16] = crc & 255 ;
}

Convert JavaScript into C# - obfuscation

i have the below Javascript code i need to convert to C#
function obfuscateApiKey(timestamp, key) {
var high = timestamp.substring(timestamp.length - 6);
var low = (parseInt(high) >> 1).toString();
var apiKey = "";
while (low.length < 6) {
low = "0" + low;
}
for (var i = 0; i < high.length; i++) {
apiKey += key.charAt(parseInt(high.charAt(i)));
}
for (var j = 0; j < low.length; j++) {
apiKey += key.charAt(parseInt(low.charAt(j)) + 2);
}
console.log(apiKey)
return apiKey;
}
I have started the conversion below in C# but i am stuck at converting
apiKey += key.charAt(parseInt(high.charAt(i)));
var timestamp = DateTime.Now.ToString();
var high = timestamp.Substring(timestamp.Length - 6);
var low = (Int32.Parse(high) >>1).ToString();
while (low.Length < 6)
{
low = "0" + low;
}
for (var i = 0; i < high.Length; i++)
{
char ch = (int.Parse(high)[i]); //Getting stuck here! < this is incorrect.
}
you got it wrong at (high)[i] try high[i] you are converting char to int and then assign it to char.
var apiKey = "";
var timestamp = DateTime.Now.ToString();
var high = timestamp.Substring(timestamp.Length - 6);
var low = (Int32.Parse(high) >>1).ToString();
while (low.Length < 6)
{
low = "0" + low;
}
for (var i = 0; i < high.Length; i++)
{
apiKey += high[i];
}
and for your comment char ch = low[j] + 2
apiKey += (Convert.ToInt32(low[j]) + 2).ToString();

Find Server Seed from Hash Verification Script

View this jsfiddle: https://jsfiddle.net/1L1uqcgv/6/
function refreshTable(){
var hash = document.getElementById("gameHash").value;
var lastHash = "";
var amount = document.getElementById("gameAmount").value;
var tableBody = document.getElementById("tbody");
tableBody.innerHTML = "";
for(var i=0; i<amount; i++){
var gameHash = (lastHash!=""?genGameHash(lastHash):hash);
var gameCrash = crashPointFromHash((lastHash!=""?genGameHash(lastHash):hash));
var clr = gameCrash > 1.97 ? 'green': (gameCrash < 1.97 ? 'red' : 'blue');
tableBody.innerHTML += "<tr><td>"+gameHash+"</td><td style='background:" + clr + "'>"+gameCrash+"</td></tr>";
lastHash = gameHash;
}
}
function divisible(hash, mod) {
// So ABCDEFGHIJ should be chunked like AB CDEF GHIJ
var val = 0;
var o = hash.length % 4;
for (var i = o > 0 ? o - 4 : 0; i < hash.length; i += 4) {
val = ((val << 16) + parseInt(hash.substring(i, i+4), 16)) % mod;
}
return val === 0;
}
function genGameHash(serverSeed) {
return CryptoJS.SHA256(serverSeed).toString()
};
function hmac(key, v) {
var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
return hmacHasher.finalize(v).toString();
}
function crashPointFromHash(serverSeed) {
// see: provably fair seeding event
var hash = hmac(serverSeed, '000000000000000007a9a31ff7f07463d91af6b5454241d5faf282e5e0fe1b3a');
// In 1 of 101 games the game crashes instantly.
if (divisible(hash, 101))
return 0;
// Use the most significant 52-bit from the hash to calculate the crash point
var h = parseInt(hash.slice(0,52/4),16);
var e = Math.pow(2,52);
return (Math.floor((100 * e - h) / (e - h))/100).toFixed(2);
};
Is it possible to find the "serverSeed" as shown in lines 31 and 41?
To find previous games, a hash is entered into the box, showing all previous games. Would serverSeed be used to find these hashes, or does the single hash create all previous hashes?
The ServerSeed is the hash you input in order to see the crash point and to view the previous games.

Categories