자바 와 js 가 des+3des 암호 화,복호화 완료

15928 단어 자바
이동 단 과 교환 할 때 암호 화,복호화 가 필요 한 경우 가 많 습 니 다.최근 에 이동 단 에 인 터 페 이 스 를 만들어 복호화 하 는 것 을 연 구 했 습 니 다.두 가지 방식 을 모 았 습 니 다.
1.des 암호 화,복호화
(1)des 복호화 도구 클래스
DesUtil:
package com.loan.fore.util;

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

/**
 * 
*   : DES   
* 
: *
:1.0 *
ProjectName: loan-utils *
PackageName: com.loan.fore.util *
ClassName: DesUtil *
Date: 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;


/**
*   :
* 
: *
:1.0 *
ProjectName: loan-utils *
PackageName: com.loan.fore.util *
ClassName: Base64 *
Date: 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)컨트롤 러 에서 직접 호출
실 체 를 되 돌려 줍 니 다 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 returnInformation = new HashMap();
	
	public Map getReturnInformation() {
		return returnInformation;
	}

	public MyReturnEntity setReturnInformation(Map returnInformation) {
		this.returnInformation = returnInformation;
		return this;
	}

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

	public MyReturnEntity(Map 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 returnInformation) {
		if (returnInformation == null) {
			return this.setReturnInformation(new HashMap());
		} 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 final MyReturnEntity SUCCESS_RETURN=new MyReturnEntity();

}
암호 화:
@ResponseBody
	@RequestMapping("DES")
	public String test_des() throws Exception{
		
		Map 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 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 는 자바 파 트 밖 에 없어 요.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 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 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 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 복호화 입 니 다.
이동 단 반환 요구 설정

좋은 웹페이지 즐겨찾기