How to transplant the java MD5 encrypt code into Python? -
here standard code java use md5 encryption string,
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: "); (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: "); (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); } }
}
the result follows,
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
so how transplant standard java code python , same result, here code wrote has bugs:
# -*- coding: utf-8 -*- hashlib import md5 def md5digest(text): bytelist = [] 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"))
result follows,
104 101 108 108 111 32 119 111 114 108 100 ['c9e1074f5b3f9fc8ea15d152add07294', '38b3eff8baf56627478ec76a704e9b52', 'a3c65c2974270fd093ee8a9bf8ae7d0b', 'a3c65c2974270fd093ee8a9bf8ae7d0b', '698d51a19d8a121ce581499d7b701668', '6364d3f0f495b6ab9dcf8d3b5c6e0b01', '07e1cd7dca89a1678042477183b7ac3f', '698d51a19d8a121ce581499d7b701668', '5fd0b37cd7dbbb00f97ba6ce92bf5add', 'a3c65c2974270fd093ee8a9bf8ae7d0b', 'f899139df5e1059396431415e770c6dd']
you can see although byte code results seem same, md5 encrypt results totally different.
please me rewrite python code debug, lot. due project reason, solution reference piece of java code in python project not allowed, please understand.
there few issues, first calculate hexdigest instead of digest. second calculate hexdigest inside loop instead of outside. instead should this:
# python 3 hashlib import md5 def md5digest(text): digest = md5(text).digest() print('origin string:', text) print('byte array:', *text) print('md5 result:', *digest) return digest # python 2 hashlib import md5 def md5digest(text): digest = md5(text).digest() print 'origin string:', text print 'byte array:', " ".join(str(ord(c)) c in text) print 'md5 result:', " ".join(str(ord(c)) c in digest) return digest
this outputs
>>> md5digest(b'hello world') origin string: b'hello world' byte array: 104 101 108 108 111 32 119 111 114 108 100 md5 result: 94 182 59 187 224 30 238 208 147 203 34 187 143 90 205 195
the difference signage, remember numbers equal mod 256.
Comments
Post a Comment