首页 > Java > 正文

Java中如何用AES实现数据加密解密

下次还敢
发布: 2025-06-28 22:42:02
原创
531人浏览过

aes加密在java中通过密钥进行数据加密和解密。1. 选择密钥长度时,128位适用于大多数场景,高安全性需求可选192位或256位;2. 处理大文件需分块加密,使用cipher.update()处理数据块,cipher.dofinal()处理剩余数据;3. 密钥管理方式包括keystore、hsm、kms、pbkdf2和ecdh,根据安全需求和预算选择。

Java中如何用AES实现数据加密解密

AES加密解密在Java里其实挺常见的,简单来说,就是用一个密钥把数据变成乱码,然后再用同样的密钥还原回去。用得好的话,能有效保护数据安全。

Java中如何用AES实现数据加密解密

直接上代码,先看怎么用AES加密解密字符串:

Java中如何用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.security.NoSuchAlgorithmException;
import java.util.Base64;

public class AESUtil {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128; // 可以是 128, 192, 或 256

    // 生成密钥
    public static SecretKey generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE);
        return keyGenerator.generateKey();
    }

    // 密钥转为Base64字符串(方便存储和传输)
    public static String secretKeyToBase64(SecretKey secretKey) {
        byte[] encoded = secretKey.getEncoded();
        return Base64.getEncoder().encodeToString(encoded);
    }

    // Base64字符串转回密钥
    public static SecretKey base64ToSecretKey(String base64Key) {
        byte[] decodedKey = Base64.getDecoder().decode(base64Key);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, ALGORITHM);
    }


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

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

    public static void main(String[] args) throws Exception {
        SecretKey secretKey = generateKey();
        String originalString = "This is a secret message!";
        String encryptedString = encrypt(originalString, secretKey);
        String decryptedString = decrypt(encryptedString, secretKey);

        System.out.println("Original String: " + originalString);
        System.out.println("Encrypted String: " + encryptedString);
        System.out.println("Decrypted String: " + decryptedString);

        // 密钥的Base64存储示例
        String base64Key = secretKeyToBase64(secretKey);
        System.out.println("Secret Key (Base64): " + base64Key);
        SecretKey restoredKey = base64ToSecretKey(base64Key);
        System.out.println("Restored Key equals Original Key: " + secretKey.equals(restoredKey));
    }
}
登录后复制

如何选择合适的AES密钥长度?

AES密钥长度通常有128位、192位和256位三种选择。密钥越长,安全性越高,但同时计算复杂度也会增加。128位密钥对于大多数应用来说已经足够安全。 如果你的数据安全性要求非常高,例如需要保护银行交易信息或国家机密,那么可以考虑使用192位或256位密钥。密钥长度的选择需要在安全性和性能之间进行权衡。一般来说,128位密钥是一个不错的折中方案。

立即学习Java免费学习笔记(深入)”;

加密文件时如何处理大文件?

直接把整个大文件读到内存里加密肯定不行,容易OOM。 正确姿势是分块加密。

Java中如何用AES实现数据加密解密
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class AESFileUtil {

    private static final String ALGORITHM = "AES";
    private static final int KEY_SIZE = 128;
    private static final int BUFFER_SIZE = 8192; // 8KB 缓冲区

    public static SecretKey generateKey() throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM);
        keyGenerator.init(KEY_SIZE);
        return keyGenerator.generateKey();
    }

    public static void encryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception {
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outputFile)) {

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                byte[] output = cipher.update(buffer, 0, bytesRead);
                if (output != null) {
                    fos.write(output);
                }
            }
            byte[] outputBytes = cipher.doFinal(); // 处理剩余数据
            if (outputBytes != null) {
                fos.write(outputBytes);
            }
        }
    }

    public static void decryptFile(String inputFile, String outputFile, SecretKey secretKey) throws Exception {
        try (FileInputStream fis = new FileInputStream(inputFile);
             FileOutputStream fos = new FileOutputStream(outputFile)) {

            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);

            byte[] buffer = new byte[BUFFER_SIZE];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                byte[] output = cipher.update(buffer, 0, bytesRead);
                if (output != null) {
                    fos.write(output);
                }
            }
            byte[] outputBytes = cipher.doFinal(); // 处理剩余数据
            if (outputBytes != null) {
                fos.write(outputBytes);
            }
        }
    }


    public static void main(String[] args) throws Exception {
        SecretKey secretKey = generateKey();
        String inputFile = "original.txt"; // 替换成你的输入文件
        String encryptedFile = "encrypted.txt";
        String decryptedFile = "decrypted.txt";

        // 创建一个示例文件
        try (FileOutputStream fos = new FileOutputStream(inputFile)) {
            fos.write("This is a sample file for encryption.".getBytes());
        }

        encryptFile(inputFile, encryptedFile, secretKey);
        System.out.println("File encrypted successfully!");

        decryptFile(encryptedFile, decryptedFile, secretKey);
        System.out.println("File decrypted successfully!");
    }
}
登录后复制

核心在于cipher.update()和cipher.doFinal()这两个方法。update()方法用于处理分块数据,而doFinal()方法用于处理最后一块数据,完成加密或解密过程。

除了直接使用SecretKey,还有没有其他密钥管理方式?

当然有。直接在代码里写死密钥或者简单存储SecretKey是很不安全的。 常见的密钥管理方式包括:

  • 使用密钥库(KeyStore): Java提供了KeyStore类来安全地存储密钥和证书。你可以将密钥存储在KeyStore中,并使用密码保护它。
  • 使用硬件安全模块(HSM): HSM是一种专门用于存储和管理密钥的硬件设备。HSM提供了更高的安全性,可以防止密钥被窃取。
  • 使用密钥管理系统(KMS): KMS是一种集中式的密钥管理服务,可以让你安全地存储、管理和使用密钥。云服务提供商通常提供KMS服务,例如AWS KMS、Azure Key Vault等。
  • 使用口令派生密钥(PBKDF2): PBKDF2算法可以使用用户提供的口令生成密钥。这种方式可以避免直接存储密钥,但安全性取决于口令的强度。
  • 使用椭圆曲线Diffie-Hellman (ECDH): 这种方法允许双方在不安全通道上协商共享密钥。

选择哪种密钥管理方式取决于你的安全需求和预算。一般来说,对于高安全性的应用,建议使用HSM或KMS。对于安全性要求较低的应用,可以使用KeyStore或PBKDF2。

以上就是Java中如何用AES实现数据加密解密的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
相关标签:
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号