import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;
/**
* @author alderaan
*/
public class AES32CBCNoPadding {
public static byte[] IV="0000000000000000".getBytes();
public static final String KEY_ALGORITHM = "AES";
public static final String CIPHER_ALGORITHM_CBC = "AES/CBC/NoPadding";
public static byte[] encrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
int blockSize = cipher.getBlockSize();
int length = data.length;
// 计算需填充长度
if (length % blockSize != 0) {
length = length + (blockSize - (length % blockSize));
}
byte[] plaintext = new byte[length];
// 拷贝数据
System.arraycopy(data, 0, plaintext, 0, data.length);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(autoKey(key), KEY_ALGORITHM), new IvParameterSpec(IV));
return cipher.doFinal(plaintext);
}
public static byte[] decrypt(byte[] data, byte[] key) throws Exception {
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM_CBC);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(autoKey(key), KEY_ALGORITHM), new IvParameterSpec(IV));
return cipher.doFinal(data);
}
private static byte[] autoKey(byte[] key){
byte[] bytes = new byte[32];
for (int i =0;i<32;i++){
bytes[i]=0;
}
if (key.length>=32){
System.arraycopy(key,0,bytes,0,32);
}else {
System.arraycopy(key,0,bytes,0,key.length);
}
return bytes;
}
public static String randomKey(int len){
StringBuilder stringBuilder = new StringBuilder();
Random random = new Random();
for (int i =0;i<len;i++){
stringBuilder.append(String.valueOf((char)(random.nextInt(94)+32)));
}
return stringBuilder.toString();
}
public static void main(String[] argv){
// 随机一个key 长度指定为3
String key = randomKey(3);
try {
// 对字符串123进行加密
byte[] temp = encrypt("plaintext...".getBytes(),key.getBytes());
// 解密并输出解密后的结果
System.out.println(new String(decrypt(temp,key.getBytes())));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Java AES-256-CBC ZeroPadding
最新推荐文章于 2024-07-31 04:24:05 发布