欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

spring+html5实现安全传输随机数字密码键盘

程序员文章站 2024-02-27 18:34:27
随着互联网的飞跃式发展,移动支付已越来越受欢迎并且已成为常态,很多三方支付公司推出了很多支付方式如快捷支付、认证支付、扫码支付等等。快捷支付和认证支付可分为移动app控件和...

随着互联网的飞跃式发展,移动支付已越来越受欢迎并且已成为常态,很多三方支付公司推出了很多支付方式如快捷支付、认证支付、扫码支付等等。快捷支付和认证支付可分为移动app控件和移动html5网页。用户第一次使用快捷支付或认证支付进行支付的时候,需先绑定银行卡。在绑定银行卡的过程中,需要验证银行卡信息。不同银行、不同银行卡验证的要素不一样,有些需要验证四要素,有的需要验证八要素。对于需要验证银行卡的交易密码的情况,怎样保证交易密码的安全不被别人所窃取呢?为了保证交易密码不在传输过程中被窃取,出现了安全传输随机数字密码键盘。

安全传输随机数字密码键盘怎么实现呢?今天给大家详细的介绍安全传输随机数字密码键盘的原理和代码实现。下图是实现的数

字键盘效果:

spring+html5实现安全传输随机数字密码键盘

一、实现原理

用户点击“交易密码”输入框,页面异步向后台发送“获取密码键盘”的请求,后台接收到请求之后随机生成“1234567890与随机密文的对应关系”和“随机密文”和“1234567890图片“的对应关系,然后把它们关系放入dto实例中并放入redis中,最后把随机密文以集合的方式返回到页面,页面js获取到密文集合后以循环的方式向后台请求对应的数字图片流,并展示在页面。

当用户点击数字键盘中的数字图片,就会把图片对应的密文放入到pkey隐藏输入框中,多个数字以逗号隔开,当点击支付的时候,就会把peykey隐藏输入框的值传入到后台,后台从redis中取出“密文”与“1234567890数字“的对应关系,就取出了对应交易密码。

二、具体实现

1).html5页面

页面主要展示密码输入框和支付按钮,需要导入jquery、bootstrap及pwdkey.js等。下面是具体代码:

<%@ page language="java" import="java.util.*" 
 contenttype="text/html; charset=utf-8"%> 
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 
<%@ page pageencoding="utf-8"%> 
<% 
 string path = request.getcontextpath(); 
%> 
<!doctype html public "-//wapforum//dtd xhtml mobile 1.0//en" "http://www.wapforum.org/dtd/xhtml-mobile10.dtd"> 
<html> 
<head> 
<meta name="viewport" 
 content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0" /> 
<meta http-equiv="cache-control" content="private,must-revalidate"> 
<link rel="stylesheet" 
 href='<c:url value="/js/bootstrap/css/bootstrap.min.css"/>'> 
<!-- 引入js脚本文件 begin --> 
<!--[if lt ie 9]> 
 <script src="http://cdn.bootcss.com/html5shiv/3.7.2/html5shiv.min.js"></script> 
 <script src="http://cdn.bootcss.com/respond.js/1.4.2/respond.min.js"></script> 
