请介绍Java中常用的加密算法(如AES、RSA等),并举例说明如何在Java代码中安全地使用它们。

Java 中常用的加密算法主要包括对称加密算法(如AES)和非对称加密算法(如RSA)。以下是它们的详细介绍及在Java中的安全使用示例。

1. 对称加密算法:AES

AES(Advanced Encryption Standard)是一种对称加密算法,即加密和解密使用相同的密钥。其特点是速度快,适合加密大量数据。

示例代码:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;

public class AESExample {
    public static void main(String[] args) throws Exception {
        // 生成密钥
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256); // 使用256位密钥
        SecretKey secretKey = keyGenerator.generateKey();

        // 加密
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] iv = new byte[16]; // 初始化向量
        new SecureRandom().nextBytes(iv);
        IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParameterSpec);
        String plainText = "Hello, AES Encryption!";
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted: " + encryptedText);

        // 解密
        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParameterSpec);
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted: " + decryptedText);
    }
}

安全提示:

  • 密钥和初始化向量(IV)必须随机生成,避免硬编码。
  • 使用CBC模式时,IV必须唯一且不可预测。
  • 密钥应存储在安全的地方(如密钥库)。

2. 非对称加密算法:RSA

RSA是一种非对称加密算法,使用公钥加密、私钥解密。适合加密少量数据或用于密钥交换。

示例代码:

import javax.crypto.Cipher;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.util.Base64;

public class RSAExample {
    public static void main(String[] args) throws Exception {
        // 生成密钥对
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        keyPairGenerator.initialize(4096); // 使用4096位密钥
        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // 加密
        Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
        String plainText = "Hello, RSA Encryption!";
        byte[] encryptedBytes = cipher.doFinal(plainText.getBytes());
        String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
        System.out.println("Encrypted: " + encryptedText);

        // 解密
        cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
        byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
        String decryptedText = new String(decryptedBytes);
        System.out.println("Decrypted: " + decryptedText);
    }
}

安全提示:

  • 使用较长的密钥(如4096位)。
  • 优先选择OAEP填充模式(如OAEPWithSHA-256AndMGF1Padding),避免PKCS#1 v1.5填充的漏洞。
  • 私钥必须严格保密,公钥可以公开。

3. 其他常用加密算法

  1. SHA-256(哈希算法)

    • 用于生成数据的指纹,不可逆。
    • 示例:
      import java.security.MessageDigest;
      import java.util.HexFormat;
      
      public class SHA256Example {
          public static void main(String[] args) throws Exception {
              String input = "Hello, SHA-256!";
              MessageDigest digest = MessageDigest.getInstance("SHA-256");
              byte[] hashBytes = digest.digest(input.getBytes());
              String hashText = HexFormat.of().formatHex(hashBytes);
              System.out.println("SHA-256 Hash: " + hashText);
          }
      }
      
  2. HMAC(消息认证码)

    • 使用密钥生成哈希,用于验证消息完整性。
    • 示例:
      import javax.crypto.Mac;
      import javax.crypto.spec.SecretKeySpec;
      import java.util.HexFormat;
      
      public class HMACExample {
          public static void main(String[] args) throws Exception {
              String message = "Hello, HMAC!";
              String secretKey = "MySecretKey";
              Mac mac = Mac.getInstance("HmacSHA256");
              mac.init(new SecretKeySpec(secretKey.getBytes(), "HmacSHA256"));
              byte[] hmacBytes = mac.doFinal(message.getBytes());
              String hmacText = HexFormat.of().formatHex(hmacBytes);
              System.out.println("HMAC: " + hmacText);
          }
      }
      

总结

  • 对称加密(AES):速度快,适合加密大量数据,密钥管理是关键。
  • 非对称加密(RSA):适合密钥交换或加密少量数据,需保护私钥。
  • 哈希(SHA-256)和HMAC:用于数据完整性验证。

在实际应用中,应根据需求选择合适算法,并遵循安全实践(如密钥管理、填充模式选择等)。