`
leon1509
  • 浏览: 527627 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

DES加解密之三

    博客分类:
  • JAVA
阅读更多
目前客户端使用的。

import java.security.Key;
import java.security.MessageDigest;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

public class EncryptUtil {
	public final static String DES = "DES";
	public final static String MD5 = "MD5";
	static AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现
	private static Key key = null;

	public static String encode(String sKey) throws Exception {
		String sKeyFormat = "ICITIC_PWD";
		byte[] inputByteArray = sKey.getBytes();
		byte[] desKey = getMD5ofStr(sKeyFormat).substring(0, 8).getBytes();
		byte[] desIV = getMD5ofStr(sKeyFormat).substring(0, 8).getBytes();
		CryptoTools(desKey, desIV);
		Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
		enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
		byte[] pasByte = enCipher.doFinal(inputByteArray);
		StringBuffer sb = new StringBuffer();
		sb.append(bytes2HexString(pasByte));
		return sb.toString();
	}

	// 设置加密工具
	private static void CryptoTools(byte[] DESkey, byte[] DESIV)
			throws Exception {
		DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
		iv = new IvParameterSpec(DESIV);// 设置向量
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);// 获得密钥工厂
		key = keyFactory.generateSecret(keySpec);// 得到密钥对象
	}

	// MD5加密
	private static String getMD5ofStr(String sKeyFormat) {
		try {
			byte[] str = sKeyFormat.getBytes();
			MessageDigest md = MessageDigest.getInstance(MD5);
			md.update(str);
			byte[] b = md.digest();
			return bytes2HexString(b);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		try {
			System.out.println(encode("888888"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static String bytes2HexString(byte[] bytes) {
		String hs = null;
		if (bytes != null) {
			final int size = bytes.length;
			if (size > 0) {
				StringBuilder sb = new StringBuilder();
				for (int i = 0; i < size; i++) {
					String tmp = (java.lang.Integer
							.toHexString(bytes[i] & 0XFF));
					if (tmp.length() == 1) {
						sb.append("0" + tmp);
					} else {
						sb.append(tmp);
					}
				}
				hs = sb.toString().toUpperCase();
			}
		}
		return hs;
	}
}



结果:
BB8DF9AB68109156
分享到:
评论
1 楼 ycq__110 2012-02-08  
THS。非常6+1

相关推荐

Global site tag (gtag.js) - Google Analytics