Keep on going, never give up.

Java DES加密解密实现

尽管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();
	}	

参考资料:

http://docs.oracle.com/javase/7/docs/api/javax/crypto/Cipher.html

相关评论(0):  

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

订阅博客

最新文章

本站采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载也必须遵循“署名-非商业用途-保持一致”的创作共用协议. 返回顶部
Copyright@2005-2016 Metsky.com, All rights Reserved.