Java中的AES和DES是兩種常用的加密算法,它們都可以用于數據的加密和解密。下面分別介紹一下這兩種算法。
AES:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AESUtil { public static byte[] encrypt(byte[] data, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return cipher.doFinal(data); } public static byte[] decrypt(byte[] encryptedData, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return cipher.doFinal(encryptedData); } public static byte[] initKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } }
DES:
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; public class DESUtil { public static byte[] encrypt(byte[] data, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); return cipher.doFinal(data); } public static byte[] decrypt(byte[] encryptedData, byte[] key) throws Exception { SecretKey secretKey = new SecretKeySpec(key, "DES"); Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, secretKey); return cipher.doFinal(encryptedData); } public static byte[] initKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); keyGenerator.init(56); SecretKey secretKey = keyGenerator.generateKey(); return secretKey.getEncoded(); } }
以上代碼為Java實現的AES和DES算法,具體使用可參考各個方法的注釋。在實際開發中,根據具體的需求選擇合適的加密算法,加強數據的安全性。
上一篇css 字體向右對其
下一篇vue怎么對接app