好久木有來更新了,最近木有在偷懶,最近在自我修煉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;
}
}