Decode in JavaScript encoded Base64 value in PHP - javascript

I'm trying to decrypt "window.btoa" in PHP, please see my PHP code in below.
<script>
var url = "?url=";
var input = 'some text';
var encrypt = window.btoa( input );
var link = "www.domain.com/"+url+encrypt;
</script>
My Link generated as below
www.domain.com/?url=c29tZSB0ZXh0
PHP code in below
<?php
$testURL = $_GET['url'];
echo $testURL;
?>
Please guide me how to decrypt this value.

The Javascript btoa function will encode your string to base-64. To decode the result in PHP use the base64_decode function;
<?php
echo base64_decode('c29tZSB0ZXh0');
?>
Will print;
some text

btoa is not encryption, it is encoding, it is Base64 encoding badly named: Base64 uses the "A-Z", "a-z", "0-9", "+", "/" and "=" characters to encode the string.
See Window btoa() Method, first hit on Google for "window.btoa".
Using Base64 -> hexadecimal string decoder c29tZSB0ZXh0 is decoded to hex: 736F6D652074657874 and text: some text.

Related

Decode JavaScript btoa() encoded string using Java/Kotlin Base64 decoder

I have an encoded string as follows:
S0VEQUkgUlVOQ0lUIFZSSU5FIEVOVEVSUFJJU0UgLSBLRyBTSU1QQU5HIDQgU09PSw
This was encoded using JavaScript btoa() function. This string can be correctly decoded using JavaScript atob() function. It should give the following decoded string :
KEDAI RUNCIT VRINE ENTERPRISE - KG SIMPANG 4 SOOK
Right now I'm developing Android app and I have to decode this string, I'm using the following to decode :
java.util.Base64.getDecoder().decode(encodedstring).toString();
I'm not getting the correct decoded output. Anyone knows what's the problem ? Is it even possible to decode using Java ?
decode(String) returns a byte[], you need to convert that to a string using a String constructor and not the toString() method:
byte[] bytes = java.util.Base64.getDecoder().decode(encodedstring);
String s = new String(bytes, java.nio.charset.StandardCharsets.UTF_8);
It looks like you need mime decoder message
java.util.Base64.Decoder decoder = java.util.Base64.getMimeDecoder();
// Decoding MIME encoded message
String dStr = new String(decoder.decode(encodedstring));
System.out.println("Decoded message: "+dStr);

How to decode utf8 data into simple string in php

I am facing issue while decoding a utf8 string into simple string which is i am getting from android. String contains both words and emoji's.
For Example:
I am storing this type of data in mysql db \u263A\uD83D\uDE22\uD83D\uDC4D\uD83D\uDE0A\uD83D\uDE0A\uD83D\uDC90. But fail to decode in readable format.
If you treat it as JSON object, it will work:
<?php
$input = '{"key":"\u263A\uD83D\uDE22\uD83D\uDC4D\uD83D\uDE0A\uD83D\uDE0A\uD83D\uDC90"}';
$output = json_decode($input, true);
print $output["key"];
Output:
β˜ΊπŸ˜’πŸ‘πŸ˜ŠπŸ˜ŠπŸ’
In javascript you can use decodeURIComponent for that, like this:
function decode(s) {
return decodeURIComponent(escape(s));
}

Base64 decode in javascript and encode in php

I am facing a major issue in encoding/decoding a base 64 image.
My purpose is to save a canvas image as base64 decoded string that can later be base64 encoded in php.
I have the javascript code as follows:
var string= canvas.toDataURL("image/jpeg");
var abc = window.atob(string.split(",")[1]);
var blob = "HEADERS"+abc;
blob is the file.
PHP code:
$Data = blob File
$img = substr($Data, $start, $end);
$img = base64_encode($img);
I start when I find chr(0xFF) . chr(0xD8) in the blob file and end when I find chr(0xFF) . chr(0xD9)
These characters are not found when I decode through javascript but easily gets found when using base64_decode of php. There is a problem of encoding type I think and I'm a novice in the encoding methods. so kindly help.

How to convert Encoded url into JSON format?

Here I want to convert my encoded url into JSON format. The encoded url is:
http://localhost:63342/AngularJs/services/e_cell.html#!/%7B%22book%22:%22ABC%22%7D
As much as I understand from your URL you are trying to post this %7B%22book%22:%22ABC%22%7D data in query string.
So first you need to decode your URL encoded data into an string which can be parsed. For that you can take help of decodeURIComponent() javascript API.
decodeURIComponent() - this function decodes an encoded URI component back to the plain text i.e. like in your encoded text it will convert %7B into opening brace {. So once we apply this API you get -
//output : Object { book: "ABC" }
This is a valid JSON string now you can simply parse. So what all you need to do is -
var formData = "%7B%22book%22:%22ABC%22%7D";
var decodedData = decodeURIComponent(formData);
var jsonObject = JSON.parse(decodedData);
console.log(jsonObject );
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string
The decodeURIComponent function will convert URL encoded characters back to plain text.
var myJSON = decodeURIComponent("%7B%22book%22:%22ABC%22%7D");
var myObject = JSON.parse(myJSON);

Sending "windows-1251"-encoded string in JSON from python to javascript

What I need to do is best descriped as example.
Previously, I had the following code:
content = u'<?xml version="1.0" encoding="windows-1251"?>\n' + ... #
with open(file_name, 'w') as f:
f.write(content.encode('cp1251'))
f.close;
Now I want to modify the architecture of my entire app and send the string which is supposed to be the file content to client via JSON and to generate the file via javascript.
So, now my code looks something like this:
response_data = {}
response_data['file_content'] = content.encode('cp1251')
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)}) # error generated
The problem is that I get UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 53: ordinal not in range(128)
I also tried the second option this way:
response_data = {}
response_data['file_content'] = content
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False).encode('utf8')}) # error generated
Then, on client, I try to covert utf8 to windows-1251.
$.post ('/my_url/', data, function(response) {
var file_content = JSON.parse(response.content).file_content;
file_content = UnicodeToWin1251(file_content);
...but...I get distorted symbols.
I know I am doing something terribly wrong here and am likely to mess up things with encoding, but still it's been an entire day I couldn't solve this issue. Could someone give a hint where my mistake is ?
Both XML and JSON contain data that is Unicode text. The XML declaration merely tells your XML parser how to decode the XML serialisation of that data. You wrote the serialisation by hand so to match the XML header, you had to encode to CP-1251.
The JSON standard states that all JSON should be encoded in either UTF-8, UTF-16 or UTF-32, with UTF-8 the standard; again, this is just the encoding for the serialisation.
Leave your data as Unicode, then encode that data to JSON with the json library; the library takes care of ensuring you get UTF-8 data (in Python 2), or gives you Unicode text (Python 3) that can be encoded to UTF-8 later. Your Javascript code will then decode the JSON again at which point you have Unicode text again:
response_data = {}
response_data['file_content'] = content
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)})
There is no need whatsoever to send binary data over JSON here, you are sending text. If you Javascript code then generates the file, it is responsible for encoding to CP-1251, not your Python code.
If you must put binary data in a JSON payload, you'll need to encode that payload to some form of text. Binary data (and CP-1251-encoded text is binary data) could be encoded in text as Base-64:
import base64
response_data = {}
response_data['file_content'] = base64.encodestring(content.encode('cp1251')).decode('ascii')
response_data['file_name'] = file_name
return JsonResponse({'content':json.dumps(response_data, ensure_ascii=False)})
Base64 data is encoded to a bytestring containing only ASCII data, so decode it as ASCII for the JSON library, which expects text to be Unicode text.
Now you are sending binary data, wrapped in a Base64 text encoding, to the Javascript client, which now has to decode the Base64 if you need the binary payload there.

Categories

Resources