加解密工具類

不好意思之前的工具類寫錯了
package com.utils.password;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.log4j.Logger;
import org.apache.tomcat.util.buf.HexUtils;

import com.google.common.base.Strings;
import com.utils.stringsutils.FormatUtil;

/**
 * The Class EncryptUtils.
 */
public class EncryptUtils {

	/**
	 * The Class AsymmetricEncryptionUtil.
	 */
	public static class AsymmetricEncryptionUtil {

		private final static int DEFAULT_KEY_SIZE = 1024;
		private final static String DEFAULT_ASYMETRIC_ENCRYPTION_ALGORITHM = "RSA";

		/**
		 * 生成祕鑰對.
		 *
		 * @param provider
		 *            the provider
		 * @param algorithm
		 *            the algorithm
		 * @param keysize
		 *            the keysize
		 */
		@SuppressWarnings("restriction")
		public static void generateKey(Provider provider, String algorithm, int keysize) {
			if (provider == null) {
				provider = new com.sun.crypto.provider.SunJCE();
			}
			if (Strings.isNullOrEmpty(algorithm)) {
				algorithm = DEFAULT_ASYMETRIC_ENCRYPTION_ALGORITHM;
			}
			if (keysize <= 0) {
				keysize = DEFAULT_KEY_SIZE;
			}
			try {
				Security.addProvider(provider);
				final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
				keyPairGenerator.initialize(keysize);
				final KeyPair keyPair = keyPairGenerator.generateKeyPair();
				final PublicKey publicKey = keyPair.getPublic();
				final PrivateKey privateKey = keyPair.getPrivate();
				System.out.println(String.format("Public Key:%s\nPrivate Key:%s",
						HexUtils.toHexString(publicKey.getEncoded()), HexUtils.toHexString(privateKey.getEncoded())));
			} catch (final NoSuchAlgorithmException e) {
				final String message = FormatUtil.Error.formatError(EncryptUtils.AsymmetricEncryptionUtil.class,
						"generateKey");
				EncryptUtils.LOGGER.error(message, e);
			}
		}
	}

	/**
	 * 對稱加密的工具類.
	 */
	public static class SymmetricEncryptionUtil {
		private final static String DEFAULT_SYMMETRIC_ENCRYPTION_ALGORITHM = "DES";

		/**
		 * 生成祕鑰 如果provider爲空則默認使用com.sun.crypto.provider.SunJCE() 如果algorithm爲空默認使用"DES"
		 *
		 * @param provider
		 *            the provider
		 * @param algorithm
		 *            the algorithm
		 */
		@SuppressWarnings("restriction")
		public static void generateKey(Provider provider, String algorithm) {
			try {
				// 如果provider爲空值則使用默認的provider
				if (provider == null) {
					provider = new com.sun.crypto.provider.SunJCE();
				}
				if (algorithm == null) {
					algorithm = DEFAULT_SYMMETRIC_ENCRYPTION_ALGORITHM;
				}
				Security.addProvider(provider);
				final KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
				final SecretKey secretKey = keyGenerator.generateKey();
				System.out.println(String.format("Secret Key:%s", HexUtils.toHexString(secretKey.getEncoded())));

			} catch (final Exception e) {
				final String message = FormatUtil.Error.formatError(EncryptUtils.SymmetricEncryptionUtil.class,
						"generateKey");
				EncryptUtils.LOGGER.error(message, e);
			}
		}
	}

	/** The Constant LOGGER. */
	private static final Logger LOGGER = Logger.getLogger(EncryptUtils.class);

	/**
	 * Decrypt.
	 *
	 * @param buff
	 *            the buff
	 * @param algorithm
	 *            the algorithm
	 * @param keyBytes
	 *            the key bytes
	 * @return the byte[]
	 */
	public static byte[] decrypt(final byte[] buff, final String algorithm, final byte[] keyBytes) {
		if (buff == null) {
			throw new NullPointerException("buff");
		}
		if (algorithm == null) {
			throw new NullPointerException("algorithm");
		}
		if (keyBytes == null) {
			throw new NullPointerException("keyBytes");
		}
		try {
			final SecretKey secretKey = new SecretKeySpec(keyBytes, algorithm);
			final Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.DECRYPT_MODE, secretKey);
			final byte[] result = cipher.doFinal(buff);
			return result;
		} catch (final Exception e) {
			final String message = FormatUtil.Error.formatError(EncryptUtils.SymmetricEncryptionUtil.class, "encrypt");
			EncryptUtils.LOGGER.error(message, e);
		}
		return null;
	}

	/**
	 * Encrypt.
	 *
	 * @param buff
	 *            the bytes
	 * @param algorithm
	 *            the algorithm
	 * @param keyBytes
	 *            the key bytes
	 * @return the byte[]
	 */
	public static byte[] encrypt(final byte[] buff, final String algorithm, final byte[] keyBytes) {
		if (buff == null) {
			throw new NullPointerException("buff");
		}
		if (algorithm == null) {
			throw new NullPointerException("algorithm");
		}
		if (keyBytes == null) {
			throw new NullPointerException("keyBytes");
		}
		try {
			final SecretKey secretKey = new SecretKeySpec(keyBytes, algorithm);
			final Cipher cipher = Cipher.getInstance(algorithm);
			cipher.init(Cipher.ENCRYPT_MODE, secretKey);
			final byte[] result = cipher.doFinal(buff);
			return result;
		} catch (final Exception e) {
			final String message = FormatUtil.Error.formatError(EncryptUtils.SymmetricEncryptionUtil.class, "encrypt");
			EncryptUtils.LOGGER.error(message, e);
		}
		return null;
	}
}


發佈了44 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章