1. 非對稱加密 RSA
- 定義:RSA 是一種廣泛使用的非對稱加密算法,其安全性基于大整數分解的困難性。它使用一對密鑰,即公鑰和私鑰。公鑰可公開用于加密消息,而私鑰必須保密,用于解密由相應公鑰加密的消息。
- 要點:
- 公鑰公開,私鑰保密,二者成對出現。
- 加密和解密使用不同的密鑰,保證了數據傳輸的安全性。
- 安全性依賴于對極大整數進行因式分解的困難程度。
- 應用:常用于數字簽名、SSL/TLS 協議中的密鑰交換和身份驗證等場景。
- Java 代碼示例:
java
import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.util.Base64;public class RSADemo {public static void main(String[] args) throws Exception {// 生成密鑰對KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");keyPairGenerator.initialize(2048);KeyPair keyPair = keyPairGenerator.generateKeyPair();PublicKey publicKey = keyPair.getPublic();PrivateKey privateKey = keyPair.getPrivate();// 待加密的明文String plainText = "Hello, RSA!";// 加密Cipher cipher = Cipher.getInstance("RSA");cipher.init(Cipher.ENCRYPT_MODE, publicKey);byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);System.out.println("Encrypted Text: " + encryptedText);// 解密cipher.init(Cipher.DECRYPT_MODE, privateKey);byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8);System.out.println("Decrypted Text: " + decryptedText);}
}
2. 對稱密鑰 DES
- 定義:DES(Data Encryption Standard)是一種對稱加密算法,它將 64 位的明文塊通過一系列的置換、替換和異或操作,轉換為 64 位的密文塊。加密和解密使用相同的密鑰。
- 要點:
- 密鑰長度為 56 位(實際使用時包含 8 位奇偶校驗位)。
- 屬于分組加密算法,每次處理 64 位的數據塊。
- 由于密鑰長度較短,安全性相對較低,如今已較少使用。
- 應用:早期用于金融、政府等領域的數據加密。
- Java 代碼示例:
java
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64;public class DESDemo {public static void main(String[] args) throws Exception {// 生成DES密鑰KeyGenerator keyGenerator = KeyGenerator.getInstance("DES");keyGenerator.init(56);SecretKey secretKey = keyGenerator.generateKey();// 待加密的明文String plainText = "Hello, DES!";// 加密Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");cipher.init(Cipher.ENCRYPT_MODE, secretKey);byte[] encryptedBytes = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);System.out.println("Encrypted Text: " + encryptedText);// 解密cipher.init(Cipher.DECRYPT_MODE, secretKey);byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));String decryptedText = new String(decryptedBytes, Sta