对称加密

对称加密常用的几种:DES,AES,3DES等

对称加密应用场景
1.本地数据加密(sp)
2.网络传输(post请求username=li,psw=jsdcaaosiiJDJJ(对密码进行了加密))
3.加密用户登入结果信并序列化到本地磁盘
4.网页交互数据加密

/**
 * 生成秘钥并保存到硬盘上,之后读取该秘钥进行加密解密操作
 */
public class SymmetricalEncryption {
    public static void main(String[] args) throws Exception {
        //生成秘钥,并将其保存到硬盘上
        //generateKey();

        //从磁盘上读取key对象
        Key key = readKey();
        encrypt(key);
    }

    public static void generateKey() throws IOException, NoSuchAlgorithmException {
        //随机生成秘钥
        SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
        //序列化
        /*FileOutputStream fos = new FileOutputStream(new File("heima.key"));
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(secretKey);*/
        SerializableUtil.saveObject(secretKey, "heima.key");
    }

    public static Key readKey() throws ClassNotFoundException, IOException {
        //反序列化
        /*FileInputStream fis = new FileInputStream(new File("heima.key"));
        ObjectInputStream ois = new ObjectInputStream(fis);
        Key key = (Key) ois.readObject();
        return key;*/
        return (Key) SerializableUtil.readObject("heima.key");
    }

    public static void encrypt(Key key) throws Exception {
        String content = "黑马程序员";
        Cipher cipher = Cipher.getInstance("AES");
        //加密
        cipher.init(Cipher.ENCRYPT_MODE, key);
        //分批处理
        /*cipher.update("黑马".getBytes());
        cipher.update("程序员".getBytes());
        byte[] result = cipher.doFinal();*/
        //一次性处理
        byte[] result = cipher.doFinal(content.getBytes());
        System.out.println("加密: " + new String(result));

        //解密
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptResult = cipher.doFinal(result);
        System.out.println("解密: " + new String(decryptResult));
        System.out.println(cipher.getProvider().getInfo());
    }
}

public class SerializableUtil {
    //序列化
    public static void saveObject(Object obj, String path) throws IOException{
        FileOutputStream fos = new FileOutputStream(new File(path));
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(obj);
        oos.close();
    }

    //反序列化
    public static Object readObject(String path) throws IOException, ClassNotFoundException {
        FileInputStream fis = new FileInputStream(new File(path));
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object obj = ois.readObject();
        ois.close();

        return obj;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值