AES文件加解密工具类
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.util.Arrays;
@Slf4j
public class AESUtil {
public static final String KEY = "password";
private static final String ENCODE = "UTF-8";
private static Cipher initAESCipher(String passsword, int cipherMode) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
Cipher cipher = null;
SecretKey key = getKey(passsword);
cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
cipher.init(cipherMode, key);
return cipher;
}
private static SecretKey getKey(String password) {
int keyLength = 256;
byte[] keyBytes = new byte[keyLength / 8];
SecretKeySpec key = null;
try {
Arrays.fill(keyBytes, (byte) 0x0);
Security.addProvider(new BouncyCastleProvider());
byte[] passwordBytes = password.getBytes(ENCODE);
int length = passwordBytes.length < keyBytes.length ? passwordBytes.length : keyBytes.length;
System.arraycopy(passwordBytes, 0, keyBytes, 0, length);
key = new SecretKeySpec(keyBytes, "AES");
} catch (UnsupportedEncodingException e) {
log.error("AES获取key失败!");
e.printStackTrace();
}
return key;
}
public static String encryptString(String jsonString, String skey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
skey = KEY;
Cipher cipher = initAESCipher(skey, Cipher.ENCRYPT_MODE);
try {
byte[] byteContent = jsonString.getBytes(ENCODE);
byte[] result = cipher.doFinal(byteContent);
String res = Base64.encodeBase64String(result);
return res;
} catch (UnsupportedEncodingException e) {
log.error("AES-encryptString()编码异常!");
e.printStackTrace();
} catch (BadPaddingException e) {
log.error("AES-encryptString()错误的填充异常!");
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
log.error("AES-encryptString()非法块大小异常!");
e.printStackTrace();
}
return null;
}
public static boolean encryptFile(String encryptPath, String decryptPath, String sKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
sKey = KEY;
long start = System.currentTimeMillis();
File encryptFile = null;
File decryptfile = null;
CipherOutputStream cipherOutputStream = null;
BufferedInputStream bufferedInputStream = null;
try {
encryptFile = new File(encryptPath);
if (!encryptFile.exists()) {
throw new NullPointerException("Encrypt file is empty");
}
decryptfile = new File(decryptPath);
if (decryptfile.exists()) {
decryptfile.delete();
}
decryptfile.createNewFile();
Cipher cipher = initAESCipher(sKey, Cipher.ENCRYPT_MODE);
cipherOutputStream = new CipherOutputStream(new FileOutputStream(decryptfile), cipher);
bufferedInputStream = new BufferedInputStream(new FileInputStream(encryptFile));
byte[] buffer = new byte[1024 * 1024 * 5];
int bufferLength;
while ((bufferLength = bufferedInputStream.read(buffer)) != -1) {
cipherOutputStream.write(buffer, 0, bufferLength);
}
bufferedInputStream.close();
cipherOutputStream.close();
} catch (IOException e) {
delFile(decryptfile.getAbsolutePath());
log.error("AES加密IO异常");
return false;
}
long endTime = System.currentTimeMillis();
log.info("加密时间:" + (endTime - start) + "ms");
return true;
}
public static String decryptString(String decryptString, String mkey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, BadPaddingException, IllegalBlockSizeException {
mkey = KEY;
Cipher cipher = initAESCipher(mkey, Cipher.DECRYPT_MODE);
byte[] result = cipher.doFinal(Base64.decodeBase64(decryptString));
String res = new String(result, ENCODE);
return res;
}
public static String decryptFile2String(File encryptFile, String mKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
mKey = KEY;
long start = System.currentTimeMillis();
BufferedOutputStream outputStream = null;
CipherInputStream inputStream = null;
String res = "";
try {
if (!encryptFile.exists()) {
log.error("找不到该文件!");
throw new NullPointerException("Decrypt file is empty");
}
Cipher cipher = initAESCipher(mKey, Cipher.DECRYPT_MODE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
inputStream = new CipherInputStream(new FileInputStream(encryptFile), cipher);
int bufferLength;
byte[] buffer = new byte[1024 * 1024 * 5];
while ((bufferLength = inputStream.read(buffer)) != -1) {
baos.write(buffer, 0, bufferLength);
}
res = new String(baos.toByteArray());
inputStream.close();
baos.close();
} catch (IOException e) {
log.error("文件解密失败" + e + e.getMessage());
return res;
}
long endTime = System.currentTimeMillis();
System.out.println("解密时间:" + (endTime - start) + "ms");
return res;
}
public static boolean decryptFile(String encryptPath, String decryptPath, String mKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException {
mKey = KEY;
long start = System.currentTimeMillis();
File encryptFile = null;
File decryptFile = null;
BufferedOutputStream outputStream = null;
CipherInputStream inputStream = null;
try {
encryptFile = new File(encryptPath);
if (!encryptFile.exists()) {
throw new NullPointerException("Decrypt file is empty");
}
decryptFile = new File(decryptPath);
if (decryptFile.exists()) {
decryptFile.delete();
}
decryptFile.createNewFile();
Cipher cipher = initAESCipher(mKey, Cipher.DECRYPT_MODE);
outputStream = new BufferedOutputStream(new FileOutputStream(decryptFile));
inputStream = new CipherInputStream(new FileInputStream(encryptFile), cipher);
int bufferLength;
byte[] buffer = new byte[1024 * 1024 * 5];
while ((bufferLength = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bufferLength);
}
inputStream.close();
outputStream.close();
} catch (IOException e) {
delFile(decryptFile.getAbsolutePath());
log.error("文件解密失败" + e + e.getMessage());
return false;
}
long endTime = System.currentTimeMillis();
System.out.println("解密时间:" + (endTime - start) + "ms");
return true;
}
public static boolean delFile(String pathFile) {
boolean flag = false;
if (pathFile == null && pathFile.length() <= 0) {
throw new NullPointerException("文件不能为空");
} else {
File file = new File(pathFile);
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
}
return flag;
}
public static InputStream encryptFile(InputStream inputStream, String key) throws IOException {
key = KEY;
long start = System.currentTimeMillis();
try {
Cipher cipher = null;
try {
cipher = initAESCipher(key, Cipher.DECRYPT_MODE);
inputStream = new CipherInputStream(inputStream, cipher);
long endTime = System.currentTimeMillis();
System.out.println("解密时间:" + (endTime - start) + "ms");
return inputStream;
} catch (NoSuchPaddingException e) {
log.error("文件解密失败" + e + e.getMessage());
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
log.error("文件解密失败" + e + e.getMessage());
e.printStackTrace();
}
} catch (InvalidKeyException e) {
log.error("文件解密失败" + e + e.getMessage());
e.printStackTrace();
}
return null;
}
}