Java 語言是一種強大的編程語言,具有簡潔、安全和跨平臺等特點,被廣泛應用于軟件開發領域。其中,實現 AES(Advanced Encryption Standard)和 RSA(Rivest–Shamir–Adleman)加密算法是 Java 開發中常用的操作。
AES 是一種對稱加密算法,加密和解密使用相同的密鑰。Java 提供了 javax.crypto 包來完成 AES 算法的實現。以下是一個簡單的 AES 加密和解密示例:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import java.nio.charset.StandardCharsets; import java.security.NoSuchAlgorithmException; public class AESEncryption { public static byte[] encrypt(String plaintext, String key) throws Exception { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, getKey(key)); return cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8)); } public static String decrypt(byte[] ciphertext, String key) throws Exception { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, getKey(key)); return new String(cipher.doFinal(ciphertext), StandardCharsets.UTF_8); } private static SecretKey getKey(String keyString) throws NoSuchAlgorithmException { KeyGenerator keyGen = KeyGenerator.getInstance("AES"); keyGen.init(128); return keyGen.generateKey(); } }
RSA 是一種非對稱加密算法,加密和解密使用不同的密鑰。Java 提供了 java.security 包來完成 RSA 算法的實現。以下是一個簡單的 RSA 加密和解密示例:
import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Security; import javax.crypto.Cipher; import org.bouncycastle.jce.provider.BouncyCastleProvider; public class RSAEncryption { public static byte[] encrypt(String plaintext, PublicKey key) throws Exception { Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(plaintext.getBytes()); } public static String decrypt(byte[] ciphertext, PrivateKey key) throws Exception { Security.addProvider(new BouncyCastleProvider()); Cipher cipher = Cipher.getInstance("RSA/NONE/OAEPWithSHA256AndMGF1Padding", "BC"); cipher.init(Cipher.DECRYPT_MODE, key); return new String(cipher.doFinal(ciphertext)); } public static KeyPair generateKeyPair() throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA", "BC"); keyGen.initialize(2048); return keyGen.generateKeyPair(); } }
AES 和 RSA 都是常用的加密算法,Java 的 javax.crypto 包和 java.security 包提供了完善的工具,可以輕松地實現對稱加密和非對稱加密,幫助我們保障信息的安全。