Java的SHA和MD5加密


import java.security.GeneralSecurityException;
import java.security.MessageDigest;

public class MD5AndSHA {
    /**
     * MD5、SHA加密
     * 
     * @param encryptionType
     *            要加密的类型 (MD5、SHA1、SHA-256、SHA-384、SHA-512)
     * @param s
     *            要加密的数据
     * @return 加密后的数据
     * @throws GeneralSecurityException 
     */
    public final static String MD5_SHA(String encryptionType, String s) throws GeneralSecurityException {
        char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        byte[] strTemp = s.getBytes();
        MessageDigest mdTemp = MessageDigest.getInstance(encryptionType);
        mdTemp.update(strTemp);
        byte[] md = mdTemp.digest();
        int j = md.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }
}

你可能感兴趣的:(java,MD5,sha)