Stuck converting Javascript function to VB.Net - javascript

I need help converting the following JS-function to vb.net please:
function testjs(s) {
var dict = {};
var data = (s + "").split("");
var currChar = data[0];
var oldPhrase = currChar;
var out = [currChar];
var code = 256;
var phrase;
for (var i=1; i<data.length; i++) {
var currCode = data[i].charCodeAt(0);
if (currCode < 256) {
phrase = data[i];
}
else {
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
}
out.push(phrase);
currChar = phrase.charAt(0);
dict[code] = oldPhrase + currChar;
code++;
oldPhrase = phrase;
}
return out.join("");
}
What my code looks like at the moment:
Private Function questionmarkop(ByVal ph As String, ByVal dictatcurr As String, ByVal ophoc As String) As String
Return If(ph = dictatcurr, dictatcurr, ophoc)
End Function
Private Function testvb(ByVal s As String) As String
Dim dict As New Dictionary(Of Integer, String)
Dim data As Char() = s.ToCharArray
Dim currchar As Char = data(0)
Dim oldphrase As String = currchar
Dim out As String() = {currchar}
Dim code As Integer = 256
Dim phrase As String = ""
Dim ret As String = ""
For i As Integer = 1 To data.Length - 1
Dim currcode As Integer = Convert.ToInt16(data(i))
If currcode < 256 Then
phrase = data(i)
Else
phrase = questionmarkop(phrase, dict(currcode), (oldphrase + currchar))
End If
ReDim Preserve out(out.Length)
out(out.Length - 1) = phrase
currchar = phrase(0)
dict.Item(code) = oldphrase + currchar
code += 1
oldphrase = phrase
Next
For Each str As String In out
ret = ret + str
Next
Return ret
End Function
When inputting the following string s: thisĂaveryshorttestđringtogiĆanexamplefČđackoĆrflow
The function should return: thisisaveryshortteststringtogiveanexampleforstackoverflow
The js function does exactly that, my vb function does not sadly.
The first time (or basically everytime) the if statement is not true, the next character will be wrong. So i figure there is something wrong with the line phrase = questionmarkop(phrase, dict(currcode), (oldphrase + currchar)).
With the test string i provided everything works until this, after that i have the first false char.
Can someone help me figure out what i am doing wrong here?

Based on discussion in the comments, it seems like the issue was producing a VB translation for this line:
phrase = dict[currCode] ? dict[currCode] : (oldPhrase + currChar);
I have only passing familiarity with Javascript, but I believe the key here is that dict[currCode] will return a type of null or missing value if there is not already an entry in the dictionary with key currCode. The .NET dictionary has facilities that will let you get the same effect, though the exact implementation is a little different.
The direct VB equivalent to this ternary and assignment is (I believe):
phrase = If(dict.ContainsKey(currCode), dict(currCode), oldPhrase & currChar)
You can eliminate a key lookup on the dictionary by using Dictionary.TryGetValue:
If Not dict.TryGetValue(currCode, phrase) Then
phrase = oldPhrase & currChar
End If
I doubt the code is performance-sensitive enough to care about the difference, so I would recommend to use the alternative that you find more clear to read.

Related

Node Red javascript Convert a HEX string to a ACSII string [duplicate]

How to convert from Hex string to ASCII string in JavaScript?
Ex:
32343630 it will be 2460
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;
}
hex2a('32343630'); // returns '2460'
Another way to do it (if you use Node.js):
var input = '32343630';
const output = Buffer.from(input, 'hex');
log(input + " -> " + output); // Result: 32343630 -> 2460
For completeness sake the reverse function:
function a2hex(str) {
var arr = [];
for (var i = 0, l = str.length; i < l; i ++) {
var hex = Number(str.charCodeAt(i)).toString(16);
arr.push(hex);
}
return arr.join('');
}
a2hex('2460'); //returns 32343630
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){
return String.fromCharCode(parseInt(v, 16));
}).join('');
document.write(asciiVal);
** for Hexa to String**
let input = '32343630';
Note : let output = new Buffer(input, 'hex'); // this is deprecated
let buf = Buffer.from(input, "hex");
let data = buf.toString("utf8");
I found a useful function present in web3 library.
var hexString = "0x1231ac"
string strValue = web3.toAscii(hexString)
Update: Newer version of web3 has this function in utils
The functions now resides in utils:
var hexString = "0x1231ac"
string strValue = web3.utils.hexToAscii(hexString)
I've found that the above solution will not work if you have to deal with control characters like 02 (STX) or 03 (ETX), anything under 10 will be read as a single digit and throw off everything after. I ran into this problem trying to parse through serial communications. So, I first took the hex string received and put it in a buffer object then converted the hex string into an array of the strings like so:
buf = Buffer.from(data, 'hex');
l = Buffer.byteLength(buf,'hex');
for (i=0; i<l; i++){
char = buf.toString('hex', i, i+1);
msgArray.push(char);
}
Then .join it
message = msgArray.join('');
then I created a hexToAscii function just like in #Delan Azabani's answer above...
function hexToAscii(str){
hexString = str;
strOut = '';
for (x = 0; x < hexString.length; x += 2) {
strOut += String.fromCharCode(parseInt(hexString.substr(x, 2), 16));
}
return strOut;
}
then called the hexToAscii function on 'message'
message = hexToAscii(message);
This approach also allowed me to iterate through the array and slice into the different parts of the transmission using the control characters so I could then deal with only the part of the data I wanted.
Hope this helps someone else!
console.log(
"68656c6c6f20776f726c6421".match(/.{1,2}/g).reduce((acc,char)=>acc+String.fromCharCode(parseInt(char, 16)),"")
)
An optimized version of the implementation of the reverse function proposed by #michieljoris (according to the comments of #Beterraba and #Mala):
function a2hex(str) {
var hex = '';
for (var i = 0, l = str.length; i < l; i++) {
var hexx = Number(str.charCodeAt(i)).toString(16);
hex += (hexx.length > 1 && hexx || '0' + hexx);
}
return hex;
}
alert(a2hex('2460')); // display 32343630
I use this one, it seems more clear to me as I also receive data with spaces like '30 31 38 30 38 30' and the output is 018080
hexToString(hex: string): string {
return hex.split(' ').map(s => string.fromCharCode(parseInt(s,16))).join('');
}

