MD5的几种加密算法
·
1. MD5.java:
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { public static String getMD5(String content) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); digest.update(content.getBytes()); return getHashString(digest); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return null; } private static String getHashString(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for (byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } }
2. MD5.java:
import java.security.MessageDigest; //MD5算法加密 public class MD5 { public static String getMD5(String source) { String s = null; //用来将字节转换成 16 进制表示的字符 char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; try{ MessageDigest md = MessageDigest.getInstance( "MD5" ); md.update(source.getBytes()); byte tmp[] = md.digest(); // MD5 的计算结果是一个 128 位的长整数 // 用字节表示就是 16 个字节 char str[] = new char[16 * 2]; // 每个字节用 16 进制表示的话,使用两个字符 ,所以表示成 16 进制需要 32 个字符 int k = 0; for (int i = 0; i < 16; i++) { // 从第一个字节开始,对 MD5 的每一个字节, 转换成 16 进制字符的转换 byte byte0 = tmp[i]; // 取第 i 个字节 str[k++] = hexDigits[byte0 >>> 4 & 0xf]; // 取字节中高 4 位的数字转换,>>> 为逻辑右移,将符号位一起右移 str[k++] = hexDigits[byte0 & 0xf]; // 取字节中低 4 位的数字转换 } s = new String(str); // 换后的结果转换为字符串 } catch(Exception e) { e.printStackTrace(); } return s; } }
3. md5.py
# -*- coding: utf-8 -*- import hashlib def md5(str): m = hashlib.md5() m.update(str) return m.hexdigest()
更多推荐
所有评论(0)