使用Spring MVC搭建参数加解密服务

1.编写Service接口层

package com.csj2018.o2o.service;

public interface YYGHParamService {
	String encrypt(String param,String device) throws Exception;
	String decrypt(String param,String device) throws Exception;
}

2.实现Service接口实现层

package com.csj2018.o2o.service.impl;

import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

import org.springframework.stereotype.Service;

import com.csj2018.o2o.service.YYGHParamService;
import com.csj2018.o2o.util.DESUtil;
@Service
public class YYGHParamServiceImpl implements YYGHParamService{
	
	@Override
	public String encrypt(String param,String device) throws Exception  {
		String url;
		if(device.equalsIgnoreCase("android")) {
			//android
			System.out.println("android加密");
            url = DESUtil.encryptDES(param);
		}else if(device.equalsIgnoreCase("ios")) {
			//iOS
			System.out.println("iOS加密");
            url = URLEncoder.encode(DESUtil.encryptDES(param),"utf-8");
		}else {
			//js
			System.out.println("URL编码");
            url = URLEncoder.encode(param,"utf-8");
		}
		return url;
	}
	@Override
	public String decrypt(String param,String device) throws Exception {
		String url;
		String str;
		if(device.equalsIgnoreCase("android")) {
			//android
			System.out.println("安卓解密");

            url = DESUtil.decryptDES(param);
		}else if(device.equalsIgnoreCase("ios")) {
			//iOS
			str = URLDecoder.decode(param, "UTF-8");
            url = DESUtil.decryptDES(str);
            System.out.println("iOS解密");
		}else {
			//js
			url = URLDecoder.decode(param,"utf-8");
            System.out.println("URL解码");
		}
		return url;
	}
}

单元测试

package com.csj2018.o2o.service;

import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.csj2018.o2o.BaseTest;
import com.csj2018.o2o.service.YYGHParamService;
import com.csj2018.o2o.service.impl.YYGHParamServiceImpl;


public class YYGHParamServiceTest extends BaseTest{
	
	@Autowired
	private YYGHParamService paramService;
	
