盡管DES現在已經基本被AES替代,但畢竟DES速度更快,在一些低級別的加密解密應用場合還是非常適合,Java DES加密解密應用方法跟前一篇的AES類似,都很簡單,網上也有很多類似文章,不過都是把編碼轉換、內容長度判斷等眾多本不屬於算法本身的因素寫到一起,導致代碼太多反倒不好理解。本文基本算是最簡化的Java DES加密解密。
基礎閱讀:
Java AES加密解密實現
AES CBC和CTR加解密實例
AES CFB/OFB/ECB/CBC/CTR優缺點
Java DES加密解密示例代碼如下:
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[] btDESPwd = new byte[8];//8 passwords private byte[] btDESIV = new byte[8];//8 iv private Cipher cObj; private SecretKey sDesPwd; private IvParameterSpec ivDesIps; private SecureRandom sr = new SecureRandom(); public ComCipher(){ int i=0; for(i=0;i<8;i++) btDESPwd[i]=0x01; } public void DESInit() throws Exception { DESKeySpec dks = new DESKeySpec(btDESPwd); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES"); sDesPwd = keyFactory.generateSecret(dks); ivDesIps = new IvParameterSpec(btDESIV); cObj = Cipher.getInstance("DES/CBC/NoPadding");//NoPadding PKCS5Padding } //DES Encrypt public byte[] DESEncrypt(byte[] btCont) throws Exception{ cObj.init(Cipher.ENCRYPT_MODE, sDesPwd,ivDesIps,sr); return cObj.doFinal(btCont); } //DES Decrypt public byte[] DESDecrypt(byte[] btCont) throws Exception{ cObj.init(Cipher.DECRYPT_MODE, sDesPwd,ivDesIps,sr); return cObj.doFinal(btCont); } }
調用示例如下:
要求內容長度必須為8Byte整數倍(上述Instance示例為NoPadding),如果需要Padding可對應修改,開啟Padding後內容長度就無限制。
ComCipher ObjCipher = new ComCipher(); try { int iLen=8; byte[] c1 = new byte[iLen]; for(int k=0;k<iLen;k++) c1[k]=0x01; ObjCipher.DESInit(); System.out.println("Source:"+HexToString(c1,iLen)); byte[] resA = ObjCipher.DESEncrypt(c1); System.out.println("DESEnc:"+HexToString(resA,resA.length)); byte[] resB = ObjCipher.DESDecrypt(resA); System.out.println("DESDec:"+HexToString(resB,resB.length)); } catch (Exception e1) { e1.printStackTrace(); }