Base 64 encoding, Java or JavaScript?
i've a particular js function that encrypts some form inputs into base64, but I need to run it in my Java app. So my question is, how can i call that function inside a java class? Otherwise I'll have to translate it but I think will be more complicated. Here's some of js code:
function e开发者_如何转开发ncode64(input)
{
//alert(input);
//alert(input);
input = escape(input);
var output = "";
var chr1, chr2, chr3 = "";
var enc1, enc2, enc3, enc4 = "";
var i = 0;
var nMod =( input.length) % 3;
//alert(nMod);
//alert(input.length);
do
{
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = (((chr1 << 4) | (chr2 >> 4))& 0x3f);
enc3 = (((chr2 << 2) | (chr3 >> 6))& 0x3f);
enc4 = chr3 & 0x3f;
output = output +
keyStr.charAt(enc1) +
keyStr.charAt(enc2) +
keyStr.charAt(enc3) +
keyStr.charAt(enc4);
chr1 = chr2 = chr3 = "";
enc1 = enc2 = enc3 = enc4 = "";
} while (i < input.length);
if(nMod == 1)
{
chr1 = input.charCodeAt(i++);
enc1 = ((chr1 & 192)>>2);
enc2 = ((chr1 & 3) <<4);
enc3 = "=";
enc4 = "=";
output = output + keyStr.charAt(enc1)
+ keyStr.charAt(enc2)
+ keyStr.charAt(enc3)
+ keyStr.charAt(enc4);
}
if(nMod == 2)
{
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
enc1 = ((chr1 & 192)>>2);
enc2 = ((chr1 & 3) << 4 )|((chr2 & 0xf0) >> 4);
enc3 = ((chr2 & 15) <<2);
enc4 = "=";
output = output + keyStr.charAt(enc1)
+ keyStr.charAt(enc2)
+ keyStr.charAt(enc3)
+ keyStr.charAt(enc4);
}
return output;
}
Thanks so much!
but I think will be more complicated.
Why would it be more complicated? You can perfectly do that in Java. If your actual problem is already the first line
input = escape(input);
then it's good to know that the Java equivalent is the URLEncoder#encode()
. As to the remnant of the coding, it's ultimately straightforward. Just replace var
by String
or char
here and there, align the methods according java.lang.String
API and you'll be fine.
Edit: for some downvoting nitpickers out here: I did NOT say that URLEncoder#encode()
does the Base64 encoding. It just does URL encoding the same way as Javascript's escape()
function does. That was just the first line of his to-be-translated Javascript code. Please read answers, do not scan answers.
Or better use commons-codec 's Base64 class
P.S. You do not "encrypt" into Base64 - you "encode"
You could do that using a javascript engine written in Java, but I think it's better to simply translate it into java.
I have used http://iharder.sourceforge.net/current/java/base64/ and it works.
Translate the code into Java - it will be quicker. (Or search for an existing example in Java!)
精彩评论