java怎么實(shí)現(xiàn)des加密解密

小億
163
2023-11-21 16:36:24

Java 中可以使用 javax.crypto 包來(lái)實(shí)現(xiàn) DES 加密和解密。

下面是一個(gè)例子,展示了如何用 DES 加密和解密字符串:

import javax.crypto.*;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class DESExample {

    public static void main(String[] args) {
        String originalText = "Hello, World!";
        String secretKey = "SecretKey";

        try {
            // 創(chuàng)建一個(gè) DES 密鑰
            SecretKey key = generateKey(secretKey);

            // 加密字符串
            String encryptedText = encrypt(originalText, key);
            System.out.println("Encrypted Text: " + encryptedText);

            // 解密字符串
            String decryptedText = decrypt(encryptedText, key);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 生成一個(gè) DES 密鑰
    private static SecretKey generateKey(String secretKey) throws NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
        DESKeySpec desKeySpec = new DESKeySpec(secretKey.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        return keyFactory.generateSecret(desKeySpec);
    }

    // 使用給定的密鑰加密字符串
    private static String encrypt(String text, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes());
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    // 使用給定的密鑰解密字符串
    private static String decrypt(String encryptedText, SecretKey key) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        return new String(decryptedBytes);
    }
}

此代碼會(huì)輸出以下結(jié)果:

Encrypted Text: 2vqyQ/J1sIc=
Decrypted Text: Hello, World!

請(qǐng)注意,上述代碼只是一個(gè)示例,并沒(méi)有處理加密和解密的異常情況。在實(shí)際使用中,建議處理可能的異常情況,以保證代碼的健壯性。

0