java Aes加解密

java中加AES解密的方式比较简单,本示例展示CBC模式AES在java中的加解密

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;

public class AesTest {
    public static final String CBC_CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
    public static final String KEY_ALGORITHM = "AES";

    public static void main(String[] args) throws IOException {
        //key必须是16的倍数,过长会报错,与jre环境local_policy.jar, US_export_policy.jar有关
        SecretKey key = restoreSecretKey("14785236963698521478523696369852");
        byte[] iv = "1236547896325474".getBytes();
        System.out.println(iv.length);
        byte[] encodeBytes = AesCbcEncode("Hello World!".getBytes(), key, iv);
        byte[] decodeBytes = AesCbcDecode(encodeBytes, key, iv);
        System.out.println(new String(decodeBytes));
    }

    /**
     * 还原密钥
     * @param keyWord
     * @return
     */
    public static SecretKey restoreSecretKey(String keyWord) {
        SecretKeySpec key = new SecretKeySpec(keyWord.getBytes(), KEY_ALGORITHM);
        return key;
    }

    public static byte[] AesCbcEncode(byte[] plainText, SecretKey key, byte[] IVParameter) {
        try {
            IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);

            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, key, ivParameterSpec);
            return cipher.doFinal(plainText);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * CBC 解密
     * @param decodedText
     * @param key
     * @param IVParameter
     * @return
     */
    public static byte[] AesCbcDecode(byte[] decodedText, SecretKey key, byte[] IVParameter) {
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IVParameter);
        try {
            Cipher cipher = Cipher.getInstance(CBC_CIPHER_ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key, ivParameterSpec);
            return cipher.doFinal(decodedText);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值