java 数据传输的加密和解密

    
    public static String CEncrypt(String content, String iv, String key) throws Exception {
        byte[] raw = key.getBytes("utf-8");
        SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec ips = new IvParameterSpec(iv.getBytes("utf-8"));
        cipher.init(1, secretKeySpec, ips);
        byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
        return Base64.getEncoder().encodeToString(encrypted);
    }
    
    public static String CDecrypt(String content, String iv, String key){
        try {
            byte[] raw = key.getBytes("utf-8");
            SecretKeySpec secretKeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec ips = new IvParameterSpec(iv.getBytes("utf-8"));
            cipher.init(2, secretKeySpec, ips);
            byte[] cbcBytes = Base64.getDecoder().decode(content);
            byte[] original = cipher.doFinal(cbcBytes);
            return new String(original, Charset.forName("utf-8"));
        } catch (Exception var9) {
            var9.printStackTrace();
            return null;
        }
    }

 

posted @ 2020-08-27 16:17  凉城  阅读(1242)  评论(0编辑  收藏  举报