Java to JavaScript (Encryption related)
I'm having difficulties to get the same string in Javascript and I'm thinking that I'm doing something wrong...
Java code:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.GregorianCalendar;
import sun.misc.BASE64Encoder;
private static String getBase64Code(String input) throws
UnsupportedEncodingException, NoSuchAlgorithmException {
String base64 = "";
开发者_C百科 byte[] txt = input.getBytes("UTF8");
byte[] text = new byte[txt.length+3];
text[0] = (byte)239;
text[1] = (byte)187;
text[2] = (byte)191;
for(int i=0; i<txt.length; i++)
text[i+3] = txt[i];
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(text);
byte digest[] = md.digest();
BASE64Encoder encoder = new BASE64Encoder();
base64 = encoder.encode(digest);
return base64;
}
I'm trying this using Paul's MD5 script as well Farhadi Base 64 Encode script
but my tests fail completely :(
my code:
function CalculateCredentialsSecret(type, user, pwd) {
var days = days_between(new Date(), new Date(2000, 1, 1));
var str = type.toUpperCase() + user.toUpperCase() + pwd.toUpperCase() + days;
var padding_data = String.fromCharCode(239) +
String.fromCharCode(187) +
String.fromCharCode(191);
var md5 = hex_md5(padding_data + str);
var b64 = base64Encode(md5);
return encodeURIComponent(b64);
}
Does anyone know how can I convert this Java method into a Javascript one?
Thank you
Tests (for today (29-09-2010), 3740 days after January 1st, 2000)
var secret = CalculateCredentialsSecret('AAA', 'BBB', 'CCC');
// secret SHOULD be: S3GYAfGWlmrhuoNsIJF94w==
http://pajhome.org.uk/crypt/md5/ <-- get Md5 function from there (first page on google for 'javascript md5') http://www.webtoolkit.info/javascript-base64.html <-- get base64 en/de code (googled 'javascript base64 encode')
function getBase64Code(input)
{
base64 = "";
txt = input
text = [];
text[0] = (byte)239; // These three lines I am stuck on
text[1] = (byte)187; // These three lines I am stuck on
text[2] = (byte)191; // These three lines I am stuck on
for(int i=0; i<txt.length; i++)
{
text[i+3] = txt[i];
}
digest = hex_md5(text);
base64 = Base64(digest);
return base64;
}
Just realised... if all you want to do is endocde in base64 for transporting the data, look at the second link. may do what you want as it is.
UPDATE:
you should be able to do something like this then, assume those extra bytes could replaced a three characters.
encoded = Base64.encode(hexmd5(padding_data + data));
correct code is
function CalculateCredentialsSecret(type, user, pwd) {
var days = days_between(new Date(), new Date(2000, 1, 1)) + 30;
var str = type.toUpperCase() + user.toUpperCase() + pwd.toUpperCase() + days;
var padding_data = String.fromCharCode(239, 187, 191);
var md5 = rstr_md5(padding_data+str);
var b64 = base64Encode(md5);
return encodeURIComponent(b64);
}
精彩评论