DES加解密

public class TestDES {
    public static void main(String[] args) throws Exception {

//        DES des = new DES();
//        byte[] encrypt = des.encrypt("2309X0415704");
//        String encryptedText1 = Base64.getEncoder().encodeToString(encrypt);
//        System.out.println("Encrypted Text1: " + encryptedText1);

//        byte[] decode = Base64.getDecoder().decode("U1N+Nxr/DkuN+S2WAOzKZQ==");
//        String decryptedText = des.decryptStr(decode);
//        System.out.println("decryptedText: " + decryptedText);
//        byte[] decrypt = des.decrypt("+4QqFJkfTN5wlZSRcOBOrw==");
//        String s = Arrays.toString(decrypt);
//        System.out.println(s);

        String plainText = "Hello World";
        String key = "dispatch"; // 密钥长度必须是8个字符

        byte[] encryptedBytes = encrypt(plainText, key);
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted Text: " + encryptedText);

        byte[] decode = Base64.getDecoder().decode(encryptedText);
        String decryptedText = decrypt(decode, key);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    public static byte[] encrypt(String plainText, String key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DES");

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

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

    public static String decrypt(byte[] encryptedBytes, String key) throws Exception {
        SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DES");

        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);

        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }
}

你可能感兴趣的:(java)