专业的JAVA编程教程与资源

网站首页 > java教程 正文

Java中的AES加密:ECB、CBC与GCM模式详解及其优劣

temp10 2025-03-06 19:46:12 java教程 66 ℃ 0 评论

AES(Advanced Encryption Standard)是一种广泛使用的对称加密算法,它提供了多种工作模式,如ECB(Electronic Codebook)、CBC(Cipher Block Chaining)和GCM(Galois/Counter Mode)。每种模式都有其特定的用途和优缺点。本文将详细讨论这些模式,以及如何在Java中实现AES加解密,同时分析它们的适用场景和注意事项。

1. ECB模式

原理

Java中的AES加密:ECB、CBC与GCM模式详解及其优劣

ECB是最基础的加密模式,它将数据分为128位的块独立加密,不考虑相邻块之间的关系。

优缺点

  • 优点:简单快速,易于实现。
  • 缺点:不安全,相同的明文块将产生相同的密文块,容易被模式分析攻击。

示例代码

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESECBExample {
    private static final String ALGORITHM = "AES/ECB/PKCS5Padding";
    private static final String KEY = "0123456789ABCDEF0123456789ABCDEF";

    public static void main(String[] args) throws Exception {
        String plainText = "This is a secret message";
        byte[] encryptedBytes = encrypt(plainText, KEY);
        System.out.println("Encrypted (Base64): " + Base64.getEncoder().encodeToString(encryptedBytes));

        byte[] decryptedBytes = decrypt(encryptedBase64, KEY);
        String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);
        System.out.println("Decrypted Text: " + decryptedText);
    }

    // 加密方法
    private static byte[] encrypt(String plainText, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        return cipher.doFinal(plainText.getBytes());
    }

    // 解密方法
    private static byte[] decrypt(String encryptedBase64, String key) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        return cipher.doFinal(Base64.getDecoder().decode(encryptedBase64));
    }
}

2. CBC模式

原理

CBC模式通过将每个明文块与前一个密文块异或后再进行加密,增加了安全性。

优缺点

  • 优点:安全性优于ECB,相同明文块不会产生相同密文块。
  • 缺点:需要额外的初始化向量(IV),且处理速度稍慢。

示例代码

// 省略相同部分,仅展示与ECB不同的地方
private static byte[] encrypt(String plainText, String key) throws Exception {
    SecureRandom random = new SecureRandom();
    byte[] iv = new byte[16]; // 16-byte IV
    random.nextBytes(iv);
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
    return concatArrays(iv, encryptedBytes);
}

private static byte[] decrypt(String encryptedBase64, String key) throws Exception {
    byte[] decodedBytes = Base64.getDecoder().decode(encryptedBase64);
    byte[] iv = new byte[16];
    byte[] encryptedBytes = new byte[decodedBytes.length - iv.length];

    System.arraycopy(decodedBytes, 0, iv, 0, iv.length);
    System.arraycopy(decodedBytes, iv.length, encryptedBytes, 0, encryptedBytes.length);

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(iv));

    return cipher.doFinal(encryptedBytes);
}

3. GCM模式

原理

GCM模式结合了CTR(Counter)模式的高效性和CBC模式的认证特性,提供了加密和消息认证。

优缺点

  • 优点:安全且高效,提供数据完整性和认证。
  • 缺点:实现复杂,需要管理非重用的nonce,且对nonce的安全性要求较高。

示例代码

// 省略相同部分,仅展示与CBC不同的地方
private static byte[] encrypt(String plainText, String key) throws Exception {
    SecureRandom random = new SecureRandom();
    byte[] nonce = new byte[12]; // 96-bit nonce
    random.nextBytes(nonce);
    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    GCMParameterSpec gcmSpec = new GCMParameterSpec(128, nonce);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmSpec);

    byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
    return concatArrays(nonce, encryptedBytes);
}

private static byte[] decrypt(String encryptedBase64, String key) throws Exception {
    byte[] decodedBytes = Base64.getDecoder().decode(encryptedBase64);
    byte[] nonce = new byte[12];
    byte[] encryptedBytes = new byte[decodedBytes.length - nonce.length];

    System.arraycopy(decodedBytes, 0, nonce, 0, nonce.length);
    System.arraycopy(decodedBytes, nonce.length, encryptedBytes, 0, encryptedBytes.length);

    SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "AES");

    Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
    GCMParameterSpec gcmSpec = new GCMParameterSpec(128, nonce);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmSpec);

    return cipher.doFinal(encryptedBytes);
}

4. 注意事项

  • 密钥管理:确保密钥的安全存储和传输,避免密钥泄露。
  • 填充模式:在处理非128位整数倍的数据时,需要选择合适的填充模式,如PKCS7、ISO 10126等。
  • 随机性:对于CBC和GCM,确保生成的nonce是随机且唯一的。
  • 安全性:在可能的情况下,优先选择GCM模式,因为它提供了更好的安全性。

通过理解AES的ECB、CBC和GCM模式,我们可以根据具体需求选择合适的加密策略。在实际应用中,根据数据安全性和性能需求选择合适的填充模式,并注意密钥和nonce的管理,以提高系统的安全性。

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表