记一个加密算法 java 3DES (DESede/ECB/PKCS5Padding) 加解密

对接一个接口,需要用到DESede/ECB/PKCS5Padding 进行加密,

刚开始以为很牛逼...

上代码

private static  Cipher DES_CIPHER;
    static {
        try {
            DES_CIPHER = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
    //key的长度要24位  DES是8 这里的3DES 所以 长度=3*8=24
    public static String encrypt3DES(String str, String key) {
        try {
            DES_CIPHER.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes("utf-8"), "DESede"));
            byte[] encryptedData = DES_CIPHER.doFinal(encryptString.getBytes("utf-8"));
            //转化为字符串
            String hexData = Hex.encodeHexString(encryptedData).toUpperCase();
            return StringUtils.leftPad(String.valueOf(hexData.length()), 6, '0') + hexData;
        } catch (Throwable e) {
            throw Throwables.propagate(e);
        }
    }

    public static String decrypt3DES(String str, String key) {
        try {
            DES_CIPHER.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes("utf-8"), "DESede"));
            byte[] decryptedData = DES_CIPHER.doFinal(Hex.decodeHex(decryptString.substring(6).toCharArray()));
            return new String(decryptedData, "utf-8");
        } catch (Throwable e) {
            throw Throwables.propagate(e);
        }
    }

 

你可能感兴趣的:(日常)