3DES加解密

public static void main(String[] args) throws Exception {
    String content = "";
    String plainText = "";
    String key = "";
    //加密
    byte[] encryptedBytes = encrypt(plainText, key);
    String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
    System.out.println("Encrypted Text: " + encryptedText);

    //解密 这里注意不能直接content去转byte要先Base64解码
    byte[] source = Base64.getDecoder().decode(content.getBytes(StandardCharsets.UTF_8));
    String decryptedText = decrypt(source, key);
    System.out.println("Decrypted Text: " + decryptedText);

}

//解密
public static String decrypt(byte[] encryptedBytes, String key) throws Exception {
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
    DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
    SecretKey secretKey = keyFactory.generateSecret(spec);
       //PKCS5Padding 和 PKCS7Padding 都可以用PKCS5Padding
    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secretKey);

    byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
    return new String(decryptedBytes, StandardCharsets.UTF_8);


}

//加密
public static byte[] encrypt(String plainText, String key) throws Exception {
    byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
    DESedeKeySpec spec = new DESedeKeySpec(keyBytes);
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
    SecretKey secretKey = keyFactory.generateSecret(spec);

    Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);

    return cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
}


//将url参数转换成map
public static Map getUrlParams(String param) {
    Map map = new HashMap(0);
    if (StringUtil.isEmpty(param)) {
        return map;
    }
    String[] params = param.split("&");
    for (int i = 0; i < params.length; i++) {
        String[] p = params[i].split("=");
        if (p.length == 2) {
            map.put(p[0], p[1]);
        }
    }
    return map;
}

3DES加解密_第1张图片

你可能感兴趣的:(java,jvm,开发语言)