Generate CHAP response in java

Currently I'm trying to generate a chap response in java. It works in php... but our backend needs it done in java.
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal)
I've managed to find some javascript code, but the response is off by a few characters.
function getPapPassword(){
//function to add value padding to a string of x length default : null padding
String.prototype.pad = function (length, padding) {
var padding = typeof padding === 'string' && padding.length > 0 ? padding[0] : '\x00'
, length = isNaN(length) ? 0 : ~~length;
return this.length < length ? this + Array(length - this.length + 1).join(padding) : this;
};
//function to convert hex to ascii characters
String.prototype.packHex = function () {
var source = this.length % 2 ? this + '0' : this
, result = '';
for (var i = 0; i < source.length; i = i + 2) {
result += String.fromCharCode(parseInt(source.substr(i, 2), 16));
}
return result;
};
var challenge = "cda9af6faa83d0883d694fa58d2e88wh";
var password = "password123";
var hexchal = challenge.packHex();
var newchal = hexchal;
var response = md5('\0' + password + newchal);
}
return response;
}
Can anyone point me in the right direction or assist?
Thanks
Okay so what I've done is tried to convert from hex to ascii in java... here is my code.
public class App{
public String convertHexToString(String hex){
StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
//49204c6f7665204a617661 split into two characters 49, 20, 4c...
for( int i=0; i<hex.length()-1; i+=2 ){
//grab the hex in pairs
String output = hex.substring(i, (i + 2));
//convert hex to decimal
int decimal = Integer.parseInt(output, 16);
//convert the decimal to character
sb.append((char)decimal);
temp.append(decimal);
}
System.out.println("Decimal : " + temp.toString());
return sb.toString();
}
public static void main(String[] args) {
App app = new App();
System.out.println("ASCII : " + app.convertHexToString("9f9585f4e88305fde280c762925f37af"));
}
}
The php of the hex challenge output is: Ÿ•…ôèƒýâ€Çb’_7¯
The java output of the hex challenge is: ôèýâÇb_7¯
So I've found that the javascript is exactly the same as the java. Something is happening in php that is changing it. The php version works perfectly when I connect to the UAM with that chap response.

Write a Optimal program to remove numbers from a string and then result string should be reversed

Write a Optimal program to remove numbers from a string and then result string should be reversed for e.g Input = "A1B2" Output = "BA" in any language
the program which i came up with is this
var str = "A1B2";
var temp = "";
for(var i = str.length - 1; i >= 0; i--) {
if(!(str[i] >= 0 && str[i] <= 9))
temp += str[i]
}
var str = "A1B2"
str.split('').reverse().join('').replace(/[0-9]/g, '')
As you mentioned, You need answer in any language.
In java,
String str="A1B2";
String answer = new StringBuilder(str.replaceAll("[0-9]","")).reverse().toString();
System.out.println(answer);
You start at the last position of the input and check if it is a number, if it is, then skip it, otherwise, add it.
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
String newWord = "";
for (int i = input.length() - 1; i >= 0; i--) {
if (input.charAt(i) < '0' || input.charAt(i) > '9') {
newWord += input.charAt(i);
}
}
System.out.println(newWord);
}
Input:
B224SA54ABCR
Output:
RCBAASB
You should iterate char by char in your string and detect wether the current char is a letter or not, may be by using ASCII table. The reserving will be done by iterating from the end on the string to the beginning as you did in the shown code. At least this is what I would do in C, but other easier ways exist in java.
You should not use temp += ""if temp has not been initialized prior. I cannot recommend you any method or function to do so " in an optimal way since it depends on the language.
Here is a possible C solution :
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char line[128] = "A1B2C9C841630ERV221";
char res[128] = "";
for (int i = strlen(line) -1; i >= 0; --i)
{
if (isalpha(line[i]))
{
char currentChar[2];
currentChar[1] = 0;
currentChar[0] = line[i];
strcat(res, currentChar);
}
}
printf("%s\n", res);
Output : VRECCBA
Only thing you should care of is the size of line and res which I set to 128 which might not be enough depending of the length of the string you input.

