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.
Related
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('');
}
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 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.
I need some help with my code. What i am trying to do is find one string at a time in a sentence and replace the same string with a span tag.
I have achieved same with javascript but I am unsure of how to do it in C#
Code in js:
//this function takes 'buffer' as content &
//search query (multiple string values) as replaceStrings and highlights the query
function highlitor(buffer, replaceStrings)
{
var highlightedText = buffer;
for (var i = 0; i < replaceStrings.length; i++)
{
var exp = new RegExp("(" + replaceStrings[i] + ")", "gi");
highlightedText = highlightedText.replace(exp, "<span class='highlight-search-text'>$1</span>");
}
return highlightedText;
}
For example
buffer=" This is an exciting and enhansive test" replaceStrings=[exciting,enhace];
highlightedText="This is an <span class='highlight-text'>exciting</span> and <span class='highlight-text'>enhansive</span> test"
Thanks in advance.
I think you just need String.Replace in a loop:
public static string Highlitor(string text, IEnumerable<string> replaceStrings)
{
string result = text;
foreach(string repl in replaceStrings.Distinct())
{
string replWith = string.Format("<span class='highlight-text'>{0}</span>", repl);
result = result.Replace(repl, replWith);
}
return result;
}
You don't need Distinct if the list doesn't contain duplicates.
UPDATE: as it seems things are much more complicated. You want to replace parts by preserving the original case when the pattern is part of the final replacement string.
Here is a modified version of my above method that uses an extended version of String.Replace:
public static string Highlitor(string text, IEnumerable<string> replaceStrings)
{
string result = text;
foreach (string repl in replaceStrings.Distinct())
{
string replWith = string.Format("<span class='highlight-text'>{0}</span>", repl);
result = ReplaceCaseInsensitive(result, repl, replWith, true);
}
return result;
}
Here is the method that replaces strings case-insensitively and supports keeping the original case:
public static string ReplaceCaseInsensitive(string original, string pattern, string replacement, bool keepOriginalCase = false)
{
int count, position0, position1;
count = position0 = position1 = 0;
int replacementIndexOfPattern = replacement.IndexOf(pattern, StringComparison.OrdinalIgnoreCase);
if (replacementIndexOfPattern == -1)
keepOriginalCase = false; // not necessary
int inc = (original.Length / pattern.Length) *
(replacement.Length - pattern.Length);
char[] chars = new char[original.Length + Math.Max(0, inc)];
bool[] upperCaseLookup = new bool[pattern.Length];
while ((position1 = original.IndexOf(pattern, position0, StringComparison.OrdinalIgnoreCase)) != -1)
{
// first part that will not be replaced
for (int i = position0; i < position1; ++i)
chars[count++] = original[i];
// remember the case of each letter in the found patter that will be replaced
if (keepOriginalCase)
{
for (int i = 0; i < pattern.Length; ++i)
upperCaseLookup[i] = Char.IsUpper(original[position1 + i]);
}
// The part that will be replaced:
for (int i = 0; i < replacement.Length; ++i)
{
// only keep case of the relevant part of the replacement that contains the part to be replaced
bool lookupCase = keepOriginalCase
&& i >= replacementIndexOfPattern
&& i < replacementIndexOfPattern + pattern.Length;
char newChar = replacement[i];
if (lookupCase)
{
bool wasUpper = upperCaseLookup[i - replacementIndexOfPattern];
bool isUpper = Char.IsUpper(newChar);
if (wasUpper && !isUpper)
newChar = Char.ToUpperInvariant(newChar);
else if (!wasUpper && isUpper)
newChar = Char.ToLowerInvariant(newChar);
}
else
{
newChar = replacement[i];
}
chars[count++] = newChar;
}
position0 = position1 + pattern.Length;
}
if (position0 == 0)
return original;
// the rest
for (int i = position0; i < original.Length; ++i)
chars[count++] = original[i];
return new string(chars, 0, count);
}
It's algorithm based on: Fastest C# Case Insenstive String Replace.
I got the functionality as :
for (var j = 0; j < searchTermArray.Length; j++)
{
CompareInfo ci = CultureInfo.CurrentCulture.CompareInfo;
int indexOfTerm = ci.IndexOf(text, searchTermArray[j], CompareOptions.IgnoreCase);
//dont replace if there is no search term in text
if(indexOfTerm!= -1)
{
string subStringToHighlight = text.Substring(indexOfTerm, searchTermArray[j].Length);
//replacing with span
string replaceWith = string.Format("<span class='highlight-search-text'>{0}</span>", subStringToHighlight);
text = Regex.Replace(text, searchTermArray[j], replaceWith, RegexOptions.IgnoreCase);
}
}
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('');
}