1. 程式人生 > >記一個加密演算法 java 3DES (DESede/ECB/PKCS5Padding) 加解密

記一個加密演算法 java 3DES (DESede/ECB/PKCS5Padding) 加解密

對接一個介面,需要用到DESede/ECB/PKCS5Padding 進行加密,

剛開始以為很牛逼...

上程式碼

private static  Cipher DES_CIPHER;
    static {
        try {
            DES_CIPHER = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
            throw Throwables.propagate(e);
        }
    }
    //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);
        }
    }