Java實現密碼、檔案MD5加密,密碼sha256、sha384、sha512Hex等加密

業餘草發表於2019-03-05

Java實現密碼、檔案MD5加密,密碼sha256、sha384、sha512Hex等加密!

使用時請先匯入 commons-codec-1.12.jar 包。pom.xml 檔案如下:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.12</version>
</dependency>

使用方法如下所示:

package com.xttblog.test.utils;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Base64OutputStream;
import org.apache.commons.codec.digest.DigestUtils;
/**
 * 類說明:密碼的加密與解密
 * @author 作者: www.xttblog.com
 * @version 建立時間:2019-03-05 上午11:07:09
 */
public class PasswordEncode {
	public final static String MD5 = "MD5";
	public final static String NONE = "NONE";
	public final static String SHA_256 = "SHA-256";
	public final static String SHA_512 = "SHA-512";
	public final static String SHA_384 = "SHA-384";
	/**
	 * 加密檔案演算法
	 * @param filename
	 *            需要加密的檔名
	 * @param algorithm
	 *            加密演算法名
	 */
	public static void digestFile(String filename, String algorithm) {
		byte[] b = new byte[1024 * 4];
		int len = 0;
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
			MessageDigest md = MessageDigest.getInstance(algorithm);
			fis = new FileInputStream(filename);
			while ((len = fis.read(b)) != -1) {
				md.update(b, 0, len);
			}
			byte[] digest = md.digest();
			StringBuffer fileNameBuffer = new StringBuffer(128).append(filename).append(".").append(algorithm);
			fos = new FileOutputStream(fileNameBuffer.toString());
			OutputStream encodedStream = new Base64OutputStream(fos);
			encodedStream.write(digest);
			encodedStream.flush();
			encodedStream.close();
		} catch (Exception e) {
			System.out.println("Error computing Digest: " + e);
		} finally {
			try {
				if (fis != null)
					fis.close();
			} catch (Exception ignored) {
			}
			try {
				if (fos != null)
					fos.close();
			} catch (Exception ignored) {
			}
		}
	}
 
	/**
	 * 加密密碼演算法
	 * @param pass
	 *            需要加密的原始密碼
	 * @param algorithm
	 *            加密演算法名稱
	 * @return 加密後的密碼
	 * @throws NoSuchAlgorithmException
	 *             當加密演算法不可用時丟擲此異常
	 */
	public static String digestString(String password, String alg) throws NoSuchAlgorithmException {
		String newPass;
		if (alg == null || MD5.equals(alg)) {
			newPass = DigestUtils.md5Hex(password);
		} else if (NONE.equals(alg)) {
			newPass = password;
		} else if (SHA_256.equals(alg)) {
			newPass = DigestUtils.sha256Hex(password);
		} else if (SHA_384.equals(alg)) {
			newPass = DigestUtils.sha384Hex(password);
		} else if (SHA_512.equals(alg)) {
			newPass = DigestUtils.sha512Hex(password);
		} else {
			newPass = DigestUtils.shaHex(password);
		}
		return newPass;
	}
 
	/**
	 * 加密密碼演算法,預設的加密演算法是MD5
	 * @param password
	 *            未加密的密碼
	 * @return String 加密後的密碼
	 */
	public static String digestPassword(String password) {
		try {
			if (password != null && !"".equals(password)) {
				return digestString(password, MD5);
			} else
				return null;
		} catch (NoSuchAlgorithmException nsae) {
			throw new RuntimeException("Security error: " + nsae);
		}
	}
 
	/**
	 * 判斷密碼是不是相等,預設的加密演算法是MD5
	 * @param beforePwd
	 *            要判斷的密碼
	 * @param afterPwd
	 *            加密後的資料庫密碼
	 * @return Boolean true 密碼相等
	 */
	public static boolean isPasswordEnable(String beforePwd, String afterPwd) {
		if (beforePwd != null && !"".equals(beforePwd)) {
			String password = digestPassword(beforePwd);
			return afterPwd.equals(password);
		} else
			return false;
	}
 
	public static void main(String[] args) throws NoSuchAlgorithmException {
		System.out.println(PasswordEncode.digestPassword("123456"));
		System.out.println(PasswordEncode.digestString("123456", PasswordEncode.MD5));
		PasswordEncode.digestFile("C:\\Users\\user\\Desktop\\PasswordEncode.java", PasswordEncode.SHA_512);
		System.out.println(PasswordEncode.isPasswordEnable("123456", PasswordEncode.digestPassword("123456")));
	}
}

640

相關文章