2
下面是標準的代碼,java的使用做了MD5加密的字符串,如何將Java MD5加密代碼移植到Python中?
import java.security.MessageDigest;
public class TransCode{
public static byte[] transcode(String text) throws Exception{
byte[] bytes = text.getBytes("UTF-8");
return bytes;
}
public static void main(String[] args){
try{
System.out.println("ORIGIN STRING: hello world");
byte[] byteArray = TransCode.transcode("hello world");
int arrLen = byteArray.length;
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(byteArray);
System.out.print("BYTE ARRAY: ");
for (int i=0;i<arrLen;i++){
System.out.print(byteArray[i]);
System.out.print(" ");
}
System.out.println();
byteArray = messageDigest.digest();
System.out.print("MD5 RESULT: ");
for (int i=0;i<arrLen;i++){
System.out.print(byteArray[i]);
System.out.print(" ");
}
System.out.print("\n");
}
catch(Exception ex){
System.out.println(ex);
}
}
}
結果如下,
ORIGIN STRING: hello world
BYTE ARRAY: 104 101 108 108 111 32 119 111 114 108 100
MD5 RESULT: 94 -74 59 -69 -32 30 -18 -48 -109 -53 34
所以如何移植這個標準Java代碼到python中,並得到相同的結果,這裏是我寫的代碼有bug:
# -*- coding: utf-8 -*-
from hashlib import md5
def MD5Digest(text):
byteList = []
for item in text:
md=md5()
unit = str(ord(item))
print unit,
md.update(unit)
byteList.append(md.hexdigest())
print
return byteList
print MD5Digest(u"hello world".encode("UTF8"))
結果如下,
104 101 108 108 111 32 119 111 114 108 100
['c9e1074f5b3f9fc8ea15d152add07294', '38b3eff8baf56627478ec76a704e9b52', 'a3c65c2974270fd093ee8a9bf8ae7d0b', 'a3c65c2974270fd093ee8a9bf8ae7d0b', '698d51a19d8a121ce581499d7b701668', '6364d3f0f495b6ab9dcf8d3b5c6e0b01', '07e1cd7dca89a1678042477183b7ac3f', '698d51a19d8a121ce581499d7b701668', '5fd0b37cd7dbbb00f97ba6ce92bf5add', 'a3c65c2974270fd093ee8a9bf8ae7d0b', 'f899139df5e1059396431415e770c6dd']
你可以看到雖然字節碼結果似乎是相同的,MD5的加密結果是完全不同的。
請幫助我重寫我的python代碼進行調試,非常感謝。 由於項目原因,在我的python項目中引用這段java代碼的解決方案實際上是不允許的,請理解。
爲什麼'byteList.append( md.hexdigest())'在循環中,當它不在你的Java代碼中? – immibis