Java是一種廣泛使用的編程語言,支持多種加密算法。其中,AES(高級加密標(biāo)準(zhǔn))是一種高度安全和廣泛使用的對稱加密算法。在Java中,我們可以使用AES128和AES256對數(shù)據(jù)進(jìn)行加密和解密。
要使用AES加密,我們需要導(dǎo)入Java提供的加密庫javax.crypto。下面是一個使用AES128進(jìn)行加密和解密的示例:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AESUtil { private static final String ALGORITHM = "AES"; public static byte[] encrypt(byte[] key, byte[] data) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return cipher.doFinal(data); } public static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec); return cipher.doFinal(encryptedData); } public static byte[] generateKey128() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); keyGenerator.init(128); SecretKey key = keyGenerator.generateKey(); return key.getEncoded(); } }
上面的代碼中,我們首先定義了一個私有常量ALGORITHM表示加密算法(這里是AES),然后通過encrypt方法和decrypt方法分別對數(shù)據(jù)進(jìn)行加密和解密。generateKey128方法用于生成一個128位的隨機(jī)密鑰。
要使用AES256進(jìn)行加密和解密,我們只需要將KeyGenerator初始化為256即可。下面是一個使用AES256進(jìn)行加密和解密的示例:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AES256Util { private static final String ALGORITHM = "AES"; public static byte[] encrypt(byte[] key, byte[] data) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.ENCRYPT_MODE, keySpec); return cipher.doFinal(data); } public static byte[] decrypt(byte[] key, byte[] encryptedData) throws Exception { SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM); Cipher cipher = Cipher.getInstance(ALGORITHM); cipher.init(Cipher.DECRYPT_MODE, keySpec); return cipher.doFinal(encryptedData); } public static byte[] generateKey256() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance(ALGORITHM); keyGenerator.init(256); SecretKey key = keyGenerator.generateKey(); return key.getEncoded(); } }
上面的代碼與之前的示例類似,只是將KeyGenerator的初始化改為了256位。這樣就可以使用AES256對數(shù)據(jù)進(jìn)行加密和解密了。