import com.fuint.fuintApplication; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.transaction.annotation.Transactional; import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; @RunWith(SpringJUnit4ClassRunner.class) //@RunWith(SpringRunner.class) @SpringBootTest(classes = fuintApplication.class) @Transactional public class aes { public String ALGORITHM = "AES"; public static final String TRANSFORMATION = "AES/CBC/PKCS5Padding"; public static final String SECRET_KEY = "0123456789abcdef"; // 16位 public static final String IV = "0123456789abcdef"; // 16位 @Test public void tt() throws Exception { String originalData = "hello 123"; // 加密 String encryptedData = null; try { encryptedData = encrypt(originalData); } catch (Exception e) { e.printStackTrace(); } System.out.println("Encrypted Data: " + encryptedData); // 解密 String decryptedData = decrypt(encryptedData); System.out.println("Decrypted Data: " + decryptedData); } public String encrypt(String data) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec); byte[] encryptedBytes = cipher.doFinal(data.getBytes()); return Base64.getEncoder().encodeToString(encryptedBytes); } public String decrypt(String encryptedData) throws Exception { Cipher cipher = Cipher.getInstance(TRANSFORMATION); SecretKeySpec keySpec = new SecretKeySpec(SECRET_KEY.getBytes(), ALGORITHM); IvParameterSpec ivSpec = new IvParameterSpec(IV.getBytes()); cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec); byte[] decodedBytes = Base64.getDecoder().decode(encryptedData); return new String(cipher.doFinal(decodedBytes)); } }