欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java DES 对称加密

程序员文章站 2022-03-12 23:03:37
...
package com.inspur.uc.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import com.inspur.uc.util.mail.Base64;


/**
 * DES 对称加密算法
 */
public class DESUtil {

	/**
	 * 生成**
	 * @param key
	 * @return SecretKey
	 */
	public static SecretKey createKey(String key) {

		// 需要判断pass长度,并需要长度大于8
		if (key == null || key.length() < 8) {
			key += "abcdefgh";
		}
		SecretKey sk = null;
		try {
			DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("ISO-8859-1"));
			SecretKeyFactory skf = SecretKeyFactory.getInstance("DES");
			sk = skf.generateSecret(desKeySpec);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sk;
	}

	/**
	 * DES加密
	 * @param content
	 * @param key
	 * @return String
	 */
	public static String encode(String content, SecretKey key){
		try {
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.ENCRYPT_MODE,key );
			byte[] b = cipher.doFinal(content.getBytes());
			return Base64.encodeBytes(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * DES解密
	 * @param miwen
	 * @param key
	 * @return String
	 * @throws Exception
	 */
	public static String decode(String miwen, SecretKey key){
		String str = null;
		try {
			Cipher cipher = Cipher.getInstance("DES");
			cipher.init(Cipher.DECRYPT_MODE, key);
			str = new String(cipher.doFinal(Base64.decode(miwen)));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return str;
	}
	public static void main(String[] args)throws Exception {
		
		String yuanwen = "123test测试@qq.11.com";
		System.out.println("原文:"+yuanwen);
		
		SecretKey key = createKey("123456");
		String bs = encode(yuanwen,key);
		System.out.println("加密后:"+bs);
		
		String bsde = decode(bs,key);
		System.out.println("解密后:"+bsde);
	}
}

 输出结果:

原文:123test测试@qq.11.com
加密后:szzkguMZPDa5LleJgENwzb92f6urkT9R
解密后:123test测试@qq.11.com

 

相关标签: 加密解密