DES加密解密工具类

1,DES加密解密工具类

package spring3.pripertyFile;

import java.security.Key;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESUtils {

	private static Key key;
	private static final String KEY_STR = "@myKey!";
	private static final String DES = "DES";
	private static final String UTF8 = "UTF8";

	static {
		try {
			KeyGenerator genarator = KeyGenerator.getInstance(DES);
			genarator.init(new SecureRandom(KEY_STR.getBytes()));
			key = genarator.generateKey();
			genarator = null;
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * 加密
	 * 
	 * @param str
	 *            原文
	 * @return 密文
	 */
	public static String getEncryptString(String str) {
		BASE64Encoder encoder = new BASE64Encoder();
		try {
			Cipher cipher = Cipher.getInstance(DES);
			cipher.init(Cipher.ENCRYPT_MODE, key);
			return encoder.encode(cipher.doFinal(str.getBytes(UTF8)));
		} catch (Exception e) {
			throw new RuntimeException();
		}
	}

	/**
	 * 解密
	 * 
	 * @param str
	 *            密文
	 * @return 原文
	 */
	public static String getDecryptString(String str) {
		BASE64Decoder decoder = new BASE64Decoder();
		try {
			Cipher cipher = Cipher.getInstance(DES);
			cipher.init(Cipher.DECRYPT_MODE, key);
			return new String(cipher.doFinal(decoder.decodeBuffer(str)), UTF8);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException();
		}
	}

	public static void main(String[] args) {
		String srcStr = "password";
		System.out.println("原文:" + srcStr);
		System.out.println("密文:" + getEncryptString(srcStr));
		System.out.println();
		String destStr = "NWVdft3lhOnJdIQo/tKMJw==";
		System.out.println("密文:" + destStr);
		System.out.println("原文:" + getDecryptString(destStr));
	}
}

 2,关于BASE64Decoder和BASE64Encoder的import问题

右键项目⇒属性java bulid pathjre System Libraryaccess rulesresolution选择accessible,下面填上** 点击确定即可
DES加密解密工具类_第1张图片
 
 

你可能感兴趣的:(加密解密)