DES加密使用

所谓加密,从应用角度就是使用指定的密钥将指定的数据进行加密。

我们不用关心具体算法的实现,只要关心应用本身需求和加密方法的使用即可。

如下是DES加密方法是用的示例,注意使用DES的话密钥长度应该是8的倍数

package com.util;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DESUtil {
	private static final String PASSWORD_CRYPT_KEY = "01234567";// 示例密钥
	private final static String DES = "DES";
	public static void main(String[] args) {
		System.out.println(encrypt("cuisuqiang", "12345678"));
		System.out.println(decrypt(encrypt("cuisuqiang", "12345678"),"12345678"));
	}
	/**
	 * 加密
	 * @param src 数据
	 * @param key 密钥,长度必须是8的倍数
	 * @return 返回加密后的数据
	 */
	private static byte[] encrypt(byte[] src, byte[] key) throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
		return cipher.doFinal(src);
	}
	/**
	 * 解密
	 * @param src 数据
	 * @param key 密钥,长度必须是8的倍数
	 * @return 返回解密后的原始数据
	 */
	private static byte[] decrypt(byte[] src, byte[] key) throws Exception {
		SecureRandom sr = new SecureRandom();
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
		return cipher.doFinal(src);
	}
	/**
	 * 密码加密
	 */
	public final static String encrypt(String data, String key) {
		try {
			return byte2hex(encrypt(data.getBytes(), key.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	/**
	 * 密码解密
	 */
	public final static String decrypt(String data, String key) {
		try {
			return new String(decrypt(hex2byte(data), key.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	// 字节码转换成16进制字符串
	private static String byte2hex(byte bytes[]) {
		StringBuffer retString = new StringBuffer();
		for (int i = 0; i < bytes.length; ++i) {
			retString.append(Integer.toHexString(0x0100 + (bytes[i] & 0x00FF)).substring(1).toUpperCase());
		}
		return retString.toString();
	}
	// 将16进制字符串转换成字节码
	private static byte[] hex2byte(String hex) {
		byte[] bts = new byte[hex.length() / 2];
		for (int i = 0; i < bts.length; i++) {
			bts[i] = (byte) Integer.parseInt(hex.substring(2 * i, 2 * i + 2),16);
		}
		return bts;
	}
}

 

 

先加密,再将加密的内容反转。

 

 

请您到ITEYE看我的原创:http://cuisuqiang.iteye.com

或支持我的个人博客,地址:http://www.javacui.com

 

你可能感兴趣的:(算法,加密,Security,密钥,des)