1. 程式人生 > >3DES 加密解密

3DES 加密解密

        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

相關推薦

C# PHP QT 3Des 加密解密

//加密解碼 不同的平臺和模式。 調整CipherMode                ECB:模式不使用iv             CBC:使用iv 填補方案:(TransformFinalBlock解密程式出錯,很大可能就是填充方案不一致)      

微信小程式:3DES加密解密

3DES加密解密   encryptDES.js var CryptoJS = CryptoJS || function(u, l) { var d = {}, n = d.lib = {}, p = function() {}, s =

3DES 加密解密

        3DES(或稱為Triple DES)是三重資料加密演算法(TDEA,Triple Data Encryption Algorithm)塊密碼的通稱。它相當於是對每個資料塊應用三次DES加密演算法。由於計算機運算能力的增強,原版DES密碼的金鑰長度變得容

微信小程式3des加密解密,這個需要看我上一遍文章微信小程式不支援window物件跟navigator物件... 本加密是存在問題的,加密java有時候不能解開

var base64ende = require('../utils/Base64.js'); /** * @description 3DES加密解密 */ function des(key, message, encrypt, mode, iv, padding

JAVA 3DES加密/解密

3DES(或稱為Triple DES)是三重資料加密演算法(TDEA,Triple Data Encryption Algorithm)塊密碼的通稱。它相當於是對每個資料塊應用三次DES加密演算法。由於計算機運算能力的增強,原版DES密碼的金鑰長度變得容易被暴

Java 3DES加密解密(Commons.Codec Base64)

依賴包import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.codec.binary.Base64;演算法程式碼 /** * 轉換成十六進位制字串 * @

C# 3DES加密解密演算法

using System; using System.Collections.Generic; using System.Text; using System.Security.Cryptography; using System.IO; namespace C

用CryptoJS 實現js端3des加密解密,用openssl_encrypt實現php的3des加密解密,相容java和C#和c++等

       因為要開發社交平臺,涉及到聊天內容,這些敏感內容想用3des加密傳輸,百度了好多資料,測試了好多次,終於實現了功能,可以直接使用,這裡寫下來,希望幫助到其他朋友。      聽說微信小程式需要資料加密,相信這個能幫到大家。 這裡說一下,iv向量一般是8位

PHP使用3DES演算法加密解密字串

3DES(或稱為Triple DES)是三重資料加密演算法(TDEA,Triple Data Encryption Algorithm)塊密碼的通稱。它相當於是對每個資料塊應用三次DES加密演算法。由於計算機運算能力的增強,原版DES密碼的金鑰長度變得容易被暴力破解;3DE

3DES演算法加密解密工具類(含有1DES)

DESCBC加密參考:點選開啟連結public class TripleDESUtil    {字元轉換參考之前一片博文點選開啟連結 /** * 加密位元組陣列 * * @param arrB 需加密的位元組陣列 * @retur

iOS-OC-3DES加密解密

+ (NSString*)TripleDES:(NSString*)plainText encryptOrDecrypt:(CCOperation)encryptOrDecrypt { con

探討NET Core資料進行3DES加密解密弱金鑰問題

前言 之前寫過一篇《探討.NET Core資料進行3DES加密和解密問題》,最近看到有人提出弱金鑰問題,換個強金鑰不就完了嗎,猜測可能是與第三方對接導致很無奈不能更換金鑰,所以產生本文解決.NET Core中3DES弱金鑰問題,寫下本文,希望對碰到此問題的童鞋有所幫助。 3DES加密或解密弱金鑰 在基於.NE

簡單的加密解密處理

length stat end socket通訊 上一個 規則 alt cnblogs 字符   今天一位小朋友通過郵箱向我發送一封求助信息。 內容大致如下: 您好!之前您寫的那個C#客戶端服務器程序運行成功,但能不能加上一個加密解密的函數,老師要求客戶端/服務器模式

Openssl及加密解密(二)openssl

opensslopenssl是一個條件實現了上百種算法、實現了單向加密工具等一組套件,代碼量很小但是功能強大。它有三部分組成:libcrypto:通用功能的加密庫,軟件開發時可以直接調用libssl:實現TLS/SSL的功能openssl:多功能命令行工具,加密、解密、創建CA、證書、一對秘鑰等openssl

c#中base64加密解密

stat mon 註意 pac enc return mba try encode using System; using System.Text; namespace Common { /// <summary> /// 實現Base64加密解密 ///

Aes加密解密

tran delegate class ext str eap ase hfs tde 加密時:先對string進行utf8解析成數組-->對數組進行加密-->對加密結果用base64解析成string。 那麽揭秘時,

Python 加密解密算法

字符串 加密 呃,今天來看看加密和解密,本文討論base64和hashlib庫: 來看看HASHLIB,他是一種單向摘要出定長字符串的方法: 擼代碼: In [18]: import time,hashlib In [19]: t = int(time.time()) In

Laravel之加密解密/日誌/異常處理及自定義錯誤

文件中 例如 tom 處理器 crypt return cat 情況 而不是 一.加密解密 1.加密Crypt::encrypt($request->secret) 2.解密try {   $decrypted = Crypt::decrypt($encryptedV

Java小案例——對字符串進行加密解密

i++ 個數 color class 異或運算 揭秘 println scanner 英文 要求:   * 對用戶輸入的每個字符的值進行加密,將解密後的字符串輸出   * 對用戶輸入的已加密字符串進行解密並輸出 實現代碼: import java.util.Sca

Python_字符串簡單加密解密

tool 字符 decrypt pan res rto ted next def 1 def crypt(source,key): 2 from itertools import cycle 3 result=‘‘ 4 temp=cycle