Java中的对称加密密码学
简介
对称加密,也称为密钥加密,是一种加密方法,其中相同的密钥用于加密和解密。这种加密方法快速高效,适用于加密大量数据。最常用的对称加密算法是高级加密标准(AES)。
Java提供了对称加密的强大支持,其中包括javax.crypto包中的类,如SecretKey、Cipher和KeyGenerator。
Java 中的对称加密
javax.crypto 包中的 Java Cipher 类提供了加密和解密的密码功能。它构成了 Java 加密扩展 (JCE) 框架的核心。
在Java中,Cipher类提供对称加密的功能,而KeyGenerator类用于生成对称加密的密钥。
Example
让我们来看一个使用Java实现的简单对称加密AES的例子−
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.nio.charset.StandardCharsets; import java.util.Base64; public class Main { public static void main(String[] args) throws Exception { // Generate key SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey(); // Original message String originalMessage = "Hello, world!"; // Create Cipher instance and initialize it to ENCRYPT_MODE Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); // Encrypt the message byte[] encryptedMessage = cipher.doFinal(originalMessage.getBytes(StandardCharsets.UTF_8)); // Convert the encrypted message to Base64 encoded string String encodedMessage = Base64.getEncoder().encodeToString(encryptedMessage); System.out.println("Original Message: " + originalMessage); System.out.println("Encrypted Message: " + encodedMessage); // Reinitialize the cipher to DECRYPT_MODE cipher.init(Cipher.DECRYPT_MODE, secretKey); // Decrypt the message byte[] decryptedMessage = cipher.doFinal(Base64.getDecoder().decode(encodedMessage)); System.out.println("Decrypted Message: " + new String(decryptedMessage, StandardCharsets.UTF_8)); } } 登录后复制