欢迎访问宙启技术站
智能推送

Java函数:如何使用原生Java实现AES加密?

发布时间:2023-09-11 09:12:34

在Java中实现AES加密,你可以使用Java标准库中的javax.crypto包中的相关类和方法。下面是一个简单的示例代码,演示如何使用原生Java实现AES加密:

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

public class AESExample {
    private static final String SECRET_KEY = "AESEncryptionKey";
    private static final String INIT_VECTOR = "RandomInitVector";

    public static String encrypt(String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String encryptedValue) {
        try {
            IvParameterSpec iv = new IvParameterSpec(INIT_VECTOR.getBytes(StandardCharsets.UTF_8));
            SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(StandardCharsets.UTF_8), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

            byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedValue));
            return new String(decrypted);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
        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);
    }
}

在上述示例中,我们使用了一个固定的密钥(SECRET_KEY)和一个初始化向量(INIT_VECTOR)。在实际应用中,为了确保更高的安全性,你可能需要使用安全的密钥管理方案生成和存储密钥。

此外,我们使用AES加密算法、CBC模式和PKCS5填充方式来进行加密和解密。加密时,我们将原始文本转换为字节数组并使用Cipher类的doFinal方法进行加密;解密时,我们对加密后的字节数组进行解密,并使用Base64进行编码和解码以便于在文本中进行传输和存储。

在上述代码中,我们定义了两个函数encrypt和decrypt,分别用于加密和解密字符串。在main函数中,我们演示了如何使用这两个函数进行加密和解密,并输出加密前后的结果。

总结起来,使用原生Java实现AES加密涉及到使用javax.crypto包中的Cipher、SecretKey和IvParameterSpec等类。通过选择合适的加密算法、模式和填充方式,并提供密钥和初始化向量,你可以利用这些类和方法实现AES加密功能。