
AES加密解密流程
補(bǔ)齊方式采用的是:不足16字節(jié),補(bǔ)齊內(nèi)容為差值(比如數(shù)據(jù)是10個(gè)字節(jié),補(bǔ)齊的內(nèi)容就是6)。
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* AES加密解密工具
*
* @author yangle
*/
public class AESUtils {
/**
* AES加密
*
* @param data
* 將要加密的內(nèi)容
* @param key
* 密鑰
* @return 已經(jīng)加密的內(nèi)容
*/
public static byte[] encrypt(byte[] data, byte[] key) {
//不足16字節(jié),補(bǔ)齊內(nèi)容為差值
int len = 16 - data.length % 16;
for (int i = 0; i < len; i++) {
byte[] bytes = { (byte) len };
data = ArrayUtils.concat(data, bytes);
}
try {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
}
return new byte[] {};
}
/**
* AES解密
*
* @param data
* 將要解密的內(nèi)容
* @param key
* 密鑰
* @return 已經(jīng)解密的內(nèi)容
*/
public static byte[] decrypt(byte[] data, byte[] key) {
data = ArrayUtils.noPadding(data, -1);
try {
SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decryptData = cipher.doFinal(data);
int len = 2 + ByteUtils.byteToInt(decryptData[4]) + 3;
return ArrayUtils.noPadding(decryptData, len);
} catch (Exception e) {
e.printStackTrace();
}
return new byte[] {};
}
}
合并數(shù)組與去除補(bǔ)齊工具
/**
* 數(shù)組工具
*
* @author yangle
*/
public class ArrayUtils {
/**
* 合并數(shù)組
*
* @param firstArray
* 第一個(gè)數(shù)組
* @param secondArray
* 第二個(gè)數(shù)組
* @return 合并后的數(shù)組
*/
public static byte[] concat(byte[] firstArray, byte[] secondArray) {
if (firstArray == null || secondArray == null) {
return null;
}
byte[] bytes = new byte[firstArray.length + secondArray.length];
System.arraycopy(firstArray, 0, bytes, 0, firstArray.length);
System.arraycopy(secondArray, 0, bytes, firstArray.length,
secondArray.length);
return bytes;
}
/**
* 去除數(shù)組中的補(bǔ)齊
*
* @param paddingBytes
* 源數(shù)組
* @param dataLength
* 去除補(bǔ)齊后的數(shù)據(jù)長(zhǎng)度
* @return 去除補(bǔ)齊后的數(shù)組
*/
public static byte[] noPadding(byte[] paddingBytes, int dataLength) {
if (paddingBytes == null) {
return null;
}
byte[] noPaddingBytes = null;
if (dataLength > 0) {
if (paddingBytes.length > dataLength) {
noPaddingBytes = new byte[dataLength];
System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, dataLength);
} else {
noPaddingBytes = paddingBytes;
}
} else {
int index = paddingIndex(paddingBytes);
if (index > 0) {
noPaddingBytes = new byte[index];
System.arraycopy(paddingBytes, 0, noPaddingBytes, 0, index);
}
}
return noPaddingBytes;
}
/**
* 獲取補(bǔ)齊的位置
*
* @param paddingBytes
* 源數(shù)組
* @return 補(bǔ)齊的位置
*/
private static int paddingIndex(byte[] paddingBytes) {
for (int i = paddingBytes.length - 1; i >= 0; i--) {
if (paddingBytes[i] != 0) {
return i + 1;
}
}
return -1;
}
}