当前位置:   article > 正文

RSA加密传输用户名密码--web_cipher.getinstance("rsa")

cipher.getinstance("rsa")

Web登录时存在明文传输用户名和密码的安全漏洞,要求是:web客户端通信的数据包中不能包含明文的账号和密码,建议采用RSA加密算法解决此漏洞。

1、在WEB系统中编写工具类如下:

  1. package com.gsww.jup.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.ObjectInputStream;
  6. import java.io.ObjectOutputStream;
  7. import java.math.BigInteger;
  8. import java.security.KeyFactory;
  9. import java.security.KeyPair;
  10. import java.security.KeyPairGenerator;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.security.PrivateKey;
  13. import java.security.PublicKey;
  14. import java.security.SecureRandom;
  15. import java.security.interfaces.RSAPrivateKey;
  16. import java.security.interfaces.RSAPublicKey;
  17. import java.security.spec.InvalidKeySpecException;
  18. import java.security.spec.RSAPrivateKeySpec;
  19. import java.security.spec.RSAPublicKeySpec;
  20. import javax.crypto.Cipher;
  21. public class RSAUtil {
  22. private static String RSAKeyStore = "RSAKey.txt";
  23. /**
  24. * 生成秘钥对
  25. * @return
  26. * @throws Exception
  27. */
  28. public static KeyPair generateKeyPair() throws Exception {
  29. try {
  30. KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA",
  31. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  32. final int KEY_SIZE = 1024;// 没什么好说的了,这个值关系到块加密的大小,可以更改,但是不要太大,否则效率会低
  33. keyPairGen.initialize(KEY_SIZE, new SecureRandom());
  34. KeyPair keyPair = keyPairGen.generateKeyPair();
  35. System.out.println(keyPair.getPrivate());
  36. System.out.println(keyPair.getPublic());
  37. saveKeyPair(keyPair);
  38. return keyPair;
  39. } catch (Exception e) {
  40. throw new Exception(e.getMessage());
  41. }
  42. }
  43. public static KeyPair getKeyPair() throws Exception {
  44. FileInputStream fis = new FileInputStream(RSAKeyStore);
  45. ObjectInputStream oos = new ObjectInputStream(fis);
  46. KeyPair kp = (KeyPair) oos.readObject();
  47. oos.close();
  48. fis.close();
  49. return kp;
  50. }
  51. public static void saveKeyPair(KeyPair kp) throws Exception {
  52. FileOutputStream fos = new FileOutputStream(RSAKeyStore);
  53. ObjectOutputStream oos = new ObjectOutputStream(fos);
  54. oos.writeObject(kp);
  55. oos.close();
  56. fos.close();
  57. }
  58. public static RSAPublicKey generateRSAPublicKey(byte[] modulus, byte[] publicExponent) throws Exception {
  59. KeyFactory keyFac = null;
  60. try {
  61. keyFac = KeyFactory.getInstance("RSA",
  62. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  63. } catch (NoSuchAlgorithmException ex) {
  64. throw new Exception(ex.getMessage());
  65. }
  66. RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(new BigInteger(
  67. modulus), new BigInteger(publicExponent));
  68. try {
  69. return (RSAPublicKey) keyFac.generatePublic(pubKeySpec);
  70. } catch (InvalidKeySpecException ex) {
  71. throw new Exception(ex.getMessage());
  72. }
  73. }
  74. public static RSAPrivateKey generateRSAPrivateKey(byte[] modulus,
  75. byte[] privateExponent) throws Exception {
  76. KeyFactory keyFac = null;
  77. try {
  78. keyFac = KeyFactory.getInstance("RSA",
  79. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  80. } catch (NoSuchAlgorithmException ex) {
  81. throw new Exception(ex.getMessage());
  82. }
  83. RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(new BigInteger(
  84. modulus), new BigInteger(privateExponent));
  85. try {
  86. return (RSAPrivateKey) keyFac.generatePrivate(priKeySpec);
  87. } catch (InvalidKeySpecException ex) {
  88. throw new Exception(ex.getMessage());
  89. }
  90. }
  91. public static byte[] encrypt(PublicKey pk, byte[] data) throws Exception {
  92. try {
  93. Cipher cipher = Cipher.getInstance("RSA",
  94. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  95. cipher.init(Cipher.ENCRYPT_MODE, pk);
  96. int blockSize = cipher.getBlockSize();// 获得加密块大小,如:加密前数据为128个byte,而key_size=1024
  97. // 加密块大小为127
  98. // byte,加密后为128个byte;因此共有2个加密块,第一个127
  99. // byte第二个为1个byte
  100. int outputSize = cipher.getOutputSize(data.length);// 获得加密块加密后块大小
  101. int leavedSize = data.length % blockSize;
  102. int blocksSize = leavedSize != 0 ? data.length / blockSize + 1
  103. : data.length / blockSize;
  104. byte[] raw = new byte[outputSize * blocksSize];
  105. int i = 0;
  106. while (data.length - i * blockSize > 0) {
  107. if (data.length - i * blockSize > blockSize)
  108. cipher.doFinal(data, i * blockSize, blockSize, raw, i
  109. * outputSize);
  110. else
  111. cipher.doFinal(data, i * blockSize, data.length - i
  112. * blockSize, raw, i * outputSize);
  113. // 这里面doUpdate方法不可用,查看源代码后发现每次doUpdate后并没有什么实际动作除了把byte[]放到
  114. // ByteArrayOutputStream中,而最后doFinal的时候才将所有的byte[]进行加密,可是到了此时加密块大小很可能已经超出了
  115. // OutputSize所以只好用dofinal方法。
  116. i++;
  117. }
  118. return raw;
  119. } catch (Exception e) {
  120. throw new Exception(e.getMessage());
  121. }
  122. }
  123. public static byte[] decrypt(PrivateKey pk, byte[] raw) throws Exception {
  124. try {
  125. Cipher cipher = Cipher.getInstance("RSA",
  126. new org.bouncycastle.jce.provider.BouncyCastleProvider());
  127. cipher.init(cipher.DECRYPT_MODE, pk);
  128. int blockSize = cipher.getBlockSize();
  129. ByteArrayOutputStream bout = new ByteArrayOutputStream(64);
  130. int j = 0;
  131. while (raw.length - j * blockSize > 0) {
  132. bout.write(cipher.doFinal(raw, j * blockSize, blockSize));
  133. j++;
  134. }
  135. return bout.toByteArray();
  136. } catch (Exception e) {
  137. throw new Exception(e.getMessage());
  138. }
  139. }
  140. }
该类属于工具类,提供加密解密的基础方法。该类用到第三方jar包,需要在pom文件中增加如下配置:
  1. <dependency>
  2. <groupId>org.bouncycastle</groupId>
  3. <artifactId>bcprov-jdk16</artifactId>
  4. <version>1.46</version>
  5. </dependency>
2、为了较小的影响现有业务,建立单独的控制器(可以是Servlet,JSP,springmvc的Controller,struts2的action等),用于将生成公钥,私钥,并可以将公钥返回至浏览器,用于JS加密。实例代码如下:

  1. package com.gsww.jup.controller.sys;
  2. import java.security.KeyPair;
  3. import java.security.interfaces.RSAPrivateKey;
  4. import java.security.interfaces.RSAPublicKey;
  5. import java.util.HashMap;
  6. import java.util.List;
  7. import java.util.Map;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import org.codehaus.jackson.map.ObjectMapper;
  11. import org.slf4j.Logger;
  12. import org.slf4j.LoggerFactory;
  13. import org.springframework.beans.factory.annotation.Autowired;
  14. import org.springframework.stereotype.Controller;
  15. import org.springframework.ui.Model;
  16. import org.springframework.web.bind.annotation.RequestMapping;
  17. import org.springframework.web.bind.annotation.RequestMethod;
  18. import org.springframework.web.bind.annotation.ResponseBody;
  19. import com.gsww.jup.controller.BaseController;
  20. import com.gsww.jup.entity.sys.SysOperator;
  21. import com.gsww.jup.service.sys.SysOperatorService;
  22. import com.gsww.jup.util.RSAUtil;
  23. @Controller
  24. @RequestMapping(value = "/sys/mybatis")
  25. public class MybatisController extends BaseController{
  26. private static Logger logger = LoggerFactory.getLogger(MybatisController.class);
  27. @Autowired
  28. private SysOperatorService sysOperatorService;
  29. @RequestMapping(value = "/show", method = RequestMethod.POST)
  30. @ResponseBody
  31. public List<SysOperator> accountView(String userAcctId,Model model,HttpServletRequest request,HttpServletResponse response) throws Exception {
  32. List<SysOperator> list=sysOperatorService.findList(null);
  33. SysOperator sysOperator=sysOperatorService.findByOperatorId("1");
  34. return list;
  35. }
  36. @RequestMapping(value = "/getkey")
  37. @ResponseBody
  38. public Object getPublicKey(HttpServletRequest request)throws Exception{
  39. Map<String,String> result = new HashMap<String,String>();
  40. KeyPair kp = RSAUtil.generateKeyPair();
  41. RSAPublicKey pubk = (RSAPublicKey) kp.getPublic();// 生成公钥
  42. RSAPrivateKey prik = (RSAPrivateKey) kp.getPrivate();// 生成私钥
  43. String publicKeyExponent = pubk.getPublicExponent().toString(16);// 16进制
  44. String publicKeyModulus = pubk.getModulus().toString(16);// 16进制
  45. request.getSession().setAttribute("prik", prik);
  46. result.put("pubexponent", publicKeyExponent);
  47. result.put("pubmodules", publicKeyModulus);
  48. return result;
  49. }
  50. }
说明,该被需要在过滤器中忽略,因为在登录之前要调用该方法。

3、登录页面,在完成非空校验后,以Ajax的方式从后台获取公钥,并对密码进行加密,将加密的数据通过登录方法提交至后台。
以公司JUP平台为例,改造如下:

  1. <!DOCTYPE html>
  2. <%@ page contentType="text/html;charset=UTF-8"%>
  3. <html>
  4. <head>
  5. <meta charset="utf-8">
  6. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  7. <meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no">
  8. <title>甘肃万维JAVA统一开发平台</title>
  9. <link rel="stylesheet" href="res/skin/default/css/login-jup.css">
  10. </head>
  11. <body>
  12. <div class="login-warp">
  13. <div class="main">
  14. <div class="logo"></div>
  15. <div class="login-form">
  16. <form id="login-form">
  17. <div class="form-title">甘肃万维JAVA统一开发平台 </div>
  18. <ul>
  19. <li>
  20. <div class="input-content">
  21. <span class="icon uname"></span>
  22. <input type="text" class="input " id="userName" name="userName" placeholder="请输入您的帐号" value="admin">
  23. </div>
  24. </li>
  25. <li>
  26. <div class="input-content">
  27. <span class="icon upwd"></span>
  28. <input type="password" class="input " id="passWord" name="passWord" placeholder="请输入您的密码" value="111111">
  29. </div>
  30. </li>
  31. <li>
  32. <div class="input-content yzm-input">
  33. <span class="icon uyzm"></span>
  34. <input type="text" class="input input-yzm" name="kaptcha" id="kaptcha" placeholder="请输入验证码" >
  35. </div>
  36. <div class="input-verificationCode yzm-img">
  37. <img style="cursor:pointer;" id="kaptchaImage" src="kaptcha/image" title="看不清,点击换一张" />
  38. </div>
  39. </li>
  40. <li>
  41. <input class="input-submit" type="submit" name="" value="登录" />
  42. </li>
  43. </ul>
  44. </form>
  45. </div>
  46. </div>
  47. <div class="footer">
  48. <p>版权所有:甘肃万维信息技术有限责任公司</p>
  49. <p> (c)2015 You company name.All rights reserve</p>
  50. </div>
  51. </div>
  52. <script type="text/javascript" src="res/skin/default/js/jquery-1.8.3.min.js"></script>
  53. <script type="text/javascript" src="res/skin/default/plugin/validate/jquery.validate.js"></script>
  54. <script type="text/javascript" src="res/skin/default/plugin/validate/jquery.validate.extension.js"></script>
  55. <script type="text/javascript" src="res/skin/default/plugin/rsa/BigInt.js"></script>
  56. <script type="text/javascript" src="res/skin/default/plugin/rsa/Barrett.js"></script>
  57. <script type="text/javascript" src="res/skin/default/plugin/rsa/RSA.js"></script>
  58. <script type="text/javascript">
  59. $(document).ready(function() {
  60. $(function() {
  61. $("#kaptchaImage").click(function() {//生成验证码
  62. $(this).attr(
  63. 'src',
  64. 'kaptcha/image?' + Math.floor(Math.random() * 100)).fadeIn();
  65. event.cancelBubble = true;
  66. });
  67. });
  68. $("#login-form").jupLogin();
  69. });
  70. // 创建一个闭包
  71. (function($) {
  72. // 插件的定义
  73. $.fn.jupLogin = function(options) {
  74. // build main options before element iteration
  75. var opts = $.extend({}, $.fn.jupLogin.defaults, options);
  76. // iterate and reformat each matched element
  77. return this.each(function() {
  78. $this = $(this);
  79. init();
  80. $this.validate({
  81. debug : true ,
  82. onkeyup: false,
  83. onclick: false,
  84. // errorElement: "div",
  85. showErrors: function(errorMap, errorList) {
  86. showErrors(errorMap,errorList);
  87. },
  88. rules: {
  89. userName: "required" ,
  90. passWord : "required" ,
  91. kaptcha : "required"
  92. },
  93. submitHandler : function(form) {
  94. //此处获取加密公钥
  95. $.post("sys/mybatis/getkey",function(data){
  96. //data为获取到的公钥数据
  97. var pubexponent =data.pubexponent;
  98. var pubmodules =data.pubmodules;
  99. setMaxDigits(200);
  100. var key = new RSAKeyPair(pubexponent, "", pubmodules);
  101. var password=$("#passWord").val();
  102. var encrypedPwd = encryptedString(key, encodeURIComponent(password));
  103. $("#passWord").val(encrypedPwd);
  104. var formData = {
  105. "userName" : $(form).find("#userName").val() ,
  106. "passWord" : $(form).find("#passWord").val() ,
  107. "kaptcha" : $(form).find("#kaptcha").val()
  108. };
  109. //登录开始
  110. $.ajax({
  111. url: 'login/sysLogin',
  112. type: 'POST',
  113. dataType: 'json',
  114. data: formData,
  115. success : function(data){
  116. //window.location.href= "sysLogin";
  117. if(data.ret != 0) {
  118. if(data.ret == 1){
  119. showErrors(
  120. {userName : data.msg},
  121. [{
  122. element : "input#kaptcha.input",
  123. message:data.msg
  124. }]);
  125. }else{
  126. showErrors(
  127. {userName : data.msg},
  128. [{
  129. element : "input#userName.input",
  130. message:data.msg
  131. }]);
  132. }
  133. }else {
  134. window.location.href= "index";
  135. }
  136. }
  137. });
  138. //登录结束
  139. });
  140. }
  141. });
  142. });
  143. };
  144. function init(){
  145. };
  146. function showErrors(errorMap, errorList) {
  147. $('.error-content').remove();
  148. $('.error').removeClass('error');
  149. $(errorList).each(function(index, el) {
  150. $(el.element).parent().addClass("error");
  151. var $content = $("<div class='error-content error'> <span class='error-msg'>" + el.message +"</span></div>");
  152. $("body").append($content);
  153. $content.css('top',($(el.element).offset().top+2)).css('left',$(el.element).offset().left-$content.width()-70).show();
  154. shake($content,$content.offset().left);
  155. });
  156. };
  157. //抖动
  158. function shake(o,box_left){
  159. var $panel = $(o);
  160. //box_left = ($(window).width() - $panel.width()) / 2;
  161. //$panel.css({'left': box_left,'position':'absolute'});
  162. for(var i=1; 4>=i; i++){
  163. $panel.animate({left:box_left-0.3*(40-10*i)},50);
  164. $panel.animate({left:box_left+0.3*(40-10*i)},50);
  165. }
  166. };
  167. // 私有函数:debugging
  168. function debug($obj) {
  169. if (window.console && window.console.log)
  170. window.console.log('jupLogin selection count: ' + $obj.size());
  171. };
  172. // 定义暴露format函数
  173. $.fn.jupLogin.format = function(txt) {
  174. return '<strong>' + txt + '</strong>';
  175. };
  176. // 插件的defaults
  177. $.fn.jupLogin.defaults = {
  178. };
  179. // 闭包结束
  180. })(jQuery);
  181. </script>
  182. </body>
  183. </html>


这里,要用到三个JS文件
Barrett.js
BigInt.js
RSA.js
具体见附件;
4、提交到后台在控制器中需要做解密处理,具体如下:
  1. /**
  2. * ajax登录
  3. * @return
  4. * @throws Exception
  5. */
  6. public void login4() {
  7. response.setContentType("text/xml;charset=UTF-8");
  8. response.setHeader("Cache-Control", "no-cache");
  9. PrintWriter out = null;
  10. Map<String, Object> message = new HashMap();
  11. try {
  12. out=response.getWriter();
  13. // String session_authcode="1234";//测试环境
  14. //客户端验证码验证  正式环境
  15. String session_authcode =String.valueOf(session.getAttribute(Constants.SESSION_USER_PHONE_AUTHCODE));
  16. if("".equals(session_authcode)||session_authcode==null||validateCode==null||"".equals(validateCode)){
  17. //out.write("短信密码不能为空,请输入正确短信密码");
  18. //rentJavascript("$.alert2('短信验证码不能为空,请输入短信验证码',function(){location.href='login.jsp'; });");
  19. //return null;
  20. message.put("success", false);
  21. message.put("message", "短信验证码不能为空,请输入短信验证码");
  22. }else{
  23. if (session_authcode.length()>0 && !session_authcode.equals(validateCode)) {
  24. // rentJavascript("$.alert2('短信验证码输入错误,请重新输入',function(){location.href='login.jsp'; });");
  25. // return null;
  26. message.put("success", false);
  27. message.put("message", "短信验证码输入错误,请重新输入");
  28. }else if(validateCode.length()==0 || session_authcode.length() == 0){
  29. // out.write("短信密码不能为空,请输入正确短信密码!");
  30. //rentJavascript("$.alert2('短信验证码不能为空,请输入正确短信验证码!',function(){location.href='login.jsp'});");
  31. //return null;
  32. message.put("success", false);
  33. message.put("message", "短信验证码不能为空,请输入正确短信验证码!");
  34. }else {
  35. //正常登陆
  36. //RSA解密
  37. RSAPrivateKey prik = (RSAPrivateKey) request.getSession().getAttribute("prik");
  38. try{
  39. byte[] en_result = new BigInteger(loginName, 16).toByteArray();
  40. byte[] de_result = RSAUtil.decrypt(prik, en_result);
  41. StringBuffer sb = new StringBuffer();
  42. sb.append(new String(de_result));
  43. loginName= sb.reverse().toString();
  44. //loginName = java.net.URLEncoder.encode(loginName);
  45. loginName = java.net.URLDecoder.decode(loginName,"UTF-8");
  46. byte[] en_identityCode = new BigInteger(identityCode, 16).toByteArray();
  47. byte[] de_identityCode = RSAUtil.decrypt(prik, en_identityCode);
  48. StringBuffer sb1 = new StringBuffer();
  49. sb1.append(new String(de_identityCode));
  50. identityCode= sb1.reverse().toString();
  51. } catch(Exception ex){
  52. ex.printStackTrace();
  53. }
  54. Bj3typePerson user=sysUserService.findBj3typePerson(loginName,identityCode);
  55. if (user == null) {
  56. //rentJavascript("$.alert2('账号错误或不存在,请重新输入!',function(){location.href='login.jsp'});");
  57. //return null;
  58. message.put("success", false);
  59. message.put("message", "账号错误或用户不存在,请重新输入!");
  60. }else if ("00".equals(user.getPersonType())) { //管理员登录
  61. //rentJavascript("$.alert2('系统将自动跳转至符合权限的登录界面',function(){location.href='admin_login.jsp'});");
  62. //return null;
  63. message.put("success", false);
  64. message.put("ptype", "00");
  65. message.put("message", "系统将自动跳转至符合权限的登录界面");
  66. }else{
  67. session.setAttribute(Constants.SESSION_USER_TYPE, user.getPersonType());
  68. session.setAttribute(Constants.SESSION_USER_KEY, user.getAssessId());
  69. session.setAttribute(Constants.SESSION_USER_IP, request.getRemoteAddr());
  70. session.setAttribute(Constants.SESSION_USER_NAME, user.getName());
  71. session.setAttribute(Constants.SESSION_USER_MOBILE, user.getPhone());
  72. session.setAttribute(Constants.SESSION_USER_SETID,"297e672589a9e5210159a9f5999c0032");
  73. session.setAttribute(Constants.SESSION_IDENTITY_CODE, user.getIdentityCode());
  74. /*UserLoginLog loginLog=new UserLoginLog();
  75. loginLog.setLoginTime(TimeHelper.getCurrentTime());
  76. loginLog.setUserId(user.getAssessId());
  77. loginLog.setLoginType(Constants.PC_LOGIN);
  78. userLoginLogService.saveLoginLog(loginLog);*/
  79. OnLineUser onLineUser = (OnLineUser) ctx.getApplication().get("onlineuser");
  80. if (onLineUser==null){
  81. onLineUser=new OnLineUser();
  82. }
  83. onLineUser.addUser(user.getAssessId());
  84. ctx.getApplication().put("onlineuser", onLineUser);
  85. onlineService.onlinUserUpdate(user.getAssessId(), request.getRemoteAddr());
  86. //rentJavascript("function(){location.href='main/main.jsp'});");
  87. message.put("success", true);
  88. //return "login";
  89. }
  90. }
  91. }
  92. } catch (Exception e) {
  93. e.printStackTrace();
  94. //rentJavascript("alert('登录失败,请重新登录!');location.href='login.jsp';");
  95. //out.write("登录失败,请重新登录!");
  96. try {
  97. out=response.getWriter();
  98. message.put("success", false);
  99. message.put("message", "操作异常,请联系管理员");
  100. } catch (IOException e1) {
  101. // TODO Auto-generated catch block
  102. e1.printStackTrace();
  103. }
  104. //return null;
  105. }finally{
  106. out.println(JSONUtil.writeMapJSON(message));
  107. out.flush();
  108. out.close();
  109. }
  110. }

附件:前面用到的3个js(Barrett.js、BigInt.js、RSA.js),CSDN博客不能上传附件,很无奈……只能把代码直接粘这里了

Barrett.js

  1. function BarrettMu(m)
  2. {
  3. this.modulus = biCopy(m);
  4. this.k = biHighIndex(this.modulus) + 1;
  5. var b2k = new BigInt();
  6. b2k.digits[2 * this.k] = 1; // b2k = b^(2k)
  7. this.mu = biDivide(b2k, this.modulus);
  8. this.bkplus1 = new BigInt();
  9. this.bkplus1.digits[this.k + 1] = 1; // bkplus1 = b^(k+1)
  10. this.modulo = BarrettMu_modulo;
  11. this.multiplyMod = BarrettMu_multiplyMod;
  12. this.powMod = BarrettMu_powMod;
  13. }
  14. function BarrettMu_modulo(x)
  15. {
  16. var q1 = biDivideByRadixPower(x, this.k - 1);
  17. var q2 = biMultiply(q1, this.mu);
  18. var q3 = biDivideByRadixPower(q2, this.k + 1);
  19. var r1 = biModuloByRadixPower(x, this.k + 1);
  20. var r2term = biMultiply(q3, this.modulus);
  21. var r2 = biModuloByRadixPower(r2term, this.k + 1);
  22. var r = biSubtract(r1, r2);
  23. if (r.isNeg) {
  24. r = biAdd(r, this.bkplus1);
  25. }
  26. var rgtem = biCompare(r, this.modulus) >= 0;
  27. while (rgtem) {
  28. r = biSubtract(r, this.modulus);
  29. rgtem = biCompare(r, this.modulus) >= 0;
  30. }
  31. return r;
  32. }
  33. function BarrettMu_multiplyMod(x, y)
  34. {
  35. /*
  36. x = this.modulo(x);
  37. y = this.modulo(y);
  38. */
  39. var xy = biMultiply(x, y);
  40. return this.modulo(xy);
  41. }
  42. function BarrettMu_powMod(x, y)
  43. {
  44. var result = new BigInt();
  45. result.digits[0] = 1;
  46. var a = x;
  47. var k = y;
  48. while (true) {
  49. if ((k.digits[0] & 1) != 0) result = this.multiplyMod(result, a);
  50. k = biShiftRight(k, 1);
  51. if (k.digits[0] == 0 && biHighIndex(k) == 0) break;
  52. a = this.multiplyMod(a, a);
  53. }
  54. return result;
  55. }

BigInt.js

  1. // BigInt, a suite of routines for performing multiple-precision arithmetic in
  2. // JavaScript.
  3. //
  4. // Copyright 1998-2005 David Shapiro.
  5. //
  6. // You may use, re-use, abuse,
  7. // copy, and modify this code to your liking, but please keep this header.
  8. // Thanks!
  9. //
  10. // Dave Shapiro
  11. // dave@ohdave.com
  12. // IMPORTANT THING: Be sure to set maxDigits according to your precision
  13. // needs. Use the setMaxDigits() function to do this. See comments below.
  14. //
  15. // Tweaked by Ian Bunning
  16. // Alterations:
  17. // Fix bug in function biFromHex(s) to allow
  18. // parsing of strings of length != 0 (mod 4)
  19. // Changes made by Dave Shapiro as of 12/30/2004:
  20. //
  21. // The BigInt() constructor doesn't take a string anymore. If you want to
  22. // create a BigInt from a string, use biFromDecimal() for base-10
  23. // representations, biFromHex() for base-16 representations, or
  24. // biFromString() for base-2-to-36 representations.
  25. //
  26. // biFromArray() has been removed. Use biCopy() instead, passing a BigInt
  27. // instead of an array.
  28. //
  29. // The BigInt() constructor now only constructs a zeroed-out array.
  30. // Alternatively, if you pass <true>, it won't construct any array. See the
  31. // biCopy() method for an example of this.
  32. //
  33. // Be sure to set maxDigits depending on your precision needs. The default
  34. // zeroed-out array ZERO_ARRAY is constructed inside the setMaxDigits()
  35. // function. So use this function to set the variable. DON'T JUST SET THE
  36. // VALUE. USE THE FUNCTION.
  37. //
  38. // ZERO_ARRAY exists to hopefully speed up construction of BigInts(). By
  39. // precalculating the zero array, we can just use slice(0) to make copies of
  40. // it. Presumably this calls faster native code, as opposed to setting the
  41. // elements one at a time. I have not done any timing tests to verify this
  42. // claim.
  43. // Max number = 10^16 - 2 = 9999999999999998;
  44. // 2^53 = 9007199254740992;
  45. var biRadixBase = 2;
  46. var biRadixBits = 16;
  47. var bitsPerDigit = biRadixBits;
  48. var biRadix = 1 << 16; // = 2^16 = 65536
  49. var biHalfRadix = biRadix >>> 1;
  50. var biRadixSquared = biRadix * biRadix;
  51. var maxDigitVal = biRadix - 1;
  52. var maxInteger = 9999999999999998;
  53. // maxDigits:
  54. // Change this to accommodate your largest number size. Use setMaxDigits()
  55. // to change it!
  56. //
  57. // In general, if you're working with numbers of size N bits, you'll need 2*N
  58. // bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need
  59. //
  60. // 1024 * 2 / 16 = 128 digits of storage.
  61. //
  62. var maxDigits;
  63. var ZERO_ARRAY;
  64. var bigZero, bigOne;
  65. function setMaxDigits(value)
  66. {
  67. maxDigits = value;
  68. ZERO_ARRAY = new Array(maxDigits);
  69. for (var iza = 0; iza < ZERO_ARRAY.length; iza++) ZERO_ARRAY[iza] = 0;
  70. bigZero = new BigInt();
  71. bigOne = new BigInt();
  72. bigOne.digits[0] = 1;
  73. }
  74. setMaxDigits(20);
  75. // The maximum number of digits in base 10 you can convert to an
  76. // integer without JavaScript throwing up on you.
  77. var dpl10 = 15;
  78. // lr10 = 10 ^ dpl10
  79. var lr10 = biFromNumber(1000000000000000);
  80. function BigInt(flag)
  81. {
  82. if (typeof flag == "boolean" && flag == true) {
  83. this.digits = null;
  84. }
  85. else {
  86. this.digits = ZERO_ARRAY.slice(0);
  87. }
  88. this.isNeg = false;
  89. }
  90. function biFromDecimal(s)
  91. {
  92. var isNeg = s.charAt(0) == '-';
  93. var i = isNeg ? 1 : 0;
  94. var result;
  95. // Skip leading zeros.
  96. while (i < s.length && s.charAt(i) == '0') ++i;
  97. if (i == s.length) {
  98. result = new BigInt();
  99. }
  100. else {
  101. var digitCount = s.length - i;
  102. var fgl = digitCount % dpl10;
  103. if (fgl == 0) fgl = dpl10;
  104. result = biFromNumber(Number(s.substr(i, fgl)));
  105. i += fgl;
  106. while (i < s.length) {
  107. result = biAdd(biMultiply(result, lr10),
  108. biFromNumber(Number(s.substr(i, dpl10))));
  109. i += dpl10;
  110. }
  111. result.isNeg = isNeg;
  112. }
  113. return result;
  114. }
  115. function biCopy(bi)
  116. {
  117. var result = new BigInt(true);
  118. result.digits = bi.digits.slice(0);
  119. result.isNeg = bi.isNeg;
  120. return result;
  121. }
  122. function biFromNumber(i)
  123. {
  124. var result = new BigInt();
  125. result.isNeg = i < 0;
  126. i = Math.abs(i);
  127. var j = 0;
  128. while (i > 0) {
  129. result.digits[j++] = i & maxDigitVal;
  130. i = Math.floor(i / biRadix);
  131. }
  132. return result;
  133. }
  134. function reverseStr(s)
  135. {
  136. var result = "";
  137. for (var i = s.length - 1; i > -1; --i) {
  138. result += s.charAt(i);
  139. }
  140. return result;
  141. }
  142. var hexatrigesimalToChar = new Array(
  143. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  144. 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
  145. 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
  146. 'u', 'v', 'w', 'x', 'y', 'z'
  147. );
  148. function biToString(x, radix)
  149. // 2 <= radix <= 36
  150. {
  151. var b = new BigInt();
  152. b.digits[0] = radix;
  153. var qr = biDivideModulo(x, b);
  154. var result = hexatrigesimalToChar[qr[1].digits[0]];
  155. while (biCompare(qr[0], bigZero) == 1) {
  156. qr = biDivideModulo(qr[0], b);
  157. digit = qr[1].digits[0];
  158. result += hexatrigesimalToChar[qr[1].digits[0]];
  159. }
  160. return (x.isNeg ? "-" : "") + reverseStr(result);
  161. }
  162. function biToDecimal(x)
  163. {
  164. var b = new BigInt();
  165. b.digits[0] = 10;
  166. var qr = biDivideModulo(x, b);
  167. var result = String(qr[1].digits[0]);
  168. while (biCompare(qr[0], bigZero) == 1) {
  169. qr = biDivideModulo(qr[0], b);
  170. result += String(qr[1].digits[0]);
  171. }
  172. return (x.isNeg ? "-" : "") + reverseStr(result);
  173. }
  174. var hexToChar = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  175. 'a', 'b', 'c', 'd', 'e', 'f');
  176. function digitToHex(n)
  177. {
  178. var mask = 0xf;
  179. var result = "";
  180. for (i = 0; i < 4; ++i) {
  181. result += hexToChar[n & mask];
  182. n >>>= 4;
  183. }
  184. return reverseStr(result);
  185. }
  186. function biToHex(x)
  187. {
  188. var result = "";
  189. var n = biHighIndex(x);
  190. for (var i = biHighIndex(x); i > -1; --i) {
  191. result += digitToHex(x.digits[i]);
  192. }
  193. return result;
  194. }
  195. function charToHex(c)
  196. {
  197. var ZERO = 48;
  198. var NINE = ZERO + 9;
  199. var littleA = 97;
  200. var littleZ = littleA + 25;
  201. var bigA = 65;
  202. var bigZ = 65 + 25;
  203. var result;
  204. if (c >= ZERO && c <= NINE) {
  205. result = c - ZERO;
  206. } else if (c >= bigA && c <= bigZ) {
  207. result = 10 + c - bigA;
  208. } else if (c >= littleA && c <= littleZ) {
  209. result = 10 + c - littleA;
  210. } else {
  211. result = 0;
  212. }
  213. return result;
  214. }
  215. function hexToDigit(s)
  216. {
  217. var result = 0;
  218. var sl = Math.min(s.length, 4);
  219. for (var i = 0; i < sl; ++i) {
  220. result <<= 4;
  221. result |= charToHex(s.charCodeAt(i))
  222. }
  223. return result;
  224. }
  225. function biFromHex(s)
  226. {
  227. var result = new BigInt();
  228. var sl = s.length;
  229. for (var i = sl, j = 0; i > 0; i -= 4, ++j) {
  230. result.digits[j] = hexToDigit(s.substr(Math.max(i - 4, 0), Math.min(i, 4)));
  231. }
  232. return result;
  233. }
  234. function biFromString(s, radix)
  235. {
  236. var isNeg = s.charAt(0) == '-';
  237. var istop = isNeg ? 1 : 0;
  238. var result = new BigInt();
  239. var place = new BigInt();
  240. place.digits[0] = 1; // radix^0
  241. for (var i = s.length - 1; i >= istop; i--) {
  242. var c = s.charCodeAt(i);
  243. var digit = charToHex(c);
  244. var biDigit = biMultiplyDigit(place, digit);
  245. result = biAdd(result, biDigit);
  246. place = biMultiplyDigit(place, radix);
  247. }
  248. result.isNeg = isNeg;
  249. return result;
  250. }
  251. function biDump(b)
  252. {
  253. return (b.isNeg ? "-" : "") + b.digits.join(" ");
  254. }
  255. function biAdd(x, y)
  256. {
  257. var result;
  258. if (x.isNeg != y.isNeg) {
  259. y.isNeg = !y.isNeg;
  260. result = biSubtract(x, y);
  261. y.isNeg = !y.isNeg;
  262. }
  263. else {
  264. result = new BigInt();
  265. var c = 0;
  266. var n;
  267. for (var i = 0; i < x.digits.length; ++i) {
  268. n = x.digits[i] + y.digits[i] + c;
  269. result.digits[i] = n % biRadix;
  270. c = Number(n >= biRadix);
  271. }
  272. result.isNeg = x.isNeg;
  273. }
  274. return result;
  275. }
  276. function biSubtract(x, y)
  277. {
  278. var result;
  279. if (x.isNeg != y.isNeg) {
  280. y.isNeg = !y.isNeg;
  281. result = biAdd(x, y);
  282. y.isNeg = !y.isNeg;
  283. } else {
  284. result = new BigInt();
  285. var n, c;
  286. c = 0;
  287. for (var i = 0; i < x.digits.length; ++i) {
  288. n = x.digits[i] - y.digits[i] + c;
  289. result.digits[i] = n % biRadix;
  290. // Stupid non-conforming modulus operation.
  291. if (result.digits[i] < 0) result.digits[i] += biRadix;
  292. c = 0 - Number(n < 0);
  293. }
  294. // Fix up the negative sign, if any.
  295. if (c == -1) {
  296. c = 0;
  297. for (var i = 0; i < x.digits.length; ++i) {
  298. n = 0 - result.digits[i] + c;
  299. result.digits[i] = n % biRadix;
  300. // Stupid non-conforming modulus operation.
  301. if (result.digits[i] < 0) result.digits[i] += biRadix;
  302. c = 0 - Number(n < 0);
  303. }
  304. // Result is opposite sign of arguments.
  305. result.isNeg = !x.isNeg;
  306. } else {
  307. // Result is same sign.
  308. result.isNeg = x.isNeg;
  309. }
  310. }
  311. return result;
  312. }
  313. function biHighIndex(x)
  314. {
  315. var result = x.digits.length - 1;
  316. while (result > 0 && x.digits[result] == 0) --result;
  317. return result;
  318. }
  319. function biNumBits(x)
  320. {
  321. var n = biHighIndex(x);
  322. var d = x.digits[n];
  323. var m = (n + 1) * bitsPerDigit;
  324. var result;
  325. for (result = m; result > m - bitsPerDigit; --result) {
  326. if ((d & 0x8000) != 0) break;
  327. d <<= 1;
  328. }
  329. return result;
  330. }
  331. function biMultiply(x, y)
  332. {
  333. var result = new BigInt();
  334. var c;
  335. var n = biHighIndex(x);
  336. var t = biHighIndex(y);
  337. var u, uv, k;
  338. for (var i = 0; i <= t; ++i) {
  339. c = 0;
  340. k = i;
  341. for (j = 0; j <= n; ++j, ++k) {
  342. uv = result.digits[k] + x.digits[j] * y.digits[i] + c;
  343. result.digits[k] = uv & maxDigitVal;
  344. c = uv >>> biRadixBits;
  345. //c = Math.floor(uv / biRadix);
  346. }
  347. result.digits[i + n + 1] = c;
  348. }
  349. // Someone give me a logical xor, please.
  350. result.isNeg = x.isNeg != y.isNeg;
  351. return result;
  352. }
  353. function biMultiplyDigit(x, y)
  354. {
  355. var n, c, uv;
  356. result = new BigInt();
  357. n = biHighIndex(x);
  358. c = 0;
  359. for (var j = 0; j <= n; ++j) {
  360. uv = result.digits[j] + x.digits[j] * y + c;
  361. result.digits[j] = uv & maxDigitVal;
  362. c = uv >>> biRadixBits;
  363. //c = Math.floor(uv / biRadix);
  364. }
  365. result.digits[1 + n] = c;
  366. return result;
  367. }
  368. function arrayCopy(src, srcStart, dest, destStart, n)
  369. {
  370. var m = Math.min(srcStart + n, src.length);
  371. for (var i = srcStart, j = destStart; i < m; ++i, ++j) {
  372. dest[j] = src[i];
  373. }
  374. }
  375. var highBitMasks = new Array(0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800,
  376. 0xFC00, 0xFE00, 0xFF00, 0xFF80, 0xFFC0, 0xFFE0,
  377. 0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE, 0xFFFF);
  378. function biShiftLeft(x, n)
  379. {
  380. var digitCount = Math.floor(n / bitsPerDigit);
  381. var result = new BigInt();
  382. arrayCopy(x.digits, 0, result.digits, digitCount,
  383. result.digits.length - digitCount);
  384. var bits = n % bitsPerDigit;
  385. var rightBits = bitsPerDigit - bits;
  386. for (var i = result.digits.length - 1, i1 = i - 1; i > 0; --i, --i1) {
  387. result.digits[i] = ((result.digits[i] << bits) & maxDigitVal) |
  388. ((result.digits[i1] & highBitMasks[bits]) >>>
  389. (rightBits));
  390. }
  391. result.digits[0] = ((result.digits[i] << bits) & maxDigitVal);
  392. result.isNeg = x.isNeg;
  393. return result;
  394. }
  395. var lowBitMasks = new Array(0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,
  396. 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,
  397. 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF);
  398. function biShiftRight(x, n)
  399. {
  400. var digitCount = Math.floor(n / bitsPerDigit);
  401. var result = new BigInt();
  402. arrayCopy(x.digits, digitCount, result.digits, 0,
  403. x.digits.length - digitCount);
  404. var bits = n % bitsPerDigit;
  405. var leftBits = bitsPerDigit - bits;
  406. for (var i = 0, i1 = i + 1; i < result.digits.length - 1; ++i, ++i1) {
  407. result.digits[i] = (result.digits[i] >>> bits) |
  408. ((result.digits[i1] & lowBitMasks[bits]) << leftBits);
  409. }
  410. result.digits[result.digits.length - 1] >>>= bits;
  411. result.isNeg = x.isNeg;
  412. return result;
  413. }
  414. function biMultiplyByRadixPower(x, n)
  415. {
  416. var result = new BigInt();
  417. arrayCopy(x.digits, 0, result.digits, n, result.digits.length - n);
  418. return result;
  419. }
  420. function biDivideByRadixPower(x, n)
  421. {
  422. var result = new BigInt();
  423. arrayCopy(x.digits, n, result.digits, 0, result.digits.length - n);
  424. return result;
  425. }
  426. function biModuloByRadixPower(x, n)
  427. {
  428. var result = new BigInt();
  429. arrayCopy(x.digits, 0, result.digits, 0, n);
  430. return result;
  431. }
  432. function biCompare(x, y)
  433. {
  434. if (x.isNeg != y.isNeg) {
  435. return 1 - 2 * Number(x.isNeg);
  436. }
  437. for (var i = x.digits.length - 1; i >= 0; --i) {
  438. if (x.digits[i] != y.digits[i]) {
  439. if (x.isNeg) {
  440. return 1 - 2 * Number(x.digits[i] > y.digits[i]);
  441. } else {
  442. return 1 - 2 * Number(x.digits[i] < y.digits[i]);
  443. }
  444. }
  445. }
  446. return 0;
  447. }
  448. function biDivideModulo(x, y)
  449. {
  450. var nb = biNumBits(x);
  451. var tb = biNumBits(y);
  452. var origYIsNeg = y.isNeg;
  453. var q, r;
  454. if (nb < tb) {
  455. // |x| < |y|
  456. if (x.isNeg) {
  457. q = biCopy(bigOne);
  458. q.isNeg = !y.isNeg;
  459. x.isNeg = false;
  460. y.isNeg = false;
  461. r = biSubtract(y, x);
  462. // Restore signs, 'cause they're references.
  463. x.isNeg = true;
  464. y.isNeg = origYIsNeg;
  465. } else {
  466. q = new BigInt();
  467. r = biCopy(x);
  468. }
  469. return new Array(q, r);
  470. }
  471. q = new BigInt();
  472. r = x;
  473. // Normalize Y.
  474. var t = Math.ceil(tb / bitsPerDigit) - 1;
  475. var lambda = 0;
  476. while (y.digits[t] < biHalfRadix) {
  477. y = biShiftLeft(y, 1);
  478. ++lambda;
  479. ++tb;
  480. t = Math.ceil(tb / bitsPerDigit) - 1;
  481. }
  482. // Shift r over to keep the quotient constant. We'll shift the
  483. // remainder back at the end.
  484. r = biShiftLeft(r, lambda);
  485. nb += lambda; // Update the bit count for x.
  486. var n = Math.ceil(nb / bitsPerDigit) - 1;
  487. var b = biMultiplyByRadixPower(y, n - t);
  488. while (biCompare(r, b) != -1) {
  489. ++q.digits[n - t];
  490. r = biSubtract(r, b);
  491. }
  492. for (var i = n; i > t; --i) {
  493. var ri = (i >= r.digits.length) ? 0 : r.digits[i];
  494. var ri1 = (i - 1 >= r.digits.length) ? 0 : r.digits[i - 1];
  495. var ri2 = (i - 2 >= r.digits.length) ? 0 : r.digits[i - 2];
  496. var yt = (t >= y.digits.length) ? 0 : y.digits[t];
  497. var yt1 = (t - 1 >= y.digits.length) ? 0 : y.digits[t - 1];
  498. if (ri == yt) {
  499. q.digits[i - t - 1] = maxDigitVal;
  500. } else {
  501. q.digits[i - t - 1] = Math.floor((ri * biRadix + ri1) / yt);
  502. }
  503. var c1 = q.digits[i - t - 1] * ((yt * biRadix) + yt1);
  504. var c2 = (ri * biRadixSquared) + ((ri1 * biRadix) + ri2);
  505. while (c1 > c2) {
  506. --q.digits[i - t - 1];
  507. c1 = q.digits[i - t - 1] * ((yt * biRadix) | yt1);
  508. c2 = (ri * biRadix * biRadix) + ((ri1 * biRadix) + ri2);
  509. }
  510. b = biMultiplyByRadixPower(y, i - t - 1);
  511. r = biSubtract(r, biMultiplyDigit(b, q.digits[i - t - 1]));
  512. if (r.isNeg) {
  513. r = biAdd(r, b);
  514. --q.digits[i - t - 1];
  515. }
  516. }
  517. r = biShiftRight(r, lambda);
  518. // Fiddle with the signs and stuff to make sure that 0 <= r < y.
  519. q.isNeg = x.isNeg != origYIsNeg;
  520. if (x.isNeg) {
  521. if (origYIsNeg) {
  522. q = biAdd(q, bigOne);
  523. } else {
  524. q = biSubtract(q, bigOne);
  525. }
  526. y = biShiftRight(y, lambda);
  527. r = biSubtract(y, r);
  528. }
  529. // Check for the unbelievably stupid degenerate case of r == -0.
  530. if (r.digits[0] == 0 && biHighIndex(r) == 0) r.isNeg = false;
  531. return new Array(q, r);
  532. }
  533. function biDivide(x, y)
  534. {
  535. return biDivideModulo(x, y)[0];
  536. }
  537. function biModulo(x, y)
  538. {
  539. return biDivideModulo(x, y)[1];
  540. }
  541. function biMultiplyMod(x, y, m)
  542. {
  543. return biModulo(biMultiply(x, y), m);
  544. }
  545. function biPow(x, y)
  546. {
  547. var result = bigOne;
  548. var a = x;
  549. while (true) {
  550. if ((y & 1) != 0) result = biMultiply(result, a);
  551. y >>= 1;
  552. if (y == 0) break;
  553. a = biMultiply(a, a);
  554. }
  555. return result;
  556. }
  557. function biPowMod(x, y, m)
  558. {
  559. var result = bigOne;
  560. var a = x;
  561. var k = y;
  562. while (true) {
  563. if ((k.digits[0] & 1) != 0) result = biMultiplyMod(result, a, m);
  564. k = biShiftRight(k, 1);
  565. if (k.digits[0] == 0 && biHighIndex(k) == 0) break;
  566. a = biMultiplyMod(a, a, m);
  567. }
  568. return result;
  569. }
RSA.js

  1. // RSA, a suite of routines for performing RSA public-key computations in
  2. // JavaScript.
  3. //
  4. // Requires BigInt.js and Barrett.js.
  5. //
  6. // Copyright 1998-2005 David Shapiro.
  7. //
  8. // You may use, re-use, abuse, copy, and modify this code to your liking, but
  9. // please keep this header.
  10. //
  11. // Thanks!
  12. //
  13. // Dave Shapiro
  14. // dave@ohdave.com
  15. function RSAKeyPair(encryptionExponent, decryptionExponent, modulus)
  16. {
  17. this.e = biFromHex(encryptionExponent);
  18. this.d = biFromHex(decryptionExponent);
  19. this.m = biFromHex(modulus);
  20. // We can do two bytes per digit, so
  21. // chunkSize = 2 * (number of digits in modulus - 1).
  22. // Since biHighIndex returns the high index, not the number of digits, 1 has
  23. // already been subtracted.
  24. this.chunkSize = 2 * biHighIndex(this.m);
  25. this.radix = 16;
  26. this.barrett = new BarrettMu(this.m);
  27. }
  28. function twoDigit(n)
  29. {
  30. return (n < 10 ? "0" : "") + String(n);
  31. }
  32. function encryptedString(key, s)
  33. // Altered by Rob Saunders (rob@robsaunders.net). New routine pads the
  34. // string after it has been converted to an array. This fixes an
  35. // incompatibility with Flash MX's ActionScript.
  36. {
  37. var a = new Array();
  38. var sl = s.length;
  39. var i = 0;
  40. while (i < sl) {
  41. a[i] = s.charCodeAt(i);
  42. i++;
  43. }
  44. while (a.length % key.chunkSize != 0) {
  45. a[i++] = 0;
  46. }
  47. var al = a.length;
  48. var result = "";
  49. var j, k, block;
  50. for (i = 0; i < al; i += key.chunkSize) {
  51. block = new BigInt();
  52. j = 0;
  53. for (k = i; k < i + key.chunkSize; ++j) {
  54. block.digits[j] = a[k++];
  55. block.digits[j] += a[k++] << 8;
  56. }
  57. var crypt = key.barrett.powMod(block, key.e);
  58. var text = key.radix == 16 ? biToHex(crypt) : biToString(crypt, key.radix);
  59. result += text + " ";
  60. }
  61. return result.substring(0, result.length - 1); // Remove last space.
  62. }
  63. function decryptedString(key, s)
  64. {
  65. var blocks = s.split(" ");
  66. var result = "";
  67. var i, j, block;
  68. for (i = 0; i < blocks.length; ++i) {
  69. var bi;
  70. if (key.radix == 16) {
  71. bi = biFromHex(blocks[i]);
  72. }
  73. else {
  74. bi = biFromString(blocks[i], key.radix);
  75. }
  76. block = key.barrett.powMod(bi, key.d);
  77. for (j = 0; j <= biHighIndex(block); ++j) {
  78. result += String.fromCharCode(block.digits[j] & 255,
  79. block.digits[j] >> 8);
  80. }
  81. }
  82. // Remove trailing null, if any.
  83. if (result.charCodeAt(result.length - 1) == 0) {
  84. result = result.substring(0, result.length - 1);
  85. }
  86. return result;
  87. }





声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/948485
推荐阅读
相关标签
  

闽ICP备14008679号