AES 对称加密

直接上代码

import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class MyAES {

    static String  charset = "UTF-8";
    //秘钥种子。
    static String pass = "kaskldfjas@#$%^&*(sdfszdf";

    public static void main(String[] age) throws Exception {
        String data = "我是秘密数据";

        Key key = generatorKey(pass,charset);

        System.out.println(key.getEncoded());
        System.out.println("加密前 "+data);
        //加密,这里已经得到了加密的二进制数据了,剩下的可以自行处理了,
        byte[] encode = encode(data.getBytes(charset),key);

        //为了方便保存和展示:这里我将得到的二进制加密数据 用base64来处理
        String encode64 = Base64.getEncoder().encodeToString(encode);
        System.out.println("加密后 "+encode64);

        //这里将 base64位数据还原成 二进制数组,再去解密
        byte[] encodes = Base64.getDecoder().decode(encode64);

        Key key1 = generatorKey(pass,charset);
        //解密
        byte[] decode = decode(encodes,key1);
        System.out.println("解密后 "+new String(decode,charset));
    }

    //解密
    private static byte[] decode(byte[] data, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE,key);
        return cipher.doFinal(data);
    }

    //加密
    private static byte[] encode(byte[] data, Key key) throws Exception {
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE,key);
        return cipher.doFinal(data);
    }

    //生成 AES秘钥 key
    public  static Key  generatorKey(String pass,String charset) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        // 随机生成秘钥,(在非对称加密和对称加密混合使用时,会使用到)
        //keyGenerator.init(128,new SecureRandom());
        // 初始化秘钥。128, 指定 秘钥种子生成秘钥。
        keyGenerator.init(128,new SecureRandom(pass.getBytes(charset)));
        SecretKey secretKey = keyGenerator.generateKey();
        //这是生成后的二进制秘钥。(可以转换成 base64保存。)
        byte[] keys = secretKey.getEncoded();
        //key转换
        Key key = new SecretKeySpec(keys, "AES");
        return key;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值