Java实现AES解密(BC模式+KEY+IV)

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Security;
import org.apache.commons.codec.binary.Base64;

public class AesDecryptExample {
    public static void main(String[] args) {
        Security.addProvider(new BouncyCastleProvider());

        String encryptedText = "l2VI2I0GL1qPA084yTKMYI8awDGGf6qE7NcI3UPgMSsVZPa8+QYjhxk0VgTls6VxXRe8M/XSq5u6cE1cOWLrMevO9ZZlOGuSkFv0FEoV5I016aTYlxraHpvv4eoNLVDg1j622SNYkfclAmqG0SUfOQ=="; // 待解密的密文,请替换为你的密文
        String encryptionKey = "xxx";   // 密钥,请替换为你的密钥
        String iv = "xxx";             //偏移量字符串必须是16位 当模式是CBC的时候必须设置偏移量
        try {
            // 将密文进行 Base64 解码
            byte[] encryptedBytes = Base64.decodeBase64(encryptedText);

            // 设置 AES 密码及密钥长度
            byte[] keyBytes = encryptionKey.getBytes("UTF-8");
            SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

            // 设置加密模式和填充方式
            Cipher cipher = Cipher.getInstance("AES/CBC/ZeroBytePadding", "BC");

            // 设置初始向量
            byte[] ivBytes = iv.getBytes("utf-8");
            IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

            // 进行解密操作
            cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
            byte[] decryptedBytes = cipher.doFinal(encryptedBytes);

            // 将解密结果转为字符串
            String decryptedText = new String(decryptedBytes);

            // 输出解密结果
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception ex) {
            System.out.println("AES decryption failed: " + ex);
        }
    }
}

你可能感兴趣的:(java,安全)