<![endif]--> 
<script src="<c:url value="/js/jquery/jquery-1.10.0.min.js"/>"></script> 
<script src="<c:url value="/js/bootstrap/js/bootstrap.min.js"/>"></script> 
<script type="text/javascript" src="<c:url value="/js/pwdkey.js"/>"></script> 
<title>xxx付款</title> 
<style type="text/css"> 
.input-out { 
 padding-top: 20px; 
} 
.btn-out { 
 margin:30px 10px; 
} 
.btn-out button { 
 width: 100%; 
 background: #5cacee; 
 border: #5cacee; 
 color: #fff; 
 height: 50px; 
 border-radius: 3px; 
 font-size: 18px; 
 font-family: "microsoft yahei", "??????", simhei, tahoma, arial, helvetica, stheiti; 
} 
.keyboard { 
 background: #fff; 
} 
.keyboard table { 
 width:100%; 
 text-align:center; 
} 
.keyboard table td { 
 padding: 15px; 
} 
.keyboard table a, 
.keyboard table a:hover, 
.keyboard table a:focus { 
 color: #333; 
 text-decoration: none; 
} 
.input-out label { 
 color:#d2d1d1; 
 font-weight: normal; 
 font-size: 16px; 
} 
.bottom { 
 color:#888888; 
 margin-bottom: 15px; 
 text-align:center; 
 margin-top:100px; 
} 
.bottom a { 
 color:#888888; 
} 
.bottom img { 
 vertical-align: middle; 
 width: 18px; 
} 
</style> 
</head> 
<body> 
 <form action="<%=path%>/pay" method="post" id="from"> 
  <div class="content"> 
    <div class="input-out pass-label" style="border-bottom: 1px solid #ddd;padding-left: 12px;" random="2321321321" path="<%=path%>" > 
     <label id="pin" >交易密码</label> 
    </div> 
  </div> 
   
  <div class="btn-out"> 
   <button type="button" class="btn btn-default" ontouchstart="check();" id="pay">支付</button> 
  </div> 
 </form> 
 <div class="bottom" id="bottom-out"> 
  <img src="<c:url value="/images/phone.png"/>" /> 
  <span>客服电话:4000-xxx-xxx</span> 
 </div> 
 <!-- jianpan--> 
 <div class="keyboard" style="display:none;" id="keyboard"> 
  <table class="table-bordered" id="key_table"> 
  </table> 
 </div> 
</body> 
</html> 

2).密码键盘js代码

用户点击“交易密码”输入框,页面异步向后台发送“获取密码键盘”的请求,后台接收到请求之后把随机密文以集合的方式返回到页面,页面js获取到密文集合后以循环的方式向后台请求对应的数字图片流并展示在页面。具体代码如下:

$(document).ready( 
  function() { 
   $("#pay").removeattr("disabled"); 
   $("input").click(function() { 
    hidekey(); 
   }); 
   $("button").click(function() { 
    hidekey(); 
   }); 
   $(".pass-label").click(function() { 
     
    var rangdom = $(this).attr("random"); 
    var path = $(this).attr("path"); 
    pwdkey(this, rangdom, path); 
   }); 
   window.addeventlistener( 
     "onorientationchange" in window ? "orientationchange" 
       : "resize", hengshuping, false); 
  }); 
