• 热门专题

3DES加密解密

作者:  发布日期:2014-03-25 20:01:16
Tag标签:加密解密  
  • 3DES(或称为Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于是对每个数据块应用三次DES加密算法。由于计算机运算能力的增强,原版DES密码的密钥长度变得容易被暴力破解;3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。

    3DES又称Triple DES,是DES加密算法的一种模式,它使用3条56位的密钥对3DES数据进行三次加密。数据加密标准(DES)是美国的一种由来已久的加密标准,它使用对称密钥加密法,并于1981年被ANSI组织规范为ANSI X.3.92。DES使用56位密钥和密码块的方法,而在密码块的方法中,文本被分成64位大小的文本块然后再进行加密。比起最初的DES,3DES更为安全。3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的加密标准),加密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,P代表明文,C代表密文,

    这样:3DES加密过程为:C=Ek3(Dk2(Ek1(P)))

    3DES解密过程为:P=Dk1(EK2(Dk3(C)))

    由于客户端开发的接口调用容易被扒取,建议采用此方法加密数据传递。

    通过动态更新密钥的方式、保证接口安全。

    JAVA代码

    需要sunjce_provider.jar 及 fastjson-1.1.8.jar

    import java.security.Provider;
    import java.security.Security;
    import java.util.Random;
    
    import javax.crypto.Cipher;
    import javax.crypto.KeyGenerator;
    import javax.crypto.Mac;
    import javax.crypto.SecretKey;
    import javax.crypto.SecretKeyFactory;
    import javax.crypto.spec.DESKeySpec;
    
    public class MathUtils {
    	public static String COMMON_KEY = "look";
    	public static Random random = new Random(System.currentTimeMillis());
    
    	public static int randomInt(int max) {
    		return (int) (Math.random() * (max));
    	}
    
    	public static long randomLong() {
    		return random.nextLong();
    	}
    
    	public static double randomDouble() {
    		return random.nextDouble();
    	}
    
    	public static String MD5(String str) {
    		Provider sunJce = new com.sun.crypto.provider.SunJCE();
    		Security.addProvider(sunJce);
    
    		try {
    			// Generate secret key for HMAC-MD5
    			KeyGenerator kg = KeyGenerator.getInstance("HmacMD5");
    			SecretKey sk = kg.generateKey();
    
    			// Get instance of Mac object implementing HMAC-MD5, and
    			// initialize it with the above secret key
    			Mac mac = Mac.getInstance("HmacMD5");
    			mac.init(sk);
    			byte[] result = mac.doFinal(str.getBytes());
    
    			return dumpBytes(result);
    		} catch (Exception e) {
    			e.printStackTrace();
    			return null;
    		}
    	}
    
    	public static byte[] desEncrypt(String msg, String salt) {
    		if (msg == null)
    			msg = "";
    		if (salt == null) {
    			salt = "dudusalt";
    		}
    		byte[] keyBytes = new byte[8];
    		int saltLen = salt.length();
    		byte[] saltBytes = salt.getBytes();
    		for (int i = 0; i < 8; i++) {
    			keyBytes[i] = saltBytes[i % saltLen];
    		}
    
    		try {
    			DESKeySpec keySpec = new DESKeySpec(keyBytes);
    			SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(
    					keySpec);
    			Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    			desCipher.init(Cipher.ENCRYPT_MODE, key);
    			byte[] text = msg.getBytes("UTF-8");
    			byte[] ciphertext = desCipher.doFinal(text);
    
    			return ciphertext;
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	public static String desDecrypt(byte[] msg, String salt) {
    		if (msg == null)
    			return null;
    		if (salt == null) {
    			salt = "dudusalt";
    		}
    		byte[] keyBytes = new byte[8];
    		int saltLen = salt.length();
    		byte[] saltBytes = salt.getBytes();
    		for (int i = 0; i < 8; i++) {
    			keyBytes[i] = saltBytes[i % saltLen];
    		}
    
    		try {
    			DESKeySpec keySpec = new DESKeySpec(keyBytes);
    			SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(
    					keySpec);
    			Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    			desCipher.init(Cipher.DECRYPT_MODE, key);
    			byte[] deciphertext = desCipher.doFinal(msg);
    
    			return new String(deciphertext, "UTF-8");
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    	public static String dumpBytes(byte[] bytes) {
    		StringBuffer sb = new StringBuffer();
    		for (int i = 0; i < bytes.length; i++) {
    			/*
    			 * if (i%32 == 0 && i!=0) { sb.append("\n"); }
    			 */
    			String s = Integer.toHexString(bytes[i]);
    			if (s.length() < 2) {
    				s = "0" + s;
    			}
    			if (s.length() > 2) {
    				s = s.substring(s.length() - 2);
    			}
    			sb.append(s);
    		}
    		return sb.toString();
    	}
    
    	public static byte[] parseBytes(String str) {
    		try {
    			int len = str.length() / 2;
    			if (len <= 2) {
    				return new byte[] { Byte.parseByte(str) };
    			}
    			byte[] arr = new byte[len];
    			for (int i = 0; i < arr.length; i++) {
    				arr[i] = (byte) Integer.parseInt(
    						str.substring(i * 2, i * 2 + 2), 16);
    			}
    			return arr;
    		} catch (Exception e) {
    			return new byte[0];
    		}
    	}
    
    	/**
    	 * 加密
    	 * 
    	 * @param encrypt_value
    	 *            被加密的字符串
    	 * @param encrypt_key
    	 *            加密的密钥
    	 * @return
    	 */
    	public static String encryptAsString(String encrypt_value,
    			String encrypt_key) {
    		return dumpBytes(desEncrypt(encrypt_value, encrypt_key));
    	}
    
    	/**
    	 * 解密
    	 * 
    	 * @param encrypt_value
    	 *            要解密的字符串
    	 * @param encrypt_key
    	 *            密钥
    	 * @return
    	 */
    	public static String desEncryptAsString(String encrypt_value,
    			String encrypt_key) {
    		return desDecrypt(parseBytes(encrypt_value), encrypt_key);
    	}
    
    	public static String desEncryptAsString(String encrypt_value) {
    		return desEncryptAsString(encrypt_value, COMMON_KEY);
    	}
    
    	public static String encryptAsString(String encrypt_value) {
    		return dumpBytes(desEncrypt(encrypt_value, COMMON_KEY));
    	}
    
    	public static String getHashPath(long parentId) {
    
    		String id = Long.toString(parentId);
    		/*
    		 * if(id.length()<6) { int m = id.length() ; for(int i = 0 ;i<(6-m);i++)
    		 * { id ="0"+id ; } } else { id =
    		 * id.substring(id.length()-6,id.length()) ; }
    		 */
    		// System.out.println("before hash::"+id) ;
    
    		byte[] buff = id.getBytes();
    		String curr = "0981276345";
    		int len = curr.length();
    		int[] res = new int[8];
    		int iter = 0;
    		for (int i = 0; i < 8; i++) {
    			if (buff.length > i && i < 6) {
    				res[i] = (buff[i] + buff[buff.length - 1 - i]) % 256;
    			} else {
    				res[i] = Integer.parseInt(curr.substring(len - iter - 3, len
    						- iter)) % 256;
    				iter++;
    			}
    		}
    		String str = "";
    		str += Integer.toHexString((int) res[0])
    				+ Integer.toHexString((int) res[1])
    				+ Integer.toHexString((int) res[2])
    				+ Integer.toHexString((int) res[3])
    				+ Integer.toHexString((int) res[4])
    				+ Integer.toHexString((int) res[5])
    				+ Integer.toHexString((int) res[6])
    				+ Integer.toHexString((int) res[7]);
    		str += parentId;
    		System.out.println("after hash::" + str);
    		return str;
    
    	}
    
    	public static String createRandomPassword() {
    		return (System.currentTimeMillis() + "").substring(5, 13);
    	}
    
    }

    public class  Test2 {
    
    	/**
    	 * @param args
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    
    		TreeMap<String, Object> map = new TreeMap<String, Object>();
    		 map.put("name","18912345678");
    		 map.put("pwd","123456");
    		 String desString = JSON.toJSONString(map);
    		 System.out.println("加密前:"+desString);
    		 String desinfo = MathUtils.encryptAsString(desString,
    		 MathUtils.COMMON_KEY);
    		 System.out.println("加密后:"+desinfo);
    
    		// 解密
    		// MathUtils.desEncryptAsString(desString, MathUtils.COMMON_KEY);
     
    	}
    
    }


    DEMO下载:http://pan.baidu.com/s/1c0FyAB2
About IT165 - 广告服务 - 隐私声明 - 版权申明 - 免责条款 - 网站地图 - 网友投稿 - 联系方式
本站内容来自于互联网,仅供用于网络技术学习,学习中请遵循相关法律法规