About java3DES encryption and decryption offset code example

 

// 3DES加密
    public static String getEnc3DES(String data, String key, String iv) throws Exception {
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312"));
        IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);
        cipher.init(Cipher.ENCRYPT_MODE, securekey, ivs);
        BASE64Encoder base64Encoder = new BASE64Encoder();
        return base64Encoder.encode(cipher.doFinal(data.getBytes("GB2312")));
    }

 

// 3DES解密
    public static String getDes3DES(String data, String key, String iv) throws Exception {
        BASE64Decoder base64Decoder = new BASE64Decoder();
        byte[] databyte = base64Decoder.decodeBuffer(data);
        Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
        DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("gb2312"));
        IvParameterSpec ivs = new IvParameterSpec(iv.getBytes("gb2312"));
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        SecretKey securekey = keyFactory.generateSecret(dks);
        cipher.init(Cipher.DECRYPT_MODE, securekey, ivs);
        return new String(cipher.doFinal(databyte), "GB2312");
    }
    

 

  Note: The KEY value is generated according to your needs. The IV offset can also be generated by yourself, here is just an example. The parameter data passed in is of json type or other. When it is passed in, it can be used like .toString ().

public static String KEY = "***";
    public static String subStr() throws Exception{
        String exOnceByTime = ExDateUtil.exOnceByTime(ExDateUtil.ExDate());//将2019-04-11 14:33:20 变成格式为20190411143320
        String IV = StringUtils.substring(exOnceByTime, 0, 8);
        return IV;
    }
    //解密数据
    public static JSONObject decode(JSONObject json) throws Exception{
        Object data = json.get("data");
        String des3des = getDes3DES(data.toString(), KEY, subStr());
        return JSONObject.fromObject(des3des);
    }

Guess you like

Origin www.cnblogs.com/divingCat/p/12699560.html