AES加密解密工具

好久木有来更新了,最近木有在偷懒,最近在自我修炼node与vue,打算修炼成一个既正宗又地道的前端,但是最近经常听到数据安全及加密解密相关的讨论,下面来记录和分享下加密解密的工具:

以下是用AES方式加密解密的工具类:

package com.ying.util;

import java.io.ByteArrayOutputStream;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * description:加密解密工具
 * @author wxy_jdhk
 */
public class AesUtil {
	protected static final Logger logger = LoggerFactory.getLogger(AesUtil.class);
	private static final String AES_KEY_ALGORITHM = "AES";
	private static final String AES_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
	
	/**
     * description: 加密
     * @param buff 密钥
     * @param data 数据
     * @return byte[] 加密后的数据
     */
	public byte[] aesEncrypt(byte[] key,byte[] data) throws SecurityException {
		ByteArrayOutputStream baos = null;
		try {
			if (null==key) {
				throw new SecurityException("AES key is null");
			}
			SecretKey secureKey = new SecretKeySpec(key,AES_KEY_ALGORITHM);
	        Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
	        cipher.init(Cipher.ENCRYPT_MODE, secureKey);
	        return cipher.doFinal(data);
		} catch(SecurityException e) {
			throw new SecurityException(e.getMessage());
		} catch(Exception e) {
			e.printStackTrace();
			logger.error("encrypt error");
		}
		return null;
	}
	/**
     * description: 解密
     * @param buff 密钥
     * @param data 数据
     * @return byte[] 解密后的数据
     */
	public byte[] aesDecrypt(byte[] key,byte[] data) throws SecurityException {
		ByteArrayOutputStream baos = null;
		try {
			if (null==key) {
				throw new SecurityException("aes key is null");
			}
			SecretKey secureKey = new SecretKeySpec(key,AES_KEY_ALGORITHM);
			Cipher cipher = Cipher.getInstance(AES_CIPHER_ALGORITHM);
	        cipher.init(Cipher.DECRYPT_MODE, secureKey);
	        return cipher.doFinal(data);
		} catch(SecurityException e) {
			throw new SecurityException(e.getMessage());
		} catch(Exception e) {
			e.printStackTrace();
			logger.error("decrypt error");
		}
		return null;
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章