function hengshuping() { 
 
 if (window.orientation == 180 || window.orientation == 0) { 
  $("div#keyboard td").each(function() { 
   $(this).css("padding", "15px"); 
  }); 
 } 
 if (window.orientation == 90 || window.orientation == -90) { 
  $("div#keyboard td").each(function() { 
   $(this).css("padding", "8px"); 
  }); 
 
 } 
 window.scrollto(0, $(".pass-label").offset().top); 
} 
function pwdkey(obj, rangdom, path) { 
 $('.keyboard').addclass("navbar-fixed-bottom"); 
 $('.keyboard').css({ 
  "z-index" : "9999" 
 }); 
 if (rangdom == null || rangdom == "") { 
  alert("无法加载密码键盘,请刷新后重试!"); 
  return false; 
 } 
 if ($("#pkey").val() == null || $("#pkey").val() == "undefined") { 
  $(obj) 
    .html( 
      $(obj).html() 
        + '<input type="hidden" name="pkey" id="pkey" />'); 
 } 
 $("#pin").html("交易密码"); 
 setcssnomal(); 
 $("#pkey").val(""); 
 $ 
   .ajax({ 
    type : 'post', 
    url : path + "/common/pkey.do", 
    cache : false, 
    async : false, 
    data : { 
     rangdom : rangdom 
    }, 
    success : function(data) { 
     if (data == null || data == "" || data == "undefined" 
       || data.length != 10) { 
      alert("无法加载密码键盘,请刷新后重试!"); 
      return false; 
     } else { 
      var key_table = $("#key_table"); 
      key_table.html(""); 
      var content = '<tr>'; 
      for (var i = 0; i < 12; i++) { 
       if ((i + 1) % 3 == 0 && i != 0 && i <= 5) { 
        content = content 
          + '<td style="width:33%;" key="' 
          + data[i] 
          + '" ontouchstart="return ontouch(this);"><img src="' 
          + path 
          + '/common/getkey.do?key=' 
          + data[i] 
          + '&rangdom=' 
          + rangdom 
          + '" style="height:20px;" id="key_img"/></td></tr><tr>'; 
       } else if (i <= 7) { 
        content = content 
          + '<td style="width:33%;" key="' 
          + data[i] 
          + '" ontouchstart="return ontouch(this);"><img src="' 
          + path 
          + '/common/getkey.do?key=' 
          + data[i] 
          + '&rangdom=' 
          + rangdom 
          + '" style="height:20px;" id="key_img"/></td>'; 
       } else if (i == 8) { 
        content = content 
          + '<td style="width:33%;" ontouchstart="return deleteone();"><img src="' 
          + path 
          + '/images/keys/delete.png" style="height:20px;" id="key_img"/></td>' 
          + '</tr><tr>'; 
       } else if (i < 11) { 
        content = content 
          + '<td style="width:33%;" key="' 
          + data[i - 1] 
          + '" ontouchstart="return ontouch(this);"><img src="' 
          + path 
          + '/common/getkey.do?key=' 
          + data[i - 1] 
          + '&rangdom=' 
          + rangdom 
          + '" style="height:20px;" id="key_img"/></td>'; 
       } else { 
        content = content 
          + '<td style="width:33%;" onclick="return _ok();"><img src="' 
          + path 
          + '/images/keys/ok.png" style="height:20px;" id="key_img"/></td>' 
          + '</tr>'; 
       } 
 
      } 
      key_table.html(content); 
 
      settimeout(function() { 
       $("#keyboard").show(); 
      }, 600); 
      hengshuping(); 
     } 
 
    }, 
    error : function() { 
     alert("无法加载键盘,请刷新后重试!"); 
    } 
   }); 
} 
function ontouch(obj) { 
 var pkey = $("#pkey").val(); 
 var key = $(obj).attr("key"); 
 if (pkey == "") { 
  $("#pin").html(""); 
 } 
 var content = $("#pin").html(); 
 if (content != "" && content.length >= 6) { 
  return false; 
 } 
 if (pkey != "") { 
  key = "," + key; 
 } 
 pkey = pkey + key; 
 $("#pkey").val(pkey); 
 $("#pin").append("*"); 
 setcsskey(); 
 
} 
function deleteone() { 
 var pkey = $("#pkey").val() + ""; 
 if (pkey == "") { 
  return false; 
 } 
 var local = pkey.lastindexof(","); 
 if (local == -1) { 
 
  $("#pkey").val(""); 
  $("#pin").html("交易密码"); 
  setcssnomal(); 
 } else { 
  pkey = pkey.substring(0, local - 1); 
  var content = $("#pin").html(); 
  content = content.substring(0, content.length - 1); 
  $("#pkey").val(pkey); 
  $("#pin").html(content); 
 } 
 
} 
function _ok() { 
 $("#key_table").html(""); 
 $("#keyboard").hide(); 
} 
function showkey() { 
 $("#keyboard").show(); 
} 
function hidekey() { 
 $("#key_table").html(""); 
 $("#keyboard").hide(); 
} 
function setcsskey() { 
 $("#pin").css({ 
  "font-size" : "18px", 
  "color" : "#030303", 
  "font-weight" : "normal", 
  "letter-spacing" : "1px" 
 }); 
} 
function setcssnomal() { 
 $("#pin").css({ 
  "font-size" : "16px", 
  "color" : "#d2d1d1", 
  "font-weight" : "normal" 
 }); 
} 

3).获取密码键盘后台方法

