温馨提示×

Java Document如何加密和解密

小樊
83
2024-06-14 13:32:03
栏目: 编程语言

在Java中可以使用javax.crypto包提供的API来加密和解密数据。下面是一个简单的示例代码来演示如何使用Java进行加密和解密:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;

public class EncryptionUtils {

    private static final String KEY = "0123456789abcdef";

    public static String encrypt(String plainText) throws Exception {
        SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
        return DatatypeConverter.printBase64Binary(encryptedBytes);
    }

    public static String decrypt(String encryptedText) throws Exception {
        SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] encryptedBytes = DatatypeConverter.parseBase64Binary(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, "UTF-8");
    }

    public static void main(String[] args) {
        try {
            String originalText = "Hello, World!";
            System.out.println("Original Text: " + originalText);

            String encryptedText = encrypt(originalText);
            System.out.println("Encrypted Text: " + encryptedText);

            String decryptedText = decrypt(encryptedText);
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这个示例中,我们使用AES算法对数据进行加密和解密。需要注意的是,加密和解密时使用的密钥(KEY)必须是相同的。你也可以使用其他加密算法和模式来进行加密和解密操作,具体使用哪种算法和模式取决于你的需求。

0