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); } }}
原文地址:https://www.cnblogs.com/jakin3130/p/10755040.html
时间: 2024-10-06 02:52:12