该方法将随机生成“1234567890与随机密文的对应关系”和“随机密文”和“1234567890图片“的对应关系,然后把它们关系放入dto实例中并放入redis中,最后把随机密文以集合的方式返回到页面。具体代码如下:

获取密码键盘:

/** 
  * 
  * @description: 获取密码键盘 
  * @param request 
  * @param rangdom 随机字符串 
  * @return 
  * 
  */ 
 @suppresswarnings("unchecked") 
 @responsebody 
 @requestmapping(value = "common/pkey.do", method = requestmethod.post) 
 public object digitkeyboard(httpservletrequest request, string rangdom) { 
  log.info("[获取密码键盘digitkeyboard][parames:outorderid=" + rangdom + "]"); 
  try { 
   if (stringutils.isblank(rangdom)) { 
    return ""; 
   } 
   pwdkeydto pwdkey = pwdkeyutils.digitkeyboard(); 
   redisutil.set("pwdkey_" + rangdom, pwdkey, 
     redisutil.getdigitkeyimeout()); 
   return pwdkey.getrundomkeys(); 
  } catch (exception e) { 
   log.error("[获取密码键盘digitkeyboard][error:{}",e); 
  } 
  return ""; 
 } 

密码pwdkeydto:  

/** 
 * 
 * @classname: pwdkeydto 
 * @description: 密码映射dto 
 * @author xxxx <a target="_blank" href="mailto:xxxx@xxx.com" rel="external nofollow" >xxxx@xxx.com</a> 
 * @date 2015年6月25日 上午11:01:20 
 * 
 */ 
public class pwdkeydto implements serializable{ 
 /** 
  描述*/ 
 private static final long serialversionuid = 1l; 
 private list<string> rundomkeys;// 随机keys 
 private map<string, string> valuekeymaps;// 密文和明文映射 
 private map<string, string> imgkeymaps;// 密文和明文映射 
 
 public pwdkeydto() { 
  super(); 
  // todo auto-generated constructor stub 
 } 
 
 public list<string> getrundomkeys() { 
  return rundomkeys; 
 } 
 
 public void setrundomkeys(list<string> rundomkeys) { 
  this.rundomkeys = rundomkeys; 
 } 
 
 public pwdkeydto(list<string> rundomkeys, map<string, string> valuekeymaps, 
   map<string, string> imgkeymaps) { 
  super(); 
  this.rundomkeys = rundomkeys; 
  this.valuekeymaps = valuekeymaps; 
  this.imgkeymaps = imgkeymaps; 
 } 
 
 public map<string, string> getvaluekeymaps() { 
  return valuekeymaps; 
 } 
 
 public void setvaluekeymaps(map<string, string> valuekeymaps) { 
  this.valuekeymaps = valuekeymaps; 
 } 
 
 public map<string, string> getimgkeymaps() { 
  return imgkeymaps; 
 } 
 
 public void setimgkeymaps(map<string, string> imgkeymaps) { 
  this.imgkeymaps = imgkeymaps; 
 } 
 
} 

生成键盘的pwdkeyutils工具类:

/** 
 * 
 * @classname: pwdkeyutils 
 * @description: 密码处理工具类 
 * @author xxxx <a target="_blank" href="mailto:xxxx@xxxx.com" rel="external nofollow" >xxxx@xxxx.com</a> 
 * @date 2015年6月25日 上午11:03:24 
 * 
 */ 
public class pwdkeyutils { 
 private final static map<string, string> imagesvaluemap; 
 
