使用AES 128位加解密,加解密模式採用CBC,填充模式採用PKCS5Padding的Java工具方法示例

大稳·杨發表於2024-10-19
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtils {

    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final int KEY_SIZE = 128;

    public static String encrypt(String data, String key, String iv) throws Exception {
        byte[] encrypted = encrypt(data.getBytes("UTF-8"), key.getBytes("UTF-8"), iv.getBytes("UTF-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String data, String key, String iv) throws Exception {
        byte[] decrypted = decrypt(Base64.getDecoder().decode(data), key.getBytes("UTF-8"), iv.getBytes("UTF-8"));
        return new String(decrypted, "UTF-8");
    }

    private static byte[] encrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(data);
    }

    private static byte[] decrypt(byte[] data, byte[] key, byte[] iv) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        return cipher.doFinal(data);
    }

    public static void main(String[] args) throws Exception {
        String data = "Hello, AES encryption!";
        String key = "1234567890123456"; // 16位元組的金鑰
        String iv = "1234567890123456"; // 16位元組的初始化向量

        String encrypted = encrypt(data, key, iv);
        System.out.println("Encrypted: " + encrypted);

        String decrypted = decrypt(encrypted, key, iv);
        System.out.println("Decrypted: " + decrypted);
    }
}

相關文章