您的位置:首页 > 编程语言 > Java开发

Java与js完成des+3des加密 、解密

2017-07-12 16:49 423 查看
与移动端进行交换的时候经常遇到需要加密、解密的情况,最近在给移动端做接口,就研究了下加解密,把两种方式汇总一下:

1、des加密、解密

(1)des加解密工具类

DesUtil:

package com.loan.fore.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
*
* <b>描述:</b> DES加解密
* <br><b>作者:</b>
* <br><b>版本:</b>1.0
* <br><b>ProjectName:</b> loan-utils
* <br><b>PackageName:</b> com.loan.fore.util
* <br><b>ClassName:</b> DesUtil
* <br><b>Date:</b> 2017年8月3日 下午2:10:40
*/
public class DesUtil {

private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
public static final String KEY = "cf410f84";

public static String encryptDES(String encryptString) throws Exception {
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
return Base64.encode(encryptedData);
}

public static String decryptDES(String decryptString)
throws Exception {
byte[] byteMi = Base64.decode(decryptString);
IvParameterSpec zeroIv = new IvParameterSpec(iv);
SecretKeySpec key = new SecretKeySpec(KEY.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);
byte decryptedData[] = cipher.doFinal(byteMi);

return new String(decryptedData);
}

public static void main(String[] args) throws Exception {
String encryptDES = encryptDES("abc");
System.out.println(encryptDES);
String decryptDES = decryptDES("MpWN08fvUgw=");
System.out.println(decryptDES);
}
}
/**
*
*/
package com.loan.fore.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
* <b>描述:</b>
* <br><b>作者:</b>
* <br><b>版本:</b>1.0
* <br><b>ProjectName:</b> loan-utils
* <br><b>PackageName:</b> com.loan.fore.util
* <br><b>ClassName:</b> Base64
* <br><b>Date:</b> 2017年8月3日 下午5:44:10
*/
public class Base64 {

private static final char[] legalChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
.toCharArray();

/**
* data[]进行编码
*
* @param data
* @return
*/
public static String encode(byte[] data) {
int start = 0;
int len = data.length;
StringBuffer buf = new StringBuffer(data.length * 3 / 2);

int end = len - 3;
int i = start;
int n = 0;

while (i <= end) {
int d = ((((int) data[i]) & 0x0ff) << 16)
| ((((int) data[i + 1]) & 0x0ff) << 8)
| (((int) data[i + 2]) & 0x0ff);

buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append(legalChars[d & 63]);

i += 3;

if (n++ >= 14) {
n = 0;
buf.append(" ");
}
}

if (i == start + len - 2) {
int d = ((((int) data[i]) & 0x0ff) << 16)
| ((((int) data[i + 1]) & 255) << 8);

buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append(legalChars[(d >> 6) & 63]);
buf.append("=");
} else if (i == start + len - 1) {
int d = (((int) data[i]) & 0x0ff) << 16;

buf.append(legalChars[(d >> 18) & 63]);
buf.append(legalChars[(d >> 12) & 63]);
buf.append("==");
}

return buf.toString();
}

public static byte[] decode(String s) {

ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
decode(s, bos);
} catch (IOException e) {
throw new RuntimeException();
}
byte[] decodedBytes = bos.toByteArray();
try {
bos.close();
bos = null;
} catch (IOException ex) {
System.err.println("Error while decoding BASE64: " + ex.toString());
}
return decodedBytes;
}
private static void decode(String s, OutputStream os) throws IOException {
int i = 0;

int len = s.length();

while (true) {
while (i < len && s.charAt(i) <= ' ')
i++;

if (i == len)
break;

int tri = (decode(s.charAt(i)) << 18)
+ (decode(s.charAt(i + 1)) << 12)
+ (decode(s.charAt(i + 2)) << 6)
+ (decode(s.charAt(i + 3)));

os.write((tri >> 16) & 255);
if (s.charAt(i + 2) == '=')
break;
os.write((tri >> 8) & 255);
if (s.charAt(i + 3) == '=')
break;
os.write(tri & 255);

i += 4;
}
}
private static int decode(char c) {
if (c >= 'A' && c <= 'Z')
return ((int) c) - 65;
else if (c >= 'a' && c <= 'z')
return ((int) c) - 97 + 26;
else if (c >= '0' && c <= '9')
return ((int) c) - 48 + 26 + 26;
else
switch (c) {
case '+':
return 62;
case '/':
return 63;
case '=':
return 0;
default:
throw new RuntimeException("unexpected code: " + c);
}
}

}