	@Test
	public void testdecrpyt() {
		//解密
		try {
			String encypted = "u%2BTLvOADdiYXfbaCgtjeYjLQvRncV%2BTZuopJiVKLlu%2BwrMwdOy%2FaBIShXR3IAMFhy1JFV8Yui5HGrd7%2BEeOM7c3%2Bb9akoIO%2F%2BzzxBc8y%2F224C%2FWGOGiFh4I1RBrRHUYhFo292BpqBBiR0F%2BX4f%2FHhsH9Hw7IKZSFOeP%2FGL3BzSAkGSqk215Pqmj8RlYK3oZidEhS31VwT4CrkeyJlc18i7MzJWHbBGjACHFKfMsBEpIq9uzypJUEH1IyR9z51OpbTFG9skDZ6YZedVOD2%2F%2FWb%2FPJOaZ96f8Mref0d3ejXJ5ZooBeNXWvGA%3D%3D";
			String result = paramService.decrypt(encypted, "android");
			System.out.println(result);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@Test
	public void testencrpyt() {
        //加密
		String param = "{\"siteRequests\":[{\"siteNo\":\"app_ask_banner\"},{\"siteNo\":\"app_expert_ask_list_ad\"}]}";
		try {
			String result = paramService.encrypt(param, "android");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

3.编写Controller层

package com.csj2018.o2o.web.shopadmin;

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

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csj2018.o2o.entity.Area;
import com.csj2018.o2o.entity.Param;
import com.csj2018.o2o.service.AreaService;
import com.csj2018.o2o.service.YYGHParamService;
import com.csj2018.o2o.util.HttpServletRequestUtil;
import com.csj2018.o2o.web.superadmin.AreaController;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller
@RequestMapping("/superadmin")
public class Getparam {
	Logger logger = LoggerFactory.getLogger(AreaController.class);
    @Autowired
    private YYGHParamService paramService;
    /**
     * 解密
     * @param request 
     * @return 
     */
    @RequestMapping(value="/decrypt", method=RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> getYYGHParamDecrypt(@RequestBody Map<String,String> request){
    	Map<String,Object> modelMap = new HashMap<>();
    	try {
    		String param = request.get("param");
    		String device = request.get("device");
    		String decrypt = paramService.decrypt(param,device);
    		modelMap.put("decrypt", decrypt);
    		logger.info("->解密内容:"+param);
    		logger.info("->解密结果:"+decrypt);
    		modelMap.put("success", "true");
    		return modelMap;
    	}catch (Exception e) {
    		modelMap.put("success", "false");
    		modelMap.put("errMsg", e.getMessage());
    		return modelMap;
    	}
    }
    /**
     * 加密
     * @param request
     * @return
     */
    @RequestMapping(value="/encrypt", method=RequestMethod.POST)
    @ResponseBody
    private Map<String, Object> getYYGHParamEncrypt(@RequestBody Map<String,String> request){
    	Map<String,Object> modelMap = new HashMap<>();
    	try {
    		String param = request.get("param");
    		String device = request.get("device");
    		String encrypt = paramService.encrypt(param,device);
    		modelMap.put("encrypt", encrypt);
    		logger.info("->加密内容"+param);
    		logger.info("->加密结果:"+encrypt);
    		modelMap.put("success", "true");
    		return modelMap;
    	}catch (Exception e) {
    		modelMap.put("success", "false");
    		modelMap.put("errMsg", e.getMessage());
    		return modelMap;
    	}
    }
}

4.前端实现

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SUI Mobile Demo</title>
<meta name="description"
	content="MSUI: Build mobile apps with simple HTML, CSS, and JS components.">
<meta name="author" content="阿里巴巴国际UED前端">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">

<!-- Google Web Fonts -->

<link rel="stylesheet"
	href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
<link rel="stylesheet"
	href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css">
<!-- <script>
	(function(){
		alert('妈蛋,为什么不能引用js文件?');
	})();
</script> -->
<script>
	//ga
</script>
<script>
	var _hmt = _hmt || [];
	(function() {
		var hm = document.createElement("script");
		hm.src = "//hm.baidu.com/hm.js?ba76f8230db5f616edc89ce066670710";
		var s = document.getElementsByTagName("script")[0];
		s.parentNode.insertBefore(hm, s);
	})();
</script>

</head>
<body>
	<div class="page-group">
		<div id="page-label-input" class="page">
			<header class="bar bar-nav">
				<h1 class="title">参数解密</h1>
			</header>
			<div class="content">
				<div class="list-block">
					<ul>
						<!-- 字符串 -->
						<li>
							<div class="item-content">
								<div class="item-inner">
									<div class="item-title label">待处理的字符串</div>
									<div class="item-input">
										<!-- <input type="text"  placeholder="加密后的字符串"> -->
										<textarea id="param" rows="10" cols="50">我是一个文本框。</textarea>
									</div>
								</div>
							</div>
						</li>
					</ul>
				</div>
				
				<div class="content-block">
					<div class="row">
						<div class="col-35" style="padding-left:100px;">
							<!-- android解密 -->
							<a  href="#" class="button button-big button-fill button-success" id="androidDecrypt">android解密</a>
						</div>
						<div class="col-35" style="padding-left:100px;">
							<!-- iOS解密 -->
							<a href="#" class="button button-big button-fill button-success" id="iosDecrypt">ios解密</a>
						</div>
						<div class="col-35" style="padding-left:100px;">
							<!-- js解密 -->
							<a href="#" class="button button-big button-fill button-success" id="jsDecrypt">js解密</a>
						</div>
						<div class="col-35" style="padding-left:100px;">
							<!-- android解密 -->
							<a  href="#" class="button button-big button-fill button-success" id="androidEncrypt">android加密</a>
						</div>
						<div class="col-35" style="padding-left:100px;">
							<!-- iOS解密 -->
							<a href="#" class="button button-big button-fill button-success" id="iosEncrypt">ios加密</a>
						</div>
						<div class="col-35" style="padding-left:100px;">
							<!-- js解密 -->
							<a href="#" class="button button-big button-fill button-success" id="jsEncrypt">js加密</a>
						</div>
					</div>
				</div>
				<div class="item-content">
					<ul>
						<li>
							<text>解密后的字符串</text>
							<div class="item-inner" id="result" style="word-wrap:break-word;word-break:break-all;padding-left: 5px;padding-right: 5px;width: wrap-content;">
							</div>
						</li>
					</ul>
				</div>				
            </div>
			</div>
		</div>

	</div>
	<script type='text/javascript'
		src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>
	<script type='text/javascript'
		src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script>
	<script type='text/javascript'
		src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>
	<script type='text/javascript'
		src='./resources/js/shop/param.js' charset="utf-8"></script>

</body>
</html>
/**
 * 
 */
$(function(){
	var decryptUrl = '/o2o/superadmin/decrypt';
	var encryptUrl = "/o2o/superadmin/encrypt";
	getShopInitInfo();
	function getShopInitInfo(){
	$('#androidDecrypt').click(function(){
		var formData = {param:$('#param').val(),device:'android'};
		$.ajax({
			url:decryptUrl,
			type:'POST',
			data:JSON.stringify(formData),
			contentType:'application/json',
			processData:false,
			cache:false,
			success:function(data){
				if(data.success){
					$.toast("提交成功!");
					//获取响应内容
//					alert(JSON.stringify(data.decrypt));
					var decrypted = JSON.parse(data.decrypt);
					$('#result').text(JSON.stringify(decrypted));
					//填充
				}else{
					$.toast("提交失败");
					$('#result').text(JSON.stringify(data.errMsg));
				}
			}
		});
	});
	
	$('#iosDecrypt').click(function(){
		var formData = {param:$('#param').val(),device:'ios'};
		$.ajax({
			url:decryptUrl,
			type:'POST',
			data:JSON.stringify(formData),
			contentType:'application/json',
			processData:false,
			cache:false,
			success:function(data){
				if(data.success){
					$.toast("提交成功!");
					//获取响应内容
//					alert(JSON.stringify(data.decrypt));
					var decrypted = JSON.parse(data.decrypt);
					$('#result').text(JSON.stringify(decrypted));
					//填充
				}else{
					$.toast("提交失败");
				}
			}
		});
	});
	
	$('#jsDecrypt').click(function(){
		var formData = {param:$('#param').val(),device:'js'};
		$.ajax({
			url:decryptUrl,
			type:'POST',
			data:JSON.stringify(formData),
			contentType:'application/json',
			processData:false,
			cache:false,
			success:function(data){
				if(data.success){
					$.toast("提交成功!");
					//获取响应内容
//					alert(JSON.stringify(data.decrypt));
					var decrypted = JSON.parse(data.decrypt);
					$('#result').text(JSON.stringify(decrypted));
					//填充
				}else{
					$.toast("提交失败:"+data.errMsg);
				}
			}
		});
	});
	$('#androidEncrypt').click(function(){
		var formData = {param:$('#param').val(),device:'android'};
		$.ajax({
			url:encryptUrl,
			type:'POST',
			data:JSON.stringify(formData),
			contentType:'application/json',
			processData:false,
			cache:false,
			success:function(data){
				if(data.success){
					$.toast("提交成功!");
					//获取响应内容
//					alert(JSON.stringify(data.encrypt));
					$('#result').text(data.encrypt);
					//填充
				}else{
					$.toast("提交失败:"+data.errMsg);
					$('#result').text(JSON.stringify(data.errMsg));
				}
			}
		});
	});
	
	$('#iosEncrypt').click(function(){
		var formData = {param:$('#param').val(),device:'ios'};
		$.ajax({
			url:encryptUrl,
			type:'POST',
			data:JSON.stringify(formData),
			contentType:'application/json',
			processData:false,
			cache:false,
			success:function(data){
				if(data.success){
					$.toast("提交成功!");
					//获取响应内容
//					alert(JSON.stringify(data.encrypt));
					$('#result').text(data.encrypt);
					//填充
				}else{
					$.toast("提交失败:"+data.errMsg);
				}
			}
		});
	});
	
	$('#jsEncrypt').click(function(){
		var formData = {param:$('#param').val(),device:'js'};
		$.ajax({
			url:encryptUrl,
			type:'POST',
			data:JSON.stringify(formData),
			contentType:'application/json',
			processData:false,
			cache:false,
			success:function(data){
				if(data.success){
					$.toast("提交成功!");
					//获取响应内容
//					alert(JSON.stringify(data.encrypt));
					$('#result').text(data.encrypt);
					//填充
				}else{
					$.toast("提交失败:"+data.errMsg);
				}
			}
		});
	});
	}
})
posted on 2019-12-30 19:27  singleSpace  阅读(730)  评论(0编辑  收藏  举报