 /** 
  * 
  * @description: 获取密码键盘映射关系 
  * @param imagesvaluemap 
  * @return 
  * 
  */ 
 static { 
  imagesvaluemap = new hashmap<string, string>(); 
  imagesvaluemap.put("0", 
    "images/keys/0.png"); 
  imagesvaluemap.put("1", 
    "images/keys/1.png"); 
  imagesvaluemap.put("2", 
    "images/keys/2.png"); 
  imagesvaluemap.put("3", 
    "images/keys/3.png"); 
  imagesvaluemap.put("4", 
    "images/keys/4.png"); 
  imagesvaluemap.put("5", 
    "images/keys/5.png"); 
  imagesvaluemap.put("6", 
    "images/keys/6.png"); 
  imagesvaluemap.put("7", 
    "images/keys/7.png"); 
  imagesvaluemap.put("8", 
    "images/keys/8.png"); 
  imagesvaluemap.put("9", 
    "images/keys/9.png"); 
 } 
 
 public static pwdkeydto digitkeyboard() { 
  list<string> rundomkeys = new arraylist<string>();// 随机key映射 
  map<string, string> valuekeys = new hashmap<string, string>();// 密文和明文映射 
  map<string, string> imgkeymaps = new hashmap<string, string>();// 密文和图片映射 
  list<string> keys = new arraylist<string>(); 
  for (int i = 0; i < 10; i++) { 
   keys.add(i + ""); 
  } 
  for (int i = 0; i < 10; i++) { 
   random r = new random(); 
   int index = r.nextint(keys.size()); 
   string key = keys.get(index); 
   keys.remove(index); 
   string randomkey = randomkey(24); 
   rundomkeys.add(randomkey); 
   valuekeys.put(randomkey, key); 
   imgkeymaps.put(randomkey, imagesvaluemap.get(key)); 
  } 
  pwdkeydto dto = new pwdkeydto(rundomkeys, valuekeys, imgkeymaps); 
  return dto; 
 } 
 
 /** 
  * 
  * @description:获取动态key 
  * @param num 
  *   key位数 
  * @return 
  * 
  */ 
 public static string randomkey(int num) { 
  stringbuffer sb = new stringbuffer(""); 
  char[] chars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 
    'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 
    'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 
    'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 
    'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 
    'x', 'y', 'z' }; 
  for (int i = 0; i < num; i++) { 
   int id = (int) math.ceil(math.random() * 60); 
   sb.append(chars[id]); 
  } 
  return sb.tostring(); 
 } 
 
 /** 
  * 
  * @description:解密pin 
  * @param request 
  * @param pin 
  * @return 
  * 
  */ 
 public static string decryptpindata(httpservletrequest request, 
   string ciphertextpin) throws exception { 
  if (stringutils.isnotblank(ciphertextpin)) { 
   map<string, string> valuekeys = (map<string, string>) request 
     .getsession().getattribute("valuekeys"); 
   if (valuekeys == null || valuekeys.size() != 10) { 
    throw new exception(); 
   } 
   string[] ciphertextpins = ciphertextpin.split(","); 
   stringbuffer sb = new stringbuffer(""); 
   for (string ctpin : ciphertextpins) { 
    sb.append(valuekeys.get(ctpin)); 
   } 
  } 
  return null; 
 } 
} 

4).获取图片流后台方法

用户页面获取到随机密文集合后以循环的方式向后台请求该方法获取对应的数字图片流。具体代码如下:

/** 
  * 获取key图片 
  * 
  * @throws exception 
  */ 
 @requestmapping(value = "/common/getkey.do", method = requestmethod.get) 
 public void getkey(string key, string rangdom, httpservletrequest request, 
   httpservletresponse response) throws exception { 
  log.info("[获取密码键盘key(getkey)][parms:key=" + key + "]"); 
  pwdkeydto pwdkey = (pwdkeydto) redisutil.get("pwdkey_" + rangdom); 
  if (pwdkey == null || pwdkey.getimgkeymaps() == null) { 
   log.error("获取图片[getkey]:未获取到对应的键盘的映射关系"); 
   throw new exception(); 
  } 
  map<string, string> imagekeys = pwdkey.getimgkeymaps(); 
  string path = imagekeys.get(key); 
  string rootpath = request.getsession().getservletcontext() 
    .getrealpath("/"); 
  path = rootpath + path; 
  log.info("[获取密码键盘key(getkey)][path=" + path + "]"); 
  if (stringutils.isnotempty(path)) { 
   try { 
    inputstream fis = new fileinputstream(new file(path)); 
    bufferedinputstream bis = new bufferedinputstream(fis); 
    outputstream fos = response.getoutputstream(); 
    bufferedoutputstream bos = new bufferedoutputstream(fos); 
    string filename = "image."; 
    string[] strs = path.split("\\."); 
    filename = filename + strs[strs.length - 1]; 
    setfiledownloadheader(request, response, filename); 
    int byteread = 0; 
    byte[] buffer = new byte[8192]; 
    while ((byteread = bis.read(buffer, 0, 8192)) != -1) { 
     bos.write(buffer, 0, byteread); 
    } 
    bos.flush(); 
    fis.close(); 
    bis.close(); 
    fos.close(); 
    bos.close(); 
 
   } catch (exception e) { 
    log.error("获取图片[path:" + path + "])失败:" + e.tostring(), e); 
   } 
  } 
 } 



