converting ANSI to UTF-8 in Java - javascript

I have a string in JSON format. There are character like \u0025 and I need to convert them to the actual character to which they refer.
is there any direct way in Java by which I can convert these character to the actual ones?
something like myString.convertToUTF-8();
I am making call to Graph API and I get the response in JSON format. I wanted to use a JSON parser or JavaScript parser to parse the JSON and take the values. That's all I need.
I used console of Google Chrome and when I assigned the response to a variable. it gives me an error which tells Uncaught SyntaxError: Unexpected identifier(ā€¦).
In JavScript I wanted to use JSON.parse(jsonString). But I cannot assign the value to jsonString in fact.
For converting these character in Java I already have tried following lines which does not change the string at all!
String responseFromFB = http.sendRequest(url);
byte[] b = responseFromFB.getBytes();
String str= new String(b, "UTF-8");
and here is the sendRequest() function which I have!
private String httpReq(String URL, String QueryString) throws Exception
{
String url = URL;
String urlParameters = QueryString;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept-Charset", "UTF-8");
con.setRequestProperty("Content-Type", "application/json; charset=utf-8");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}

All I needed was to write
JSONObject jsonResponse = new JSONObject(responseFromFB);
String decodedResponseFromFB = jsonResponse.toString();

Related

try to generating signature using HMACSHA512 in c#

signature in c# using HMACSHA512 not equivalent to java and JavaScript.
after tracing my c# code i found the key is not used during generating signature.
using System.Security.Cryptography;
using System.Text;
string privateKey = "OPAYPRV16388855997950.6319778282304234";
string message = "{\r\n \"country\": \"EG\",\r\n \"reference\": \"9cf357a79ffc4cb5a57cd0489a1a4bfa\"\r\n}";
byte[] messagebyte = Encoding.Default.GetBytes(message);
byte[] pkey = Encoding.Default.GetBytes(privateKey);
HMACSHA512 hMACSHA512 = new HMACSHA512(pkey);
//hMACSHA512.Key = pkey; //other way and not give right signature
//hmacsha512.Initialize();
var hmac = hMACSHA512.ComputeHash(messagebyte);
var hmacres = BitConverter.ToString(hmac).Replace("-", "");
Console.WriteLine(hmacres);
// signature c# =FC96AABB47DE439A78CB98943BA3E9F9C25B24264E1431CC4180348F5B48C869F9003E3B67B8E387D25A7189093ACDD90205A103A489856379971EBE07E295E5
// signature in java and JavaScript (the same and the right signature)=
20c8b06951a7907b48db0ccb0b1fb514e8addb2b7c72786cc21316576d57e57560188cac837ffe232a9b24e65e73c6c05e6a5dddff3cc03e26521c92e74e064d
HMACSHA512 deal with \r\n and spaces as characters, when remove /r/n and space I got the right signature
message= message.Replace(System.Environment.NewLine, string.Empty).Replace(" ", "");
byte[] messagebyte = Encoding.Default.GetBytes(message);
byte[] pkey = Encoding.Default.GetBytes(privateKey);
HMACSHA512 hMACSHA512 = new HMACSHA512(pkey);
var hmac = hMACSHA512.ComputeHash(messagebyte);
var hmacres = BitConverter.ToString(hmac).Replace("-", "");

Confused on how to implement HMACSHA1 in C# .NET coming from javascript

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&timestamp=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&timestamp=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&timestamp=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;
}

unable to get the value of decoded base64 data in node

this value was encoded to base64
{
a: "008078888658936",
b: "REA"
}
and was decoded using this code
var mytokenvalue = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ=="
let decoded = Buffer.from(token, 'base64')
meanwhile, when I try to get the decoded value
console.log(decoded.a)
I am getting undefined in my console.
Please help
You may need to return the decoded value as a string with .toString().
let token = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ==";
let decoded = Buffer.from(token, 'base64').toString();
console.log(decoded);
You could do:
var token = "ewphOiAiMDA4MDc4ODg4NjU4OTM2IiwKYjogIlJFQSIKfQ==";
eval('var decoded = ' + Buffer.from(token, 'base64').toString());
console.log(decoded.a);
But eval is extremely dangerous if the base64-encoded string can come from somewhere that is outside your control. An arbitrary string could expand to some unexpected JavaScript that would cause eval to do something that would make your program misbehave or breach security.
It would be better to express the original object as a JSON string (use JSON.stringify to do that) and base64-encode that string. Then you can use JSON.parse to reconstruct the original object without taking on the risk of using eval. Like this:
var obj = { x: "foo", y: 123 };
var obj_json = JSON.stringify(obj);
// obj_json is '{"x":"foo","y":123}'
var obj_b64 = Buffer(obj_json).toString('base64');
// obj_b64 is 'eyJ4IjoiZm9vIiwieSI6MTIzfQ=='
var decoded = JSON.parse(Buffer.from(obj_b64, 'base64').toString());
console.log(decoded.x);

Generate Base64 MD5 hash of byte array

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.

Decompressing string (from gzcompress) returns wrong result when special chars are involved

I'm trying to write a front end application in js and I am getting my data (Iā¤U\nšŸ˜˜šŸ˜˜šŸ˜˜) from a webserver.
jsFiddle https://jsfiddle.net/czmovg26/1/
Webserver:
<?php
print($compressed = base64_encode(gzcompress('I\u2764U\n\uD83D\uDE18\uD83D\uDE18\uD83D\uDE18', 6)));
?>
Frontend:
var b64Data = "eJzzjCk1MjczCY3Jiyl1sTB2AZKuhha42ABGUQ2i"; // === Iā¤U\nšŸ˜˜šŸ˜˜šŸ˜˜
// Decode base64 (convert ascii to binary)
var strData = atob(b64Data);
// Convert binary string to character-number array
var charData = strData.split('').map(function (x) {
return x.charCodeAt(0);
});
// Turn number array into byte-array
var binData = new Uint8Array(charData);
// Pako magic
var data = pako.inflate(binData);
// Convert gunzipped byteArray back to ascii string:
var decoded = String.fromCharCode.apply(null, new Uint8Array(data));
var r = /\\u([\d\w]{4})/gi;
decoded = decoded.replace(r, function(match, grp) {
return String.fromCharCode(parseInt(grp, 16));
});
decoded = unescape(decoded);
Now, the string looks the same when you print it in the console, but
console.log(decoded == "Iā¤U\nšŸ˜˜šŸ˜˜šŸ˜˜");
resturns false, and things like
var val = decoded.replace(RegExp("\n","g"), "<br>");
do not work.
The decompression must be the problem, as it works fine with a normal string, but I don't understand, what's wrong with the decompression.
In JavaScript a string literal with \n in it denotes a new line, if you were to log such a string to the console you would see it split along multiple lines.
If you take a look at the log of the decoded string you'd notice its on a single line.
This means your original string did not have a new line in it.
From your php you can see that very clearly. In php the escape slash only escapes the single quote in a single quoted php string, so for \n to represent a newline it has to be within a double quoted string.
<?php
print($compressed = base64_encode(gzcompress("I\u2764U\n\uD83D\uDE18\uD83D\uDE18\uD83D\uDE18", 6)));

Categories

Resources