【无标题】

Utils存放的是工具类,防止系统出现异常
package com.vilicode.Utils;

import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class MyCipher {
    public MyCipher() {
    }

    private Key getKeyt(String str) {
        SecretKey keyt = null;

        try {
            KeyGenerator generator = KeyGenerator.getInstance("DES");
            generator.init(new SecureRandom(str.getBytes()));
            keyt = generator.generateKey();
            generator = null;
        } catch (Exception var4) {
            var4.printStackTrace();
        }

        return keyt;
    }

    private byte[] getEncrypt(byte[] plaintexts, String str) {
        Key key = this.getKeyt(str);
        byte[] ciphertexts = (byte[])null;

        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(1, key);
            ciphertexts = cipher.doFinal(plaintexts);
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            cipher = null;
        }

        return ciphertexts;
    }

    public String encrypt(String plaintext, String str) {
        String ciphertext = "";
        BASE64Encoder base64en = new BASE64Encoder();

        try {
            byte[] plaintexts = plaintext.getBytes("UTF8");
            byte[] ciphers = this.getEncrypt(plaintexts, str);
            ciphertext = base64en.encode(ciphers);
        } catch (Exception var7) {
            var7.printStackTrace();
        }

        return ciphertext;
    }

    private byte[] decrypt(byte[] ciphertexts, String str) {
        Key key = this.getKeyt(str);
        byte[] plaintexts = (byte[])null;

        Cipher cipher;
        try {
            cipher = Cipher.getInstance("DES");
            cipher.init(2, key);
            plaintexts = cipher.doFinal(ciphertexts);
        } catch (Exception var10) {
            System.out.println(var10.getMessage());
        } finally {
            cipher = null;
        }

        return plaintexts;
    }

    public String decrypt(String ciphertext, String str) {
        String plaintext = "";
        BASE64Decoder base64De = new BASE64Decoder();

        try {
            byte[] bytes = base64De.decodeBuffer(ciphertext);
            byte[] ciphers = this.decrypt(bytes, str);
            plaintext = new String(ciphers, "UTF8");
        } catch (Exception var7) {
            System.out.println(var7.getMessage() + " 空指针异常!");
        }

        return plaintext;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值