Simply XOR encrypt in Javascript and Decrypt in Java

The purpose for this is not highly security-relevant and the key will be long, so I'm just wanting to use simple XOR encryption to the strings.
Well, the Javascript on the client is as follows:
function dc_encrypt(str, key)
{
var ord = []; var res = "";
var i;
for (i = 1; i <= 255; i++) {ord[String.fromCharCode(i)] = i}
for (i = 0; i < str.length; i++)
res += String.fromCharCode(ord[str.substr(i, 1)] ^ ord[key.substr(i % key.length, 1)]);
return(res);
}
And the Java is is:
public String dc_decrypt(String str, String key)
{
StringBuilder sb = new StringBuilder();
for(int i = 0; i < str.length(); i++)
sb.append((char)(str.charAt(i) ^ key.charAt(i % (key.length()))));
return(sb.toString());
}
Unfortunately this produces some very weird results. Some letters differ after encrypting in JS, sending the result through a POST and decrypt in Java.
In every case it doesn't seem to be reliable.
I assume the issue must have something to do with encoding... does someone know a more reliable solution for this?
Huge thanks in advance! :)
When XOR-encoding two strings, the resulting XOR-values of the individual characters sometimes do not result in characters that can be displayed.
Therefore one solution is to encode the result as a sequence of hex-values and then to decode these hex-values on the server side.
Javascript:
function encryptStringWithXORtoHex(input,key) {
var c = '';
while (key.length < input.length) {
key += key;
}
for(var i=0; i<input.length; i++) {
var value1 = input[i].charCodeAt(0);
var value2 = key[i].charCodeAt(0);
var xorValue = value1 ^ value2;
var xorValueAsHexString = xorValue.toString("16");
if (xorValueAsHexString.length < 2) {
xorValueAsHexString = "0" + xorValueAsHexString;
}
c += xorValueAsHexString;
}
return c;
}
Java-Code:
private static String decryptStringWithXORFromHex(String input,String key) {
StringBuilder c = new StringBuilder();
while (key.length() < input.length()/2) {
key += key;
}
for (int i=0;i<input.length();i+=2) {
String hexValueString = input.substring(i, i+2);
int value1 = Integer.parseInt(hexValueString, 16);
int value2 = key.charAt(i/2);
int xorValue = value1 ^ value2;
c.append(Character.toString((char) xorValue));
}
return c.toString();
};
Example:
Encode in Javascript:
encryptStringWithXORtoHex('Encrypt This','SecretKey');
returns the string 160b00001c043f452d3b0c10
Decrypting in Java:
decryptStringWithXORFromHex("160b00001c043f452d3b0c10","SecretKey")
returns Encrypt This
Please note: the shown solution only works for characters that have a charChode value of less or equal than 255. If you want to use the solution for unicode characters (e.g. €) you will have to change the code to take care of this.

Unicode value \uXXXX to Character in Javascript

I've never done this before and am not sure why it's outputting the infamous � encoding character. Any ideas on how to output characters as they should (ASCII+Unicode)? I think \u0041-\u005A should print A-Z in UTF-8, which Firefox is reporting is the page encoding.
var c = new Array("F","E","D","C","B","A",9,8,7,6,5,4,3,2,1,0);
var n = 0;
var d = "";
var o = "";
for (var i=16;i--;){
for (var j=16;j--;){
for (var k=16;k--;){
for (var l=16;l--;){
d = c[i].toString()
+ c[j].toString()
+ c[k].toString()
+ c[l].toString();
o += ( ++n + ": "
+ d + " = "
+ String.fromCharCode("\\u" + d)
+ "\n<br />" );
if(n>=500){i=j=k=l=0;} // stop early
}
}
}
}
document.write(o);
The .fromCharCode() function takes a number, not a string. You can't put together a string like that and expect the parser to do what you think it'll do; that's just not the way the language works.
You could ammend your code to make a string (without the '\u') from your hex number, and call
var n = parseInt(hexString, 16);
to get the value. Then you could call .fromCharCode() with that value.
A useful snippet for replacing all unicode-encoded special characters in a text is:
var rawText = unicodeEncodedText.replace(
/\\u([0-9a-f]{4})/g,
function (whole, group1) {
return String.fromCharCode(parseInt(group1, 16));
}
);
Using replace, fromCharCode and parseInt
If you want to use the \unnnn syntax to create characters, you have to do that in a literal string in the code. If you want to do it dynamically, you have to do it in a literal string that is evaluated at runtime:
var hex = "0123456789ABCDEF";
var s = "";
for (var i = 65; i <= 90; i++) {
var hi = i >> 4;
var lo = i % 16;
var code = "'\\u00" + hex[hi] + hex[lo] + "'";
var char = eval(code);
s += char;
}
document.write(s);
Of course, just using String.fromCharCode(i) would be a lot easier...

Categories