Java提供了對稱加密和不對稱加密兩種加密方式。
對稱加密是指加密和解密使用相同密鑰的加密方式。Java中常用的對稱加密算法有DES、AES、RC4等。以下是使用AES算法進行對稱加密的示例代碼:
import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.util.Base64; public class AESEncryptor { private static final String KEY = "abcdefghijklmnop"; public static String encrypt(String data) throws Exception { SecretKeySpec secretKeySpec = new SecretKeySpec(KEY.getBytes(), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec); byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(encryptedBytes); } }
不對稱加密是指加密和解密使用不同密鑰的加密方式。Java中常用的不對稱加密算法有RSA、DSA等。以下是使用RSA算法進行不對稱加密的示例代碼:
import javax.crypto.Cipher; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.PrivateKey; import java.security.PublicKey; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.X509EncodedKeySpec; public class RSAEncryptor { private static final String ALGORITHM = "RSA"; public static KeyPair generateKeyPair(int keySize) throws Exception { KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM); keyPairGenerator.initialize(keySize); return keyPairGenerator.generateKeyPair(); } public static byte[] encrypt(byte[] data, PublicKey publicKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, publicKey); return cipher.doFinal(data); } public static byte[] decrypt(byte[] data, PrivateKey privateKey) throws Exception { Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, privateKey); return cipher.doFinal(data); } }