温馨提示×

java中aes加密的实现方法是什么

小亿
89
2024-12-07 09:06:36
栏目: 编程语言
Java开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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类来加载一个已存储的密钥。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:java中链表的实现方法是什么

0