日期:2014-05-20  浏览次数:20847 次

在JAVA中怎么用 MessageDigest实现MD5的加密?
比如说 我有一个String pwd="123" 想用MD5对他进行加密

代码怎么写

请详细说下原理

------解决方案--------------------
Java code
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MessageDigestUtil {
    
    public static void main(String[] args) {
        String txt = "123";
        byte[] bys = digest(txt.getBytes(), MessageDigestType.MD5);
        System.out.println(ByteUtil.bytes2Hex(bys));
    }    
    
    private static byte[] digest(byte[] bys, MessageDigestType type) {
        if(bys == null || bys.length == 0 || type == null) {
            throw new IllegalArgumentException("argument is invalid!");
        }
        MessageDigest m = null;
        try {
            m = MessageDigest.getInstance(type.getAlgorithms());
        } catch (NoSuchAlgorithmException e) {
        }
        m.update(bys);
        return m.digest();
    }   
}

class MessageDigestType {

    private String algorithms;
    
    private MessageDigestType(String algorithms) {
        this.algorithms = algorithms;
    }
    
    public final static MessageDigestType MD2 = new MessageDigestType("MD2");
    public final static MessageDigestType MD5 = new MessageDigestType("MD5");
    public final static MessageDigestType SHA1 = new MessageDigestType("SHA-1");
    public final static MessageDigestType SHA256 = new MessageDigestType("SHA-256");
    public final static MessageDigestType SHA384 = new MessageDigestType("SHA-384");
    public final static MessageDigestType SHA512 = new MessageDigestType("SHA-512");
    
    public String getAlgorithms() {
        return algorithms;
    }
}

class ByteUtil {
    private final static char[] HEX = "0123456789abcdef".toCharArray();
    
    /**
     * 将字节数组转成 16 进制的字符串来表示,每个字节采用两个字符表表示
     * 
     * @param bys       需要转换成 16 进制的字节数组
     * @return
     */
    public static String bytes2Hex(byte[] bys) {
        char[] chs = new char[bys.length * 2];
        for(int i = 0, offset = 0; i < bys.length; i++) {
            chs[offset++] = HEX[bys[i] >> 4 & 0xf];
            chs[offset++] = HEX[bys[i] & 0xf];
        }
        return new String(chs);
    }
}