實測 沒問題 java
package cn.com.test;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
public class Des3 {
private static final String Algorithm = new String("DESede"); //算法標識
private SecretKey deskey; //密鑰
public Des3() throws Exception {
KeyGenerator keygen = KeyGenerator.getInstance(Algorithm);
deskey = keygen.generateKey();
}
public Des3(byte[] key) throws Exception {
if (key == null) {
throw new Exception("input key can not null");
}
if (key.length != 24) {
throw new Exception("key length is error, key length must 24 bytes");
}
SecretKeySpec destmp = new SecretKeySpec(key, Algorithm);
deskey = destmp;
}
public byte[] getKey() {
return deskey.getEncoded();
}
/**
* 加密數據
* @param data byte[]
* @return byte[]
*/
public byte[] encrypt(byte[] data) throws Exception {
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.ENCRYPT_MODE, deskey);
return c1.doFinal(data);
}
/**
* 解密數據
* @param data byte[]
* @return byte[]
*/
public byte[] decrypt(byte[] data) throws Exception {
Cipher c1 = Cipher.getInstance(Algorithm);
c1.init(Cipher.DECRYPT_MODE, deskey);
return c1.doFinal(data);
}
}
算法
package cn.com.test;
import com.ibm.misc.BASE64Decoder;
import com.ibm.misc.BASE64Encoder;
public class Des3Util {
public static String decryptBy3Des(String encryptStr, String key) throws Exception {
Des3 des = new Des3(key.getBytes());
BASE64Decoder base64decoder = new BASE64Decoder();
byte[] encryptBytes = base64decoder.decodeBuffer(encryptStr);
byte[] decryptBytes = des.decrypt(encryptBytes);
return new String(decryptBytes,"UTF-8");
}
public static String encryptBy3Des(String str, String key) throws Exception {
Des3 des = new Des3(key.getBytes());
byte[] encryptBytes=des.encrypt(str.getBytes("UTF-8"));
BASE64Encoder base64encoder=new BASE64Encoder();
String dd= base64encoder.encode(encryptBytes);;
return dd;
}
}
測試類 json
package cn.com.test;
import java.util.HashMap;
import java.util.Map;
import com.alibaba.fastjson.JSON;
public class JiamiTest {
public static void main(String[] args) throws Exception {
Map<String,String> jiamimap=new HashMap<String, String>();
jiamimap.put("birthday","2016-01-08");
jiamimap.put("card","12345689522");
jiamimap.put("cardType","4");
jiamimap.put("community_id","1");
jiamimap.put("community_name","通常社康");
jiamimap.put("dept_id","223");
jiamimap.put("dept_name","骨科");
jiamimap.put("doctor_name","張三");
jiamimap.put("phone","12345678944");
jiamimap.put("querytime","xxxxxx");
jiamimap.put("return_url","xxxx");
jiamimap.put("sex","女");
jiamimap.put("token","4028800b51e760b40151e781bb44004b");
jiamimap.put("truename","張四");
jiamimap.put("user","shekang");
String json =JSON.toJSONString(jiamimap);
String a=Des3Util.encryptBy3Des(json, "abcabcabcabcabcabcabcabc");
System.out.println("加密後的字符串++++++++++"+a);
String b=Des3Util.decryptBy3Des(a, "abcabcabcabcabcabcabcabc");
System.out.println("解密後的字符串——————————"+b);
}
}
測試