AES加密,CBC模式,0填充

Posted jakin3130

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AES加密,CBC模式,0填充相关的知识,希望对你有一定的参考价值。

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填充的主要内容,如果未能解决你的问题,请参考以下文章

小程序:JS AES加密解密(ECB/CBC)

AES共有ECB,CBC,CFB,OFB,CTR五种模式分别有啥区别

AES共有ECB,CBC,CFB,OFB,CTR五种模式分别有啥区别

AES在线加密解密-附AES128,192,256,CBC,CFB,ECB,OFB,PCBC各种加密解密源码

nodejs中aes-128-cbc加密和解密

分组对称加密模式:ECB/CBC/CFB/OFB(转)