java实现DES加密

通常,在传输文件的时候,需要对传输内容进行加密。DES是一种比较简单的加密方式,能够满足一定条件下的数据安全需求。

 

public class DESTest {
	
	static String DES = "DES";
	
	public static void main(String[] args){
		String strData = "woshihaoren";
		String pwd = "98765432";
		try {
			byte[] st1 = encrypt(strData.getBytes(), pwd.getBytes());
			System.out.println(new String(st1));
			
			byte[] st2 = decrypt(st1, pwd.getBytes());
			
			System.out.println(new String(st2));
			
		} catch (Exception e) {

			e.printStackTrace();
		}
	}
	
	
	public static byte[] decrypt(byte[] data, byte[] key) throws Exception{
		// DES算法要求有一个可信任的随机数源
		SecureRandom random = new SecureRandom();
		// 创建一个DESKeySpec对象
		DESKeySpec desKey = new DESKeySpec(key);
		// 创建一个密匙工厂
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		// 将DESKeySpec对象转换成SecretKey对象
		SecretKey securekey = keyFactory.generateSecret(desKey);
		
		// Cipher对象实际完成解密操作
		Cipher cipher = Cipher.getInstance(DES);
		// 用密匙初始化Cipher对象
		cipher.init(Cipher.DECRYPT_MODE, securekey, random);
		// 真正开始解密操作
		return cipher.doFinal(data);
	}
	
	public static byte[] encrypt(byte[] data, byte[] key) throws Exception{
		
		//生成一个随机数据源
		SecureRandom random = new SecureRandom();
		
		DESKeySpec ds = new DESKeySpec(key);
		
		//创建一个密匙工厂,然后用它把DESKeySpec转换成
		SecretKeyFactory  keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(ds);
		
		//Cipher对象实际完成加密操作
		Cipher cipher = Cipher.getInstance(DES);
		
		//用密匙初始化Cipher对象
		cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
		
		//获取数据并加密
		return cipher.doFinal(data);
	}
}

 

 

 

 

 

你可能感兴趣的:(java基本算法与代码片段)