5).用户支付

当用户点击数字键盘中的数字图片,就会把图片对应的密文放入到pkey隐藏输入框中,多个数字以逗号隔开,当点击支付的时候,就会把peykey隐藏输入框的值传入到后台,后台从redis中取出“密文”与“1234567890数字“的对应关系,就取出了对应交易密码。具体代码如下:

页面提交支付js:

function check() 
{ 
 hidekey(); 
 var pin=""; 
  
   
  pin=$("#pkey").val(); 
  if(pin==""||pin==undefined) 
  { 
   bool=false; 
   alert("请输入交易密码"); 
    
   return false; 
  }else 
  { 
   var keys=pin.split(","); 
   if(keys.length!=6) 
   { 
    alert("请输入6位交易密码"); 
     
    return false; 
   } 
  } 
  $.ajax({ 
   type : 'post', 
   url : "test/pay.do", 
   data : { 
    random:"2321321321", 
    pin:pin 
   }, 
   cache : false, 
   success : function(data) { 
    if(data.success) 
     { 
      alert(data.message); 
     }else{ 
       
     } 
     
   }, 
   error : function(){ 
     
    alert("系统异常,请重试!"); 
   } 
  }); 
} 

后台解析密文方法:

/** 
  * 
  * @description: 支付 
  * @param pin 交易密码密文 
  * @param random 随机码 
  * @return 
  * 
  */ 
 @responsebody 
 @requestmapping(value = "/test/pay.do", method = requestmethod.post) 
 public object pay(string pin,string random, httpservletrequest request) { 
  try { 
   log.info("[支付(pay)][params:pin=" + pin + ",random="+random+"]"); 
   if (stringutils.isnotblank(pin)) { 
    stringbuffer sb = new stringbuffer(""); 
    pwdkeydto pwdkey = (pwdkeydto) redisutil.get("pwdkey_" + random); 
    if (pwdkey == null || pwdkey.getvaluekeymaps() == null) { 
     return new result(false,"密码键盘已失效,请重新输入密码"); 
    } 
    map<string, string> valuekeys = pwdkey.getvaluekeymaps(); 
    string[] pins = pin.split(","); 
    if (pins.length != 6) { 
     return new result(false,"交易密码位数不对"); 
    } 
    for (string pinkey : pins) { 
     string val = valuekeys.get(pinkey); 
     if (stringutils.isblank(val)) { 
      return new result(false,"密码键盘已失效,请重新输入密码"); 
     } 
     sb.append(val); 
    } 
    /** 
     * sb.tostring()就是明文交易密码,下面就是具体的支付操作 
     */ 
     
   } 
   return new result(true, "成功"); 
   
  } catch (exception e) { 
   log.error("[支付(pay)][error:{}]",e); 
   return new result(false, "支付异常,请重试!"); 
  } 
 
 } 

以上就是对使用spring+html5实现安全传输随机数字密码键盘的介绍和代码实现,大家有什么疑问或设计的不合理的地方可以一起讨论。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。