对称加密方法DES等

package cn.haq.des;
import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class DES {

	//KeyGenerator提供对称密钥生成器的功能,支持各种算法
	private KeyGenerator keyGen;
	//SecretKey负责保存对称密钥
	private SecretKey desKey;
	private SecretKey desKey2;
	//Cipher负责完成加密或解密工作
	private Cipher c;
	//该字节数组保存加密的结果
	private byte[] cipherByte;
	public DES()
	{
//		Security.addProvider(new com.sun.crypto.provider.SunJCE());
		try {
			//实例化支持DES算法的密钥生成器(算法名称需按规定,否则抛出异常)
			keyGen = KeyGenerator.getInstance("DES");
			//生成密钥
			desKey =keyGen.generateKey();
			desKey2 = keyGen.generateKey();
			//生成Cipher对象,指定其支持DES算法
			c = Cipher.getInstance("DES");
		} catch (Exception e) {
			// TODO: handle exception
		}
	}
	/**
	 * 对字符串str加密
	 */
	public byte[] createEncryptor(String str)
	{
			try {
				//根据密钥,对Cipher对象进行初始化,ENCRYPT_MODE表示加密模式
				c.init(Cipher.ENCRYPT_MODE, desKey);//第二个参数就是密钥
				byte[] src = str.getBytes();
				//加密 结果保存到cipherByte
				cipherByte = c.doFinal(src);
			} catch (Exception e) {
				// TODO: handle exception
			}
			return cipherByte;
	}
	/**
	 * 对字节数组buff解密
	 */
	public byte[] createDecryptor(byte[] buff)
	{
		try
		{
			//根据密钥,对Cipher对象进行初始化,DECRYPT_MODE表示解密
			c.init(Cipher.DECRYPT_MODE, desKey);//解密需要同一个密钥
			//得到明文存到cipherByte
			cipherByte = c.doFinal(buff);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		return cipherByte;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		DES des = new DES();
		String msg = "测试加密";
		System.out.println("明文是:"+msg);
		byte[] enc = des.createEncryptor(msg);
		System.out.println("密文是:"+ new String(enc));
		byte[] dnc = des.createDecryptor(enc);
		System.out.println("解密是:"+new String(dnc));
	}

}

你可能感兴趣的:(对称加密方法DES等)