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

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);

Related

Need Equivalent of SHA1 function in python

Please help me convert below JS code to Python.
const di_digest = CryptoJS.SHA1(di_plainTextDigest).toString(CryptoJS.enc.Base64);
di_plainTextDigest is a String.
I tried a few Python methods, but not working. Example
result = hashlib.sha1(di_plainTextDigest.encode())
hexd = result.hexdigest()
hexd_ascii = hexd.encode("ascii")
dig2 = base64.b64encode(hexd_ascii)
dig3 = dig2.decode("ascii")
print(dig3 )
To replicate the functionality of the JavaScript code in Python, you can use the hashlib and base64 modules as you have attempted to do. However, the difference between your Python code and the JavaScript code is in the encoding format used. In the JavaScript code, the di_plainTextDigest is encoded using the Base64 format, whereas in your Python code, you are encoding the SHA1 hash of di_plainTextDigest as a hex string before encoding it in Base64. To replicate the JavaScript code in Python, you can skip the hex encoding step and directly encode the SHA1 hash of di_plainTextDigest in Base64. Here is the Python code that should produce the same result as the JavaScript code:
import hashlib
import base64
di_plainTextDigest = "your plaintext digest"
sha1_hash = hashlib.sha1(di_plainTextDigest.encode())
base64_hash = base64.b64encode(sha1_hash.digest()).decode('ascii')
print(base64_hash)
Note that we are encoding the digest() of the sha1_hash object, instead of its hexdigest(). This is because hexdigest() returns a hex-encoded string, whereas we want to produce a Base64-encoded string. We also use the decode() method to convert the resulting bytes object to a string in ASCII format.

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);

How to encode and decode query string from javascript to servletpage using java?

How to encode and decode query string from javascript to servletpage
Javascript
var page=http://localhost/jsp/index.jsp?pname=jack & sparrow&price=$20&rate=10 - 20%
$('#listContent').load(page);
I got 404 error
var page=http://localhost/jsp/index.jsp?pname=titanic&price=10&rate=12
$('#listContent').load(page);
this one working fine
how to pass if query string contain space and special symbols
how to encode it and how to pass this query string
if it is encoded how to decode in servlet page
My expected output as
String pname=request.getParameter("pname")
String price=request.getParameter("price")
String rate=request.getParameter("rate")
pname=jack & sparrow
price=$20
rate=10 - 20%
On the Javascript side you have to encode it using function encodeURIComponent(yourString)
If you want to decode such string on Java side, you can do it using (for example) new java.net.URI(receivedString).getPath()

Decrypt a string using Base64 decode in angularJS

I am encrypting a token that is sent from JAVA code to Angular using Base64 encryption:
String token = "1345BCHCNB";
Cipher ecipher = Cipher.getInstance("AES");
String mykey = "1234567891234567";
SecretKey key = new SecretKeySpec(mykey.getBytes(), "AES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
byte[] utf8 = token.getBytes("UTF-8");
byte[] enc = ecipher.doFinal(utf8);
String enctoken = Base64.encodeBase64(enc).toString());
Now i want to decrypt it on Angular side. I am not able to figure it out how to convert it back to actual token
Base64 is NOT about encryption, but it is an encoding flavour. You can always, with no key nor anything secret, get the original data.
In Javascript, it is implemented using the functions btoa and atob.
More infos here: http://www.w3schools.com/jsref/met_win_atob.asp
And a related topic: Base64 encoding and decoding in client-side Javascript
For the AES part, you could give a look at this topic: How to decrypt message with CryptoJS AES. I have a working Ruby example

Unable to decode base64 from req.header.authorization

In express I am grabbing the basic auth from:
req.headers.authorization
From that I get back
dXNlcm5hbWU6cGFzc3dvcmQ=
I say "hey that looks like base64". I quickly go to one of those base64 sites and decode it and it turns out to be 'username:password'. So I google how to decode base64 in express 4. I wind up with this code:
console.log(new Buffer(req.headers.authorization.toString(), 'base64').toString('ascii'));
That is returning:
+"qUMI95iAMM]=I
Which is not username:password. I also tried this with the utf8 setting and that did not work either. I also tried this without toString() on the req.headers.authorization. How do I properly decode base64 with expressjs?
In case anyone is as stupid as I am and didn't realize that the string that is returned from req.headers.authorization is the word Basic followed by the base64 encoded string, you must split the string before decoding.
console.log(new Buffer(req.headers.authorization.split(" ")[1], 'base64').toString())
req.headers.authorization returned for me: Basic dXNlcm5hbWU6cGFzc3dvcmQ=. Not just the base64 string.
Using the new Buffer API it is now
console.log(Buffer.from(req.headers.authorization.split(" ")[1], 'base64').toString())
Else you will get deprecated warnings.

Categories

Resources