[Java] TripleDES + CBC + PKCS7 加密&解密代码

January 9, 2019 奇怪的代码

找了好久也没有,这是多个修改得来的
使用了其他的base64的类,建议自己修改。

private String ALGO = "DESede";
private String ALGO_MODE = "DESede/CBC/PKCS7Padding";
public String decrypt(String encryptedData, String akey, String aiv) {
    try {
        byte[] encrypted1 = Base64.decode(encryptedData);
        byte[] iv = aiv.getBytes("utf-8");
        Cipher cipher = Cipher.getInstance(ALGO_MODE);
        SecretKeySpec keyspec = new SecretKeySpec(akey.getBytes("utf-8"), ALGO);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keyspec, ivspec);
        byte[] original = cipher.doFinal(encrypted1);
        String originalString = new String(original);
        return originalString.trim();
    } catch (Exception e) {
        return "";
    }
}

public String encrypt(String Data, String akey, String aiv){
    try {
        byte[] iv = aiv.getBytes("utf-8");
        Cipher cipher = Cipher.getInstance(ALGO_MODE);
        SecretKeySpec keyspec = new SecretKeySpec(akey.getBytes("utf-8"), ALGO);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, keyspec, ivspec);
        byte[] encrypted = cipher.doFinal(Data.getBytes("utf-8"));
        String EncStr = Base64.encode(encrypted);
        return EncStr;
    } catch (Exception e) {
        return "";
    }
}

使用方法

String str = "String!";
String Enkey = "key";
String Eniv = "iv";
String encrypted = this.encrypt(str, Enkey, Eniv);
String decrypted = this.decrypt(encrypted, Enkey, Eniv);

添加新评论