假如使用的JDK1.8不支持PKCS7填充方式,需要添加依赖
<dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.64</version>
</dependency>
AESUtils
package com.hm.utils;import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Arrays;
import java.util.Base64;public class AESUtils {private static final String transformation = "AES/CBC/PKCS7Padding";private static final String algorithm = "AES";public static String encrypt(byte[] key, byte[] initVector, String value) {try {IvParameterSpec iv = new IvParameterSpec(initVector);SecretKeySpec skeySpec = new SecretKeySpec(key, algorithm);Cipher cipher = Cipher.getInstance(transformation);cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);byte[] encrypted = cipher.doFinal(value.getBytes());return Base64.getEncoder().encodeToString(encrypted);} catch (Exception ex) {ex.printStackTrace();}return null;}public static String decrypt(String key, String initVector, String encrypted) {try {IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);Cipher cipher = Cipher.getInstance(transformation);cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);byte[] original = cipher.doFinal(Base64.getDecoder().decode(encrypted));return new String(original);} catch (Exception ex) {ex.printStackTrace();}return null;}// 对数据进行PKCS7补位public static byte[] addPKCS7Padding(byte[] keyByte, int blockSize) {int groups = keyByte.length / blockSize + (keyByte.length % blockSize != 0 ? 1 : 0);byte[] temp = new byte[groups * blockSize];Arrays.fill(temp, (byte) 0);System.arraycopy(keyByte, 0, temp, 0, keyByte.length);keyByte = temp;return keyByte;}
}
package com.hm.utils.wms;import com.hm.utils.AESUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.stereotype.Component;import java.nio.charset.StandardCharsets;
import java.security.Security;/*** WMS系统接口对接工具类** @author Xu Wei* @version 1.0* @aate 2024/11/12 10:54*/
@Component
public class WmsUtil {static {Security.addProvider(new BouncyCastleProvider());}public static void main(String[] args) {int client = 1; // 1表示风卡,2表示名家(这里只是模拟,实际应用中可能从其他地方获取这个值)String key = "123";byte[] temp = AESUtils.addPKCS7Padding(key.getBytes(), 32);String iv = "1234567890abcdef";String data = "data数据";System.out.println(AESUtils.encrypt(temp, iv.getBytes(StandardCharsets.UTF_8), data));}}