android md5 加密字符串
转载至
注意转载原作者的代码是有误的private static String toMd5(byte[] bytes) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(bytes); return toHexString(algorithm.digest(), ""); } catch (NoSuchAlgorithmException e) { Log.v("he--------------------------------ji", "toMd5(): " + e); throw new RuntimeException(e); // 05-20 09:42:13.697: ERROR/hjhjh(256): // 5d5c87e61211ab7a4847f7408f48ac } } private static String toHexString(byte[] bytes, String separator) { StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { hexString.append(Integer.toHexString(0xFF & b)).append(separator); } return hexString.toString(); }很不幸的是,原作者的md5算法是有误的。在与python作md5对称的时候,发现有时候会少一位(31),在网上查找到的资料stackoverflow正确的
private static String toMd5(byte[] bytes) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(bytes); return toHexString(algorithm.digest(), ""); } catch (NoSuchAlgorithmException e) { Log.v("he--------------------------------ji", "toMd5(): " + e); throw new RuntimeException(e); // 05-20 09:42:13.697: ERROR/hjhjh(256): // 5d5c87e61211ab7a4847f7408f48ac } } private static String toHexString(byte[] bytes, String separator) { StringBuilder hexString = new StringBuilder(); for (byte b : bytes) { String hex = Integer.toHexString(0xFF & b); if(hex.length()==1){ hexString.append('0'); } hexString.append(hex).append(separator); } return hexString.toString(); }