在网上找了大半天资料,终于找到一个可以用的
public static class AES {
// 算法名称
final static String KEY_ALGORITHM = "AES";
// 加解密算法/模式/填充方式
final static String algorithmStr = "AES/CBC/PKCS7Padding";
//
private static Key key;
private static Cipher cipher;
boolean isInited = false;
public static class AES {
// 算法名称
final static String KEY_ALGORITHM = "AES";
// 加解密算法/模式/填充方式
final static String algorithmStr = "AES/CBC/PKCS7Padding";
//
private static Key key;
private static Cipher cipher;
boolean isInited = false;
public static void init(byte[] keyBytes) {
// 如果密钥不足16位,那么就补足. 这个if 中的内容很重要
int base = 16;
if (keyBytes.length % base != 0) {
int groups = keyBytes.length / base + (keyBytes.length % base != 0 ? 1 : 0);
byte[] temp = new byte[groups * base];
Arrays.fill(temp, (byte) 0);
System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
keyBytes = temp;
}
// 初始化
Security.addProvider(new BouncyCastleProvider());
// 转化成JAVA的密钥格式
key = new SecretKeySpec(keyBytes, KEY_ALGORITHM);
try {
// 初始化cipher
cipher = Cipher.getInstance(algorithmStr, "BC");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchPaddingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchProviderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 加密方法
*
* @param content 要加密的字符串
* @param keyBytes 加密密钥
* @return
*/
@SuppressWarnings("restriction")
public static String encrypt(byte[] content, byte[] keyBytes, byte[] iv) {
byte[] encryptedText = null;
init(keyBytes);
try {
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
encryptedText = cipher.doFinal(content);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BASE64Encoder encoder = new sun.misc.BASE64Encoder();
return encoder.encode(encryptedText);
}
/**
* 解密方法
*
* @param encryptedData 要解密的字符串
* @param keyBytes 解密密钥
* @return
*/
public byte[] decrypt(byte[] encryptedData, byte[] keyBytes) {
/*
* byte[] encryptedText = null; init(keyBytes); System.out.println("IV:" + new
* String(iv)); try { cipher.init(Cipher.DECRYPT_MODE, key, new
* IvParameterSpec(iv)); encryptedText = cipher.doFinal(encryptedData); } catch
* (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
* return encryptedText; }
*/
return null;
}
}
原文地址:https://www.cnblogs.com/lilinqi/p/10497405.html