本文總結Java AES加密解密應用實例,Java加密解密庫都很完善,所以,調用方法也都非常簡單,但Java代碼以低效率著稱,所以,對時效性要求太高的盡量避開Java層而使用C/C++等程序實現。C/C++ AES算法實現可參考天緣前一篇文章《AES CBC和CTR加解密實例》。
基礎知識,AES模式區別:AES CFB/OFB/ECB/CBC/CTR優缺點
Java示例代碼如下:
默認使用AES128 ECB/NoPadding,具體參數設置可參考文末地址。因為是NoPadding,所以,要求輸入的數據長度必須為16Byte倍數。如果使用CBC模式,還需附帶IV參量。
import java.security.SecureRandom; import java.security.Key; import java.security.Security; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.KeyGenerator; import javax.crypto.Cipher; import javax.crypto.spec.DESKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.IvParameterSpec; //AES 128 public class ComCipher { private byte[] btAESKey = new byte[16];//128 bits AES private Cipher cObj; private SecretKeySpec sAesKey; public ComCipher(){ int i=0; for(i=0;i<16;i++) btAESKey[i]=0x01; } public void AESInit() throws Exception{ sAesKey = new SecretKeySpec(btAESKey, "AES"); cObj = Cipher.getInstance("AES/ECB/NoPadding");//NoPadding PKCS5Padding } //AES Encrypt content public byte[] AESEncrypt(byte[] btCont) throws Exception { cObj.init(Cipher.ENCRYPT_MODE, sAesKey); return cObj.doFinal(btCont); } //AES Decrypt content public byte[] AESDecrypt(byte[] btCont) throws Exception { cObj.init(Cipher.DECRYPT_MODE, sAesKey); return cObj.doFinal(btCont); } }
用法如下:
ComCipher ObjCipher = new ComCipher(); try { int iLen=8; byte[] c1 = new byte[iLen]; for(int k=0;k<iLen;k++) c1[k]=0x01; ObjCipher.AESInit(); byte[] resC = ObjCipher.AESEncrypt(c1); System.out.println("AESEnc:"+HexToString(resC,resC.length)); byte[] resD = ObjCipher.AESDecrypt(resA); System.out.println("AESDec:"+HexToString(resD,resD.length)); } catch (Exception e1) { e1.printStackTrace(); }
上述代碼中,HexToString打印Byte數組到字符串,源碼略。