溫馨提示×

java中aes加密的實現方法是什么

小億
112
2024-12-07 09:06:36
欄目: 編程語言

在Java中,可以使用javax.crypto包中的類和方法來實現AES加密。以下是一個簡單的AES加密和解密示例:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class AesEncryptionExample {

    public static void main(String[] args) throws Exception {
        String originalText = "Hello, World!";
        String encryptedText = encrypt(originalText, "AES");
        String decryptedText = decrypt(encryptedText, "AES");

        System.out.println("Original Text: " + originalText);
        System.out.println("Encrypted Text: " + encryptedText);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    public static String encrypt(String plainText, String algorithm) throws Exception {
        SecretKey secretKey = generateSecretKey(algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String encryptedText, String algorithm) throws Exception {
        SecretKey secretKey = generateSecretKey(algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decodedBytes = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedBytes = cipher.doFinal(decodedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static SecretKey generateSecretKey(String algorithm) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        keyGenerator.init(128); // 128-bit key size
        return keyGenerator.generateKey();
    }
}

這個示例中,我們首先使用KeyGenerator生成一個AES密鑰,然后使用Cipher類進行加密和解密操作。注意,我們需要對原始文本和加密后的文本進行Base64編碼,以便在輸出時更容易查看。

在實際應用中,你可能需要將密鑰存儲在一個安全的地方,而不是每次都生成一個新的密鑰。你可以使用SecretKeySpec類來加載一個已存儲的密鑰。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女