【发布时间】:2011-05-24 12:59:59
【问题描述】:
我有这个自定义函数来计算 MD5 哈希,用 Java 编写。我无法改变它。我需要将它翻译成 JavaScript 才能在客户端使用它。我自己尝试过,但无法使用 JavaScript 数据类型(尤其是 Java char[])进行管理...感谢任何帮助,谢谢!
// codes array
char[] codes = new char[64];
// initialise
private void initCodes(){
codes = new char[64];
codes[0] = '$';
int count = 0;
for (char i='0';i<='9';i++){ count++; codes[count] = i; }
for (char i='A';i<='Z';i++){ count++; codes[count] = i; }
for (char i='a';i<='z';i++){ count++; codes[count] = i; }
codes[63] = '£';
}
// custom MD5 algorithm
public String customMD5(String source) {
initCodes();
byte[] buf = new byte[source.length()];
buf = source.getBytes();
MessageDigest algorithm = null;
try {
algorithm = MessageDigest.getInstance("MD5");
} catch(NoSuchAlgorithmException e){}
algorithm.reset();
algorithm.update(buf);
byte[] digest = algorithm.digest();
int len = digest.length;
char[] encrypted = new char[len];
for (int i=0;i<len;i++)
encrypted[i] = codes[(int)(Math.floor((double)((digest[i]+128)/4)))];
return new String(encrypted);
}
【问题讨论】:
-
如果你在 google 上输入:"md5 javascript" 有很多现有的库
-
但可能没有此 custom MD5 的库
-
已经给出了解决方案,但是你不应该命名这个 custom MD5 - 它不是一个自定义的 MD5(没有这样的东西 - 如果它是自定义的,它是没有MD5),它只是MD5的自定义编码。
标签: java javascript md5 porting