码迷,mamicode.com
首页 > 其他好文 > 详细

AES加密,CBC模式,0填充

时间:2019-04-23 11:06:54      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:time   length   block   secret   模式   ali   tin   encode   padding   

java的aes加密的CBC模式只有NoPadding,PKCS5Padding,PKCS7Padding,因此0填充需要手动更改

public static byte[] encrypt(byte[] data, byte[] iv, byte[] key) {
if(key.length != 16) {
throw new RuntimeException("Invalid AES key length (must be 16 bytes)");
} else {
try {
SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
byte[] enCodeFormat = secretKey.getEncoded();
SecretKeySpec seckey = new SecretKeySpec(enCodeFormat, "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
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);
IvParameterSpec ivSpec = new IvParameterSpec(iv);
cipher.init(1, seckey, ivSpec);
byte[] result = cipher.doFinal(plaintext);
return result;
} catch (Exception var9) {
throw new RuntimeException("encrypt fail!", var9);
}
}
}

AES加密,CBC模式,0填充

标签:time   length   block   secret   模式   ali   tin   encode   padding   

原文地址:https://www.cnblogs.com/jakin3130/p/10755040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!