加密工具类,包含MD5,BASE64,SHA,CRC32的加密与解密方法。
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
/**
* 加密工具类,包含MD5,BASE64,SHA,CRC32
*
*/
public class CryptoUtils {
private static final String DEFAULT_CHARSET = "UTF-8";
/**
* MD5加密
*
* @param bytes
* an array of byte.
* @return a {@link java.lang.String} object.
*/
public static String encodeMD5(final byte[] bytes) {
return DigestUtils.md5Hex(bytes);
}
/**
* MD5加密,默认UTF-8
*
* @param str
* a {@link java.lang.String} object.
* @return a {@link java.lang.String} object.
*/
public static String encodeMD5(final String str) {
return encodeMD5(str, DEFAULT_CHARSET);
}
/**
* MD5加密
*
* @param str
* a {@link java.lang.String} object.
* @param charset
* a {@link java.lang.String} object.
* @return a {@link java.lang.String} object.
*/
public static String encodeMD5(final String str, final String charset) {
if (str == null) {
return null;
}
try {
byte[] bytes = str.getBytes(charset);
return encodeMD5(bytes);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
/**
* SHA加密
*
* @param bytes
* an array of byte.
* @return a {@link java.lang.String} object.
*/
public static String encodeSHA(final byte[] bytes) {