(2)Controller里头直接调用

返回实体MyReturnEntity:按移动端返回要求设置

package com.loan.fore.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class MyReturnEntity {

private Integer returnStatus=200;
private String returnReason="OK";
private String remarks="No remarks";//中文乱码
private Integer returnTotal=0;

// private List returnMessage=new ArrayList();
private Map<String, Object> returnInformation = new HashMap<String, Object>();

public Map<String, Object> getReturnInformation() {
return returnInformation;
}

public MyReturnEntity setReturnInformation(Map<String, Object> returnInformation) {
this.returnInformation = returnInformation;
return this;
}

public MyReturnEntity() {
// TODO Auto-generated constructor stub
}

public MyReturnEntity(Map<String, Object> returnInformation) {
this.setReturnInformation(returnInformation);
// setReturnMessage(returnMessage);
}

public MyReturnEntity(Integer returnStatus, String returnReason, String remarks) {
this.returnStatus = returnStatus;
this.returnReason = returnReason;
this.remarks = remarks;
}

public MyReturnEntity(Integer returnStatus, String returnReason, String remarks, List returnMessage) {
this.returnStatus = returnStatus;
this.returnReason = returnReason;
this.remarks = remarks;
this.setReturnInformation(returnInformation);
// setReturnMessage(returnMessage);
}

public Integer getReturnStatus() {
return returnStatus;
}

public void setReturnStatus(Integer returnStatus) {
this.returnStatus = returnStatus;
}

public String getReturnReason() {
return returnReason;
}

public void setReturnReason(String returnReason) {
this.returnReason = returnReason;
}

public String getRemarks() {
return remarks;
}

public void setRemarks(String remarks) {
this.remarks = remarks;
}

public Integer getReturnTotal() {
return returnTotal;
}

public void setReturnTotal(Integer returnTotal) {
this.returnTotal = returnTotal;
}

// public List getReturnMessage() {
// return returnMessage;
// }
//
// public void setReturnMessage(List returnMessage) {
// this.returnMessage = returnMessage;
//
// returnTotal=returnMessage==null?0:returnMessage.size();
// }
//
// public MyReturnEntity set(List returnMessage){
//
// if (returnMessage==null) return this.set(new ArrayList());
//
// this.returnMessage = returnMessage;
//
// returnTotal=Optional.ofNullable(returnMessage).map(s->s.size()).orElse(0);
//
// return this;
// }
public MyReturnEntity put(Map<String, Object> returnInformation) {
if (returnInformation == null) {
return this.setReturnInformation(new HashMap<String, Object>());
} else {
this.returnInformation = returnInformation;
returnTotal=Optional.ofNullable(returnInformation).map(s->s.size()).orElse(0);
return this;
}
}

}


package com.loan.fore.util;

//返回消息的工具类
public class ReturnEntityUtils {

//加密验证失败
public static final MyReturnEntity ENCRYFAIL_RETURN=new MyReturnEntity(401,"Invalid encry","非法加密");
//cookie验证失败
public static final MyReturnEntity COOKIEFAIL_RETURN=new MyReturnEntity(401, "Invalid Cookie", "非法 Cookie");
//header验证失败
public static final MyReturnEntity HEADERFAIL_RETURN=new MyReturnEntity(401, "Invalid Header", "非法 Header");
//成功返回,调用时需要.set() 设置返回数据
public static
bed5
final MyReturnEntity SUCCESS_RETURN=new MyReturnEntity();

}
加密:

@ResponseBody
@RequestMapping("DES")
public String test_des() throws Exception{

Map<String, Object> map = new HashMap<>();

map.put("result", "成功");
ProductInfo productInfo=new ProductInfo();
productInfo.setKeyId(1562352);
map.put("product", productInfo);

//加密得到密文
String resCiphertext = DesUtil.encryptDES((JSON.toJSONString(map)));
System.out.println("des加密密文:  "+resCiphertext);

Map<String, Object> map2 = new HashMap<>();
map2.put("dec", resCiphertext);

return JSON.toJSONString(ReturnEntityUtils.SUCCESS_RETURN.put(map2));
}

@RequestMapping("DES")
public void test_des(String ciphertext, HttpServletRequest req, HttpServletResponse rep) throws IOException{

rep.setContentType("application/json;charset=utf-8");

System.out.println("DES接收到的密文: "+ciphertext);

//解密得到明文
try {
String res = DesUtil.decryptDES(ciphertext);
System.out.println("des解密明文: "+res);
}catch (Exception e) {
e.printStackTrace();
}

rep.getWriter().write(JSON.toJSONString(ReturnEntityUtils.SUCCESS_RETURN.put(map)));
}

以上基本des加密就完成了。
2、3des加密解密

 3des只有Java部分哦,js部分没有找,如果需要自己找哦~

(1)3des 工具类

按移动端返回要求设置
package com.loan.fore.util;

import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;

public class ThreeDESUtil {
    public static final String KEY = "*******";//移动端约定好的key
    public static final boolean ISENABLED=true;

    /**
     * DESCBC加密
     *
     * @param src
     *            数据源
     * @param key
     *            密钥,长度必须是8的倍数
     * @return 返回加密后的数据 Base64编码
     * @throws Exception
     */
    // 3DESECB加密,key必须是长度大于等于 3*8 = 24 位
    public static String encryptThreeDESECB(final String src, final String key) throws Exception {
        final DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        final SecretKey securekey = keyFactory.generateSecret(dks);

        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, securekey);
        final byte[] b = cipher.doFinal(src.getBytes());
        
        String res=Base64.getEncoder().encodeToString(b);

        return res;

    }

    /**
     * DESCBC解密
     *
     * @param src
     *            加密之后的数据
     * @param key
     *            密钥,长度必须是8的倍数
     * @return 明码
     * @throws Exception
     */
    // 3DESECB解密,key必须是长度大于等于 3*8 = 24 位
    public static String decryptThreeDESECB(final String src, final String key) throws Exception {
        // --通过base64,将字符串转成byte数组
       //final byte[] bytesrc = Base64.getDecoder().decode(src);
       final byte[] bytesrc=Base64.getMimeDecoder().decode(src);
   
    	//byte[] bytesrc=src.getBytes();
   
        // --解密的key
        final DESedeKeySpec dks = new DESedeKeySpec(key.getBytes("UTF-8"));
        final SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DESede");
        final SecretKey securekey = keyFactory.generateSecret(dks);

        // --Chipher对象解密
        final Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, securekey);
        final byte[] retByte = cipher.doFinal(bytesrc);

        return new String(retByte);
    }
    
    public static void main(String[] args) throws Exception {
        final String key = ThreeDESUtil.KEY;
        // 加密流程
        String telePhone = "{\"id\":29}";
       // telePhone_encrypt = ThreeDESUtil.encryptThreeDESECB(URLEncoder.encode(telePhone, "UTF-8"), key);
        String telePhone_encrypt2=ThreeDESUtil.encryptThreeDESECB(telePhone, key);
        System.out.println(telePhone_encrypt2);
        
        // 解密流程
        String tele_decrypt = ThreeDESUtil.decryptThreeDESECB("8hd/SyOpCYD/rL5I9g45IQ==", key);
        System.out.println("模拟代码解密:" + tele_decrypt);
    }

}

(2)调用的话直接通过 如下调用就可以:

加密:

@ResponseBody
@RequestMapping("threeDES")
public String test_3des(HttpServletRequest req, HttpServletResponse rep) throws IOException{
Map<String, Object> map = new HashMap<>();

map.put("result", "成功");

String resCiphertext = null;
try {
System.out.println(JSON.toJSONString(map));
resCiphertext = ThreeDESUtil.encryptThreeDESECB(JSON.toJSONString(map), ThreeDESUtil.KEY);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Map<String, Object> map2 = new HashMap<>();
map2.put("dec", resCiphertext);

//rep.getWriter().write(resCiphertext);
return JSON.toJSONString(map2);

}解密:
@RequestMapping(value="threeDES")
public void test_3des(HttpServletRequest req, String ciphertext, HttpServletResponse rep) throws IOException{
String res="";
rep.setContentType("application/json;charset=utf-8");
Map<String, Object> map = new HashMap<>();
System.out.println("3DES接收到的密文:  "+ciphertext);
try {
//解密得到明文
res = ThreeDESUtil.decryptThreeDESECB(ciphertext, ThreeDESUtil.KEY);
} catch (Exception e) {
e.printStackTrace();
}
rep.getWriter().write(JSON.toJSONString(ReturnEntityUtils.SUCCESS_RETURN.put(map)));

}


以上就是des+3des加解密

按移动端返回要求设置
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: