zoukankan      html  css  js  c++  java
  • 帐号明文传输漏洞

    表单提交前加密,本文使用(BASE64)加密

      1 /**
      2  *BASE64 Encode and Decode By UTF-8 unicode
      3  *可以和java的BASE64编码和解码互相转化
      4  */
      5 (function(){
      6     var BASE64_MAPPING = [
      7         'A','B','C','D','E','F','G','H',
      8         'I','J','K','L','M','N','O','P',
      9         'Q','R','S','T','U','V','W','X',
     10         'Y','Z','a','b','c','d','e','f',
     11         'g','h','i','j','k','l','m','n',
     12         'o','p','q','r','s','t','u','v',
     13         'w','x','y','z','0','1','2','3',
     14         '4','5','6','7','8','9','+','/'
     15     ];
     16 
     17     /**
     18      *ascii convert to binary
     19      */
     20     var _toBinary = function(ascii){
     21         var binary = new Array();
     22         while(ascii > 0){
     23             var b = ascii%2;
     24             ascii = Math.floor(ascii/2);
     25             binary.push(b);
     26         }
     27         /*
     28         var len = binary.length;
     29         if(6-len > 0){
     30             for(var i = 6-len ; i > 0 ; --i){
     31                 binary.push(0);
     32             }
     33         }*/
     34         binary.reverse();
     35         return binary;
     36     };
     37 
     38     /**
     39      *binary convert to decimal
     40      */
     41     var _toDecimal  = function(binary){
     42         var dec = 0;
     43         var p = 0;
     44         for(var i = binary.length-1 ; i >= 0 ; --i){
     45             var b = binary[i];
     46             if(b == 1){
     47                 dec += Math.pow(2 , p);
     48             }
     49             ++p;
     50         }
     51         return dec;
     52     };
     53 
     54     /**
     55      *unicode convert to utf-8
     56      */
     57     var _toUTF8Binary = function(c , binaryArray){
     58         var mustLen = (8-(c+1)) + ((c-1)*6);
     59         var fatLen = binaryArray.length;
     60         var diff = mustLen - fatLen;
     61         while(--diff >= 0){
     62             binaryArray.unshift(0);
     63         }
     64         var binary = [];
     65         var _c = c;
     66         while(--_c >= 0){
     67             binary.push(1);
     68         }
     69         binary.push(0);
     70         var i = 0 , len = 8 - (c+1);
     71         for(; i < len ; ++i){
     72             binary.push(binaryArray[i]);
     73         }
     74 
     75         for(var j = 0 ; j < c-1 ; ++j){
     76             binary.push(1);
     77             binary.push(0);
     78             var sum = 6;
     79             while(--sum >= 0){
     80                 binary.push(binaryArray[i++]);
     81             }
     82         }
     83         return binary;
     84     };
     85 
     86     var __BASE64 = {
     87             /**
     88              *BASE64 Encode
     89              */
     90             encoder:function(str){
     91                 var base64_Index = [];
     92                 var binaryArray = [];
     93                 for(var i = 0 , len = str.length ; i < len ; ++i){
     94                     var unicode = str.charCodeAt(i);
     95                     var _tmpBinary = _toBinary(unicode);
     96                     if(unicode < 0x80){
     97                         var _tmpdiff = 8 - _tmpBinary.length;
     98                         while(--_tmpdiff >= 0){
     99                             _tmpBinary.unshift(0);
    100                         }
    101                         binaryArray = binaryArray.concat(_tmpBinary);
    102                     }else if(unicode >= 0x80 && unicode <= 0x7FF){
    103                         binaryArray = binaryArray.concat(_toUTF8Binary(2 , _tmpBinary));
    104                     }else if(unicode >= 0x800 && unicode <= 0xFFFF){//UTF-8 3byte
    105                         binaryArray = binaryArray.concat(_toUTF8Binary(3 , _tmpBinary));
    106                     }else if(unicode >= 0x10000 && unicode <= 0x1FFFFF){//UTF-8 4byte
    107                         binaryArray = binaryArray.concat(_toUTF8Binary(4 , _tmpBinary));    
    108                     }else if(unicode >= 0x200000 && unicode <= 0x3FFFFFF){//UTF-8 5byte
    109                         binaryArray = binaryArray.concat(_toUTF8Binary(5 , _tmpBinary));
    110                     }else if(unicode >= 4000000 && unicode <= 0x7FFFFFFF){//UTF-8 6byte
    111                         binaryArray = binaryArray.concat(_toUTF8Binary(6 , _tmpBinary));
    112                     }
    113                 }
    114 
    115                 var extra_Zero_Count = 0;
    116                 for(var i = 0 , len = binaryArray.length ; i < len ; i+=6){
    117                     var diff = (i+6)-len;
    118                     if(diff == 2){
    119                         extra_Zero_Count = 2;
    120                     }else if(diff == 4){
    121                         extra_Zero_Count = 4;
    122                     }
    123                     //if(extra_Zero_Count > 0){
    124                     //    len += extra_Zero_Count+1;
    125                     //}
    126                     var _tmpExtra_Zero_Count = extra_Zero_Count;
    127                     while(--_tmpExtra_Zero_Count >= 0){
    128                         binaryArray.push(0);
    129                     }
    130                     base64_Index.push(_toDecimal(binaryArray.slice(i , i+6)));
    131                 }
    132 
    133                 var base64 = '';
    134                 for(var i = 0 , len = base64_Index.length ; i < len ; ++i){
    135                     base64 += BASE64_MAPPING[base64_Index[i]];
    136                 }
    137 
    138                 for(var i = 0 , len = extra_Zero_Count/2 ; i < len ; ++i){
    139                     base64 += '=';
    140                 }
    141                 return base64;
    142             },
    143             /**
    144              *BASE64  Decode for UTF-8 
    145              */
    146             decoder : function(_base64Str){
    147                 var _len = _base64Str.length;
    148                 var extra_Zero_Count = 0;
    149                 /**
    150                  *计算在进行BASE64编码的时候,补了几个0
    151                  */
    152                 if(_base64Str.charAt(_len-1) == '='){
    153                     //alert(_base64Str.charAt(_len-1));
    154                     //alert(_base64Str.charAt(_len-2));
    155                     if(_base64Str.charAt(_len-2) == '='){//两个等号说明补了4个0
    156                         extra_Zero_Count = 4;
    157                         _base64Str = _base64Str.substring(0 , _len-2);
    158                     }else{//一个等号说明补了2个0
    159                         extra_Zero_Count = 2;
    160                         _base64Str = _base64Str.substring(0 , _len - 1);
    161                     }
    162                 }
    163 
    164                 var binaryArray = [];
    165                 for(var i = 0 , len = _base64Str.length; i < len ; ++i){
    166                     var c = _base64Str.charAt(i);
    167                     for(var j = 0 , size = BASE64_MAPPING.length ; j < size ; ++j){
    168                         if(c == BASE64_MAPPING[j]){
    169                             var _tmp = _toBinary(j);
    170                             /*不足6位的补0*/
    171                             var _tmpLen = _tmp.length;
    172                             if(6-_tmpLen > 0){
    173                                 for(var k = 6-_tmpLen ; k > 0 ; --k){
    174                                     _tmp.unshift(0);
    175                                 }
    176                             }
    177                             binaryArray = binaryArray.concat(_tmp);
    178                             break;
    179                         }
    180                     }
    181                 }
    182 
    183                 if(extra_Zero_Count > 0){
    184                     binaryArray = binaryArray.slice(0 , binaryArray.length - extra_Zero_Count);
    185                 }
    186 
    187                 var unicode = [];
    188                 var unicodeBinary = [];
    189                 for(var i = 0 , len = binaryArray.length ; i < len ; ){
    190                     if(binaryArray[i] == 0){
    191                         unicode=unicode.concat(_toDecimal(binaryArray.slice(i,i+8)));
    192                         i += 8;
    193                     }else{
    194                         var sum = 0;
    195                         while(i < len){
    196                             if(binaryArray[i] == 1){
    197                                 ++sum;
    198                             }else{
    199                                 break;
    200                             }
    201                             ++i;
    202                         }
    203                         unicodeBinary = unicodeBinary.concat(binaryArray.slice(i+1 , i+8-sum));
    204                         i += 8 - sum;
    205                         while(sum > 1){
    206                             unicodeBinary = unicodeBinary.concat(binaryArray.slice(i+2 , i+8));
    207                             i += 8;
    208                             --sum;
    209                         }
    210                         unicode = unicode.concat(_toDecimal(unicodeBinary));
    211                         unicodeBinary = [];
    212                     }
    213                 }
    214                 return unicode;
    215             }
    216     };
    217 
    218     window.BASE64 = __BASE64;
    219 })();
    BASE64.js

    登陆检验:

     1 <form name="form1" method="post" action="<%=basePath%>/core/login.action"
     2                         onsubmit="return checkParam();"></form>
     3 
     4 
     5 <script language="JavaScript" type="text/JavaScript">
     6             //登录检验
     7             function checkParam(){
     8                 var userName = $.trim($("#userName").val()); 
     9                 var passWord = $.trim($("#passWord").val()); 
    10                 if(userName==""){
    11                     alert("请输入用户名!");
    12                     $("#userName").focus();
    13                     return false;
    14                 }
    15                 if(passWord==""){
    16                     alert("请输入密码!");
    17                     $("#passWord").focus();
    18                     return false;
    19                 }
    20                 document.form1.action.value="authenticate";
    21                 document.getElementById("userName").value = BASE64.encoder($("#userName").val());//返回编码后的账号
    22                 document.getElementById("passWord").value = BASE64.encoder($("#passWord").val());//返回编码后的账号
    23                 return true;
    24             }
    25             
    26         </script>
    form1
      1 import java.io.Serializable;
      2 import java.io.UnsupportedEncodingException;
      3 
      4 /**
      5  * BASE64加密解密的处理类 
      6  * <br>
      7  * 
      8  * @author Vivim
      9  * @time Jan 13, 2009 12:12:42 PM
     10  * @version 1.0
     11  */
     12 public class BASE64 implements Serializable {
     13 
     14     private static final long serialVersionUID = 3762133767673900132L;
     15 
     16     private static char[] base64EncodeChars = new char[] { 'A', 'B', 'C', 'D',
     17             'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
     18             'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd',
     19             'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q',
     20             'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
     21             '4', '5', '6', '7', '8', '9', '+', '/' };
     22 
     23     private static byte[] base64DecodeChars = new byte[] { -1, -1, -1, -1, -1,
     24             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
     25             -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
     26             -1, -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59,
     27             60, 61, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
     28             10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1,
     29             -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
     30             38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1,
     31             -1, -1 };
     32 
     33     // 编码
     34     public final static String encode(byte[] data) {
     35         StringBuffer sb = new StringBuffer();
     36         int len = data.length;
     37         int i = 0;
     38         int b1, b2, b3;
     39         while (i < len) {
     40             b1 = data[i++] & 0xff;
     41             if (i == len) {
     42                 sb.append(base64EncodeChars[b1 >>> 2]);
     43                 sb.append(base64EncodeChars[(b1 & 0x3) << 4]);
     44                 sb.append("==");
     45                 break;
     46             }
     47             b2 = data[i++] & 0xff;
     48             if (i == len) {
     49                 sb.append(base64EncodeChars[b1 >>> 2]);
     50                 sb.append(base64EncodeChars[((b1 & 0x03) << 4)
     51                         | ((b2 & 0xf0) >>> 4)]);
     52                 sb.append(base64EncodeChars[(b2 & 0x0f) << 2]);
     53                 sb.append("=");
     54                 break;
     55             }
     56             b3 = data[i++] & 0xff;
     57             sb.append(base64EncodeChars[b1 >>> 2]);
     58             sb.append(base64EncodeChars[((b1 & 0x03) << 4)
     59                     | ((b2 & 0xf0) >>> 4)]);
     60             sb.append(base64EncodeChars[((b2 & 0x0f) << 2)
     61                     | ((b3 & 0xc0) >>> 6)]);
     62             sb.append(base64EncodeChars[b3 & 0x3f]);
     63         }
     64         return sb.toString();
     65     }
     66 
     67     // 解码
     68     public final static byte[] decode(String str)
     69             throws UnsupportedEncodingException {
     70         StringBuffer sb = new StringBuffer();
     71         byte[] data = str.getBytes("US-ASCII");
     72         int len = data.length;
     73         int i = 0;
     74         int b1, b2, b3, b4;
     75         while (i < len) {
     76             /* b1 */
     77             do {
     78                 b1 = base64DecodeChars[data[i++]];
     79             } while (i < len && b1 == -1);
     80             if (b1 == -1)
     81                 break;
     82             /* b2 */
     83             do {
     84                 b2 = base64DecodeChars[data[i++]];
     85             } while (i < len && b2 == -1);
     86             if (b2 == -1)
     87                 break;
     88             sb.append((char) ((b1 << 2) | ((b2 & 0x30) >>> 4)));
     89             /* b3 */
     90             do {
     91                 b3 = data[i++];
     92                 if (b3 == 61)
     93                     return sb.toString().getBytes("ISO-8859-1");
     94                 b3 = base64DecodeChars[b3];
     95             } while (i < len && b3 == -1);
     96             if (b3 == -1)
     97                 break;
     98             sb.append((char) (((b2 & 0x0f) << 4) | ((b3 & 0x3c) >>> 2)));
     99             /* b4 */
    100             do {
    101                 b4 = data[i++];
    102                 if (b4 == 61)
    103                     return sb.toString().getBytes("ISO-8859-1");
    104                 b4 = base64DecodeChars[b4];
    105             } while (i < len && b4 == -1);
    106             if (b4 == -1)
    107                 break;
    108             sb.append((char) (((b3 & 0x03) << 6) | b4));
    109         }
    110         return sb.toString().getBytes("ISO-8859-1");
    111     }
    112 
    113     /**
    114      * 获得指定字符串的Base64编码值字符串
    115      * <br>
    116      * @param srcString
    117      * @return
    118      */
    119     public final static String encodeToBase64(String srcString) {
    120         return encode(srcString.getBytes());
    121     }
    122 
    123     /**
    124      * 获得Base64编码字符串的解码值字符串
    125      * @param base64String
    126      * @return
    127      * @throws UnsupportedEncodingException
    128      */
    129     public final static String decodeFromBase64(String base64String){
    130         String s = null;
    131         try {
    132             s = new String(decode(base64String));
    133         } catch (UnsupportedEncodingException e) {
    134             e.printStackTrace();
    135         }
    136         return s;
    137     }
    138 }
    BASE64.java

    action层解密

    1             userName = BASE64.decodeFromBase64(userName);
    2             passWord = BASE64.decodeFromBase64(passWord);
    LoginAction

    service层md5加密后与数据库密文对比。

    md5不能解密。

    ====================分割线====================

    前端rsa加密

      1 /*
      2  * RSA, a suite of routines for performing RSA public-key computations in JavaScript.
      3  * Copyright 1998-2005 David Shapiro.
      4  * Dave Shapiro
      5  * dave@ohdave.com 
      6  * changed by Fuchun, 2010-05-06
      7  * fcrpg2005@gmail.com
      8  */
      9 
     10 (function($w) {
     11 
     12 if(typeof $w.RSAUtils === 'undefined')
     13     var RSAUtils = $w.RSAUtils = {};
     14 
     15 var biRadixBase = 2;
     16 var biRadixBits = 16;
     17 var bitsPerDigit = biRadixBits;
     18 var biRadix = 1 << 16; // = 2^16 = 65536
     19 var biHalfRadix = biRadix >>> 1;
     20 var biRadixSquared = biRadix * biRadix;
     21 var maxDigitVal = biRadix - 1;
     22 var maxInteger = 9999999999999998;
     23 
     24 //maxDigits:
     25 //Change this to accommodate your largest number size. Use setMaxDigits()
     26 //to change it!
     27 //
     28 //In general, if you're working with numbers of size N bits, you'll need 2*N
     29 //bits of storage. Each digit holds 16 bits. So, a 1024-bit key will need
     30 //
     31 //1024 * 2 / 16 = 128 digits of storage.
     32 //
     33 var maxDigits;
     34 var ZERO_ARRAY;
     35 var bigZero, bigOne;
     36 
     37 var BigInt = $w.BigInt = function(flag) {
     38     if (typeof flag == "boolean" && flag == true) {
     39         this.digits = null;
     40     } else {
     41         this.digits = ZERO_ARRAY.slice(0);
     42     }
     43     this.isNeg = false;
     44 };
     45 
     46 RSAUtils.setMaxDigits = function(value) {
     47     maxDigits = value;
     48     ZERO_ARRAY = new Array(maxDigits);
     49     for (var iza = 0; iza < ZERO_ARRAY.length; iza++) ZERO_ARRAY[iza] = 0;
     50     bigZero = new BigInt();
     51     bigOne = new BigInt();
     52     bigOne.digits[0] = 1;
     53 };
     54 RSAUtils.setMaxDigits(20);
     55 
     56 //The maximum number of digits in base 10 you can convert to an
     57 //integer without JavaScript throwing up on you.
     58 var dpl10 = 15;
     59 
     60 RSAUtils.biFromNumber = function(i) {
     61     var result = new BigInt();
     62     result.isNeg = i < 0;
     63     i = Math.abs(i);
     64     var j = 0;
     65     while (i > 0) {
     66         result.digits[j++] = i & maxDigitVal;
     67         i = Math.floor(i / biRadix);
     68     }
     69     return result;
     70 };
     71 
     72 //lr10 = 10 ^ dpl10
     73 var lr10 = RSAUtils.biFromNumber(1000000000000000);
     74 
     75 RSAUtils.biFromDecimal = function(s) {
     76     var isNeg = s.charAt(0) == '-';
     77     var i = isNeg ? 1 : 0;
     78     var result;
     79     // Skip leading zeros.
     80     while (i < s.length && s.charAt(i) == '0') ++i;
     81     if (i == s.length) {
     82         result = new BigInt();
     83     }
     84     else {
     85         var digitCount = s.length - i;
     86         var fgl = digitCount % dpl10;
     87         if (fgl == 0) fgl = dpl10;
     88         result = RSAUtils.biFromNumber(Number(s.substr(i, fgl)));
     89         i += fgl;
     90         while (i < s.length) {
     91             result = RSAUtils.biAdd(RSAUtils.biMultiply(result, lr10),
     92                     RSAUtils.biFromNumber(Number(s.substr(i, dpl10))));
     93             i += dpl10;
     94         }
     95         result.isNeg = isNeg;
     96     }
     97     return result;
     98 };
     99 
    100 RSAUtils.biCopy = function(bi) {
    101     var result = new BigInt(true);
    102     result.digits = bi.digits.slice(0);
    103     result.isNeg = bi.isNeg;
    104     return result;
    105 };
    106 
    107 RSAUtils.reverseStr = function(s) {
    108     var result = "";
    109     for (var i = s.length - 1; i > -1; --i) {
    110         result += s.charAt(i);
    111     }
    112     return result;
    113 };
    114 
    115 var hexatrigesimalToChar = [
    116     '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    117     'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
    118     'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
    119     'u', 'v', 'w', 'x', 'y', 'z'
    120 ];
    121 
    122 RSAUtils.biToString = function(x, radix) { // 2 <= radix <= 36
    123     var b = new BigInt();
    124     b.digits[0] = radix;
    125     var qr = RSAUtils.biDivideModulo(x, b);
    126     var result = hexatrigesimalToChar[qr[1].digits[0]];
    127     while (RSAUtils.biCompare(qr[0], bigZero) == 1) {
    128         qr = RSAUtils.biDivideModulo(qr[0], b);
    129         digit = qr[1].digits[0];
    130         result += hexatrigesimalToChar[qr[1].digits[0]];
    131     }
    132     return (x.isNeg ? "-" : "") + RSAUtils.reverseStr(result);
    133 };
    134 
    135 RSAUtils.biToDecimal = function(x) {
    136     var b = new BigInt();
    137     b.digits[0] = 10;
    138     var qr = RSAUtils.biDivideModulo(x, b);
    139     var result = String(qr[1].digits[0]);
    140     while (RSAUtils.biCompare(qr[0], bigZero) == 1) {
    141         qr = RSAUtils.biDivideModulo(qr[0], b);
    142         result += String(qr[1].digits[0]);
    143     }
    144     return (x.isNeg ? "-" : "") + RSAUtils.reverseStr(result);
    145 };
    146 
    147 var hexToChar = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
    148         'a', 'b', 'c', 'd', 'e', 'f'];
    149 
    150 RSAUtils.digitToHex = function(n) {
    151     var mask = 0xf;
    152     var result = "";
    153     for (i = 0; i < 4; ++i) {
    154         result += hexToChar[n & mask];
    155         n >>>= 4;
    156     }
    157     return RSAUtils.reverseStr(result);
    158 };
    159 
    160 RSAUtils.biToHex = function(x) {
    161     var result = "";
    162     var n = RSAUtils.biHighIndex(x);
    163     for (var i = RSAUtils.biHighIndex(x); i > -1; --i) {
    164         result += RSAUtils.digitToHex(x.digits[i]);
    165     }
    166     return result;
    167 };
    168 
    169 RSAUtils.charToHex = function(c) {
    170     var ZERO = 48;
    171     var NINE = ZERO + 9;
    172     var littleA = 97;
    173     var littleZ = littleA + 25;
    174     var bigA = 65;
    175     var bigZ = 65 + 25;
    176     var result;
    177 
    178     if (c >= ZERO && c <= NINE) {
    179         result = c - ZERO;
    180     } else if (c >= bigA && c <= bigZ) {
    181         result = 10 + c - bigA;
    182     } else if (c >= littleA && c <= littleZ) {
    183         result = 10 + c - littleA;
    184     } else {
    185         result = 0;
    186     }
    187     return result;
    188 };
    189 
    190 RSAUtils.hexToDigit = function(s) {
    191     var result = 0;
    192     var sl = Math.min(s.length, 4);
    193     for (var i = 0; i < sl; ++i) {
    194         result <<= 4;
    195         result |= RSAUtils.charToHex(s.charCodeAt(i));
    196     }
    197     return result;
    198 };
    199 
    200 RSAUtils.biFromHex = function(s) {
    201     var result = new BigInt();
    202     var sl = s.length;
    203     for (var i = sl, j = 0; i > 0; i -= 4, ++j) {
    204         result.digits[j] = RSAUtils.hexToDigit(s.substr(Math.max(i - 4, 0), Math.min(i, 4)));
    205     }
    206     return result;
    207 };
    208 
    209 RSAUtils.biFromString = function(s, radix) {
    210     var isNeg = s.charAt(0) == '-';
    211     var istop = isNeg ? 1 : 0;
    212     var result = new BigInt();
    213     var place = new BigInt();
    214     place.digits[0] = 1; // radix^0
    215     for (var i = s.length - 1; i >= istop; i--) {
    216         var c = s.charCodeAt(i);
    217         var digit = RSAUtils.charToHex(c);
    218         var biDigit = RSAUtils.biMultiplyDigit(place, digit);
    219         result = RSAUtils.biAdd(result, biDigit);
    220         place = RSAUtils.biMultiplyDigit(place, radix);
    221     }
    222     result.isNeg = isNeg;
    223     return result;
    224 };
    225 
    226 RSAUtils.biDump = function(b) {
    227     return (b.isNeg ? "-" : "") + b.digits.join(" ");
    228 };
    229 
    230 RSAUtils.biAdd = function(x, y) {
    231     var result;
    232 
    233     if (x.isNeg != y.isNeg) {
    234         y.isNeg = !y.isNeg;
    235         result = RSAUtils.biSubtract(x, y);
    236         y.isNeg = !y.isNeg;
    237     }
    238     else {
    239         result = new BigInt();
    240         var c = 0;
    241         var n;
    242         for (var i = 0; i < x.digits.length; ++i) {
    243             n = x.digits[i] + y.digits[i] + c;
    244             result.digits[i] = n % biRadix;
    245             c = Number(n >= biRadix);
    246         }
    247         result.isNeg = x.isNeg;
    248     }
    249     return result;
    250 };
    251 
    252 RSAUtils.biSubtract = function(x, y) {
    253     var result;
    254     if (x.isNeg != y.isNeg) {
    255         y.isNeg = !y.isNeg;
    256         result = RSAUtils.biAdd(x, y);
    257         y.isNeg = !y.isNeg;
    258     } else {
    259         result = new BigInt();
    260         var n, c;
    261         c = 0;
    262         for (var i = 0; i < x.digits.length; ++i) {
    263             n = x.digits[i] - y.digits[i] + c;
    264             result.digits[i] = n % biRadix;
    265             // Stupid non-conforming modulus operation.
    266             if (result.digits[i] < 0) result.digits[i] += biRadix;
    267             c = 0 - Number(n < 0);
    268         }
    269         // Fix up the negative sign, if any.
    270         if (c == -1) {
    271             c = 0;
    272             for (var i = 0; i < x.digits.length; ++i) {
    273                 n = 0 - result.digits[i] + c;
    274                 result.digits[i] = n % biRadix;
    275                 // Stupid non-conforming modulus operation.
    276                 if (result.digits[i] < 0) result.digits[i] += biRadix;
    277                 c = 0 - Number(n < 0);
    278             }
    279             // Result is opposite sign of arguments.
    280             result.isNeg = !x.isNeg;
    281         } else {
    282             // Result is same sign.
    283             result.isNeg = x.isNeg;
    284         }
    285     }
    286     return result;
    287 };
    288 
    289 RSAUtils.biHighIndex = function(x) {
    290     var result = x.digits.length - 1;
    291     while (result > 0 && x.digits[result] == 0) --result;
    292     return result;
    293 };
    294 
    295 RSAUtils.biNumBits = function(x) {
    296     var n = RSAUtils.biHighIndex(x);
    297     var d = x.digits[n];
    298     var m = (n + 1) * bitsPerDigit;
    299     var result;
    300     for (result = m; result > m - bitsPerDigit; --result) {
    301         if ((d & 0x8000) != 0) break;
    302         d <<= 1;
    303     }
    304     return result;
    305 };
    306 
    307 RSAUtils.biMultiply = function(x, y) {
    308     var result = new BigInt();
    309     var c;
    310     var n = RSAUtils.biHighIndex(x);
    311     var t = RSAUtils.biHighIndex(y);
    312     var u, uv, k;
    313 
    314     for (var i = 0; i <= t; ++i) {
    315         c = 0;
    316         k = i;
    317         for (j = 0; j <= n; ++j, ++k) {
    318             uv = result.digits[k] + x.digits[j] * y.digits[i] + c;
    319             result.digits[k] = uv & maxDigitVal;
    320             c = uv >>> biRadixBits;
    321             //c = Math.floor(uv / biRadix);
    322         }
    323         result.digits[i + n + 1] = c;
    324     }
    325     // Someone give me a logical xor, please.
    326     result.isNeg = x.isNeg != y.isNeg;
    327     return result;
    328 };
    329 
    330 RSAUtils.biMultiplyDigit = function(x, y) {
    331     var n, c, uv;
    332 
    333     result = new BigInt();
    334     n = RSAUtils.biHighIndex(x);
    335     c = 0;
    336     for (var j = 0; j <= n; ++j) {
    337         uv = result.digits[j] + x.digits[j] * y + c;
    338         result.digits[j] = uv & maxDigitVal;
    339         c = uv >>> biRadixBits;
    340         //c = Math.floor(uv / biRadix);
    341     }
    342     result.digits[1 + n] = c;
    343     return result;
    344 };
    345 
    346 RSAUtils.arrayCopy = function(src, srcStart, dest, destStart, n) {
    347     var m = Math.min(srcStart + n, src.length);
    348     for (var i = srcStart, j = destStart; i < m; ++i, ++j) {
    349         dest[j] = src[i];
    350     }
    351 };
    352 
    353 var highBitMasks = [0x0000, 0x8000, 0xC000, 0xE000, 0xF000, 0xF800,
    354         0xFC00, 0xFE00, 0xFF00, 0xFF80, 0xFFC0, 0xFFE0,
    355         0xFFF0, 0xFFF8, 0xFFFC, 0xFFFE, 0xFFFF];
    356 
    357 RSAUtils.biShiftLeft = function(x, n) {
    358     var digitCount = Math.floor(n / bitsPerDigit);
    359     var result = new BigInt();
    360     RSAUtils.arrayCopy(x.digits, 0, result.digits, digitCount,
    361               result.digits.length - digitCount);
    362     var bits = n % bitsPerDigit;
    363     var rightBits = bitsPerDigit - bits;
    364     for (var i = result.digits.length - 1, i1 = i - 1; i > 0; --i, --i1) {
    365         result.digits[i] = ((result.digits[i] << bits) & maxDigitVal) |
    366                            ((result.digits[i1] & highBitMasks[bits]) >>>
    367                             (rightBits));
    368     }
    369     result.digits[0] = ((result.digits[i] << bits) & maxDigitVal);
    370     result.isNeg = x.isNeg;
    371     return result;
    372 };
    373 
    374 var lowBitMasks = [0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F,
    375         0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF,
    376         0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF];
    377 
    378 RSAUtils.biShiftRight = function(x, n) {
    379     var digitCount = Math.floor(n / bitsPerDigit);
    380     var result = new BigInt();
    381     RSAUtils.arrayCopy(x.digits, digitCount, result.digits, 0,
    382               x.digits.length - digitCount);
    383     var bits = n % bitsPerDigit;
    384     var leftBits = bitsPerDigit - bits;
    385     for (var i = 0, i1 = i + 1; i < result.digits.length - 1; ++i, ++i1) {
    386         result.digits[i] = (result.digits[i] >>> bits) |
    387                            ((result.digits[i1] & lowBitMasks[bits]) << leftBits);
    388     }
    389     result.digits[result.digits.length - 1] >>>= bits;
    390     result.isNeg = x.isNeg;
    391     return result;
    392 };
    393 
    394 RSAUtils.biMultiplyByRadixPower = function(x, n) {
    395     var result = new BigInt();
    396     RSAUtils.arrayCopy(x.digits, 0, result.digits, n, result.digits.length - n);
    397     return result;
    398 };
    399 
    400 RSAUtils.biDivideByRadixPower = function(x, n) {
    401     var result = new BigInt();
    402     RSAUtils.arrayCopy(x.digits, n, result.digits, 0, result.digits.length - n);
    403     return result;
    404 };
    405 
    406 RSAUtils.biModuloByRadixPower = function(x, n) {
    407     var result = new BigInt();
    408     RSAUtils.arrayCopy(x.digits, 0, result.digits, 0, n);
    409     return result;
    410 };
    411 
    412 RSAUtils.biCompare = function(x, y) {
    413     if (x.isNeg != y.isNeg) {
    414         return 1 - 2 * Number(x.isNeg);
    415     }
    416     for (var i = x.digits.length - 1; i >= 0; --i) {
    417         if (x.digits[i] != y.digits[i]) {
    418             if (x.isNeg) {
    419                 return 1 - 2 * Number(x.digits[i] > y.digits[i]);
    420             } else {
    421                 return 1 - 2 * Number(x.digits[i] < y.digits[i]);
    422             }
    423         }
    424     }
    425     return 0;
    426 };
    427 
    428 RSAUtils.biDivideModulo = function(x, y) {
    429     var nb = RSAUtils.biNumBits(x);
    430     var tb = RSAUtils.biNumBits(y);
    431     var origYIsNeg = y.isNeg;
    432     var q, r;
    433     if (nb < tb) {
    434         // |x| < |y|
    435         if (x.isNeg) {
    436             q = RSAUtils.biCopy(bigOne);
    437             q.isNeg = !y.isNeg;
    438             x.isNeg = false;
    439             y.isNeg = false;
    440             r = biSubtract(y, x);
    441             // Restore signs, 'cause they're references.
    442             x.isNeg = true;
    443             y.isNeg = origYIsNeg;
    444         } else {
    445             q = new BigInt();
    446             r = RSAUtils.biCopy(x);
    447         }
    448         return [q, r];
    449     }
    450 
    451     q = new BigInt();
    452     r = x;
    453 
    454     // Normalize Y.
    455     var t = Math.ceil(tb / bitsPerDigit) - 1;
    456     var lambda = 0;
    457     while (y.digits[t] < biHalfRadix) {
    458         y = RSAUtils.biShiftLeft(y, 1);
    459         ++lambda;
    460         ++tb;
    461         t = Math.ceil(tb / bitsPerDigit) - 1;
    462     }
    463     // Shift r over to keep the quotient constant. We'll shift the
    464     // remainder back at the end.
    465     r = RSAUtils.biShiftLeft(r, lambda);
    466     nb += lambda; // Update the bit count for x.
    467     var n = Math.ceil(nb / bitsPerDigit) - 1;
    468 
    469     var b = RSAUtils.biMultiplyByRadixPower(y, n - t);
    470     while (RSAUtils.biCompare(r, b) != -1) {
    471         ++q.digits[n - t];
    472         r = RSAUtils.biSubtract(r, b);
    473     }
    474     for (var i = n; i > t; --i) {
    475     var ri = (i >= r.digits.length) ? 0 : r.digits[i];
    476     var ri1 = (i - 1 >= r.digits.length) ? 0 : r.digits[i - 1];
    477     var ri2 = (i - 2 >= r.digits.length) ? 0 : r.digits[i - 2];
    478     var yt = (t >= y.digits.length) ? 0 : y.digits[t];
    479     var yt1 = (t - 1 >= y.digits.length) ? 0 : y.digits[t - 1];
    480         if (ri == yt) {
    481             q.digits[i - t - 1] = maxDigitVal;
    482         } else {
    483             q.digits[i - t - 1] = Math.floor((ri * biRadix + ri1) / yt);
    484         }
    485 
    486         var c1 = q.digits[i - t - 1] * ((yt * biRadix) + yt1);
    487         var c2 = (ri * biRadixSquared) + ((ri1 * biRadix) + ri2);
    488         while (c1 > c2) {
    489             --q.digits[i - t - 1];
    490             c1 = q.digits[i - t - 1] * ((yt * biRadix) | yt1);
    491             c2 = (ri * biRadix * biRadix) + ((ri1 * biRadix) + ri2);
    492         }
    493 
    494         b = RSAUtils.biMultiplyByRadixPower(y, i - t - 1);
    495         r = RSAUtils.biSubtract(r, RSAUtils.biMultiplyDigit(b, q.digits[i - t - 1]));
    496         if (r.isNeg) {
    497             r = RSAUtils.biAdd(r, b);
    498             --q.digits[i - t - 1];
    499         }
    500     }
    501     r = RSAUtils.biShiftRight(r, lambda);
    502     // Fiddle with the signs and stuff to make sure that 0 <= r < y.
    503     q.isNeg = x.isNeg != origYIsNeg;
    504     if (x.isNeg) {
    505         if (origYIsNeg) {
    506             q = RSAUtils.biAdd(q, bigOne);
    507         } else {
    508             q = RSAUtils.biSubtract(q, bigOne);
    509         }
    510         y = RSAUtils.biShiftRight(y, lambda);
    511         r = RSAUtils.biSubtract(y, r);
    512     }
    513     // Check for the unbelievably stupid degenerate case of r == -0.
    514     if (r.digits[0] == 0 && RSAUtils.biHighIndex(r) == 0) r.isNeg = false;
    515 
    516     return [q, r];
    517 };
    518 
    519 RSAUtils.biDivide = function(x, y) {
    520     return RSAUtils.biDivideModulo(x, y)[0];
    521 };
    522 
    523 RSAUtils.biModulo = function(x, y) {
    524     return RSAUtils.biDivideModulo(x, y)[1];
    525 };
    526 
    527 RSAUtils.biMultiplyMod = function(x, y, m) {
    528     return RSAUtils.biModulo(RSAUtils.biMultiply(x, y), m);
    529 };
    530 
    531 RSAUtils.biPow = function(x, y) {
    532     var result = bigOne;
    533     var a = x;
    534     while (true) {
    535         if ((y & 1) != 0) result = RSAUtils.biMultiply(result, a);
    536         y >>= 1;
    537         if (y == 0) break;
    538         a = RSAUtils.biMultiply(a, a);
    539     }
    540     return result;
    541 };
    542 
    543 RSAUtils.biPowMod = function(x, y, m) {
    544     var result = bigOne;
    545     var a = x;
    546     var k = y;
    547     while (true) {
    548         if ((k.digits[0] & 1) != 0) result = RSAUtils.biMultiplyMod(result, a, m);
    549         k = RSAUtils.biShiftRight(k, 1);
    550         if (k.digits[0] == 0 && RSAUtils.biHighIndex(k) == 0) break;
    551         a = RSAUtils.biMultiplyMod(a, a, m);
    552     }
    553     return result;
    554 };
    555 
    556 
    557 $w.BarrettMu = function(m) {
    558     this.modulus = RSAUtils.biCopy(m);
    559     this.k = RSAUtils.biHighIndex(this.modulus) + 1;
    560     var b2k = new BigInt();
    561     b2k.digits[2 * this.k] = 1; // b2k = b^(2k)
    562     this.mu = RSAUtils.biDivide(b2k, this.modulus);
    563     this.bkplus1 = new BigInt();
    564     this.bkplus1.digits[this.k + 1] = 1; // bkplus1 = b^(k+1)
    565     this.modulo = BarrettMu_modulo;
    566     this.multiplyMod = BarrettMu_multiplyMod;
    567     this.powMod = BarrettMu_powMod;
    568 };
    569 
    570 function BarrettMu_modulo(x) {
    571     var $dmath = RSAUtils;
    572     var q1 = $dmath.biDivideByRadixPower(x, this.k - 1);
    573     var q2 = $dmath.biMultiply(q1, this.mu);
    574     var q3 = $dmath.biDivideByRadixPower(q2, this.k + 1);
    575     var r1 = $dmath.biModuloByRadixPower(x, this.k + 1);
    576     var r2term = $dmath.biMultiply(q3, this.modulus);
    577     var r2 = $dmath.biModuloByRadixPower(r2term, this.k + 1);
    578     var r = $dmath.biSubtract(r1, r2);
    579     if (r.isNeg) {
    580         r = $dmath.biAdd(r, this.bkplus1);
    581     }
    582     var rgtem = $dmath.biCompare(r, this.modulus) >= 0;
    583     while (rgtem) {
    584         r = $dmath.biSubtract(r, this.modulus);
    585         rgtem = $dmath.biCompare(r, this.modulus) >= 0;
    586     }
    587     return r;
    588 }
    589 
    590 function BarrettMu_multiplyMod(x, y) {
    591     /*
    592     x = this.modulo(x);
    593     y = this.modulo(y);
    594     */
    595     var xy = RSAUtils.biMultiply(x, y);
    596     return this.modulo(xy);
    597 }
    598 
    599 function BarrettMu_powMod(x, y) {
    600     var result = new BigInt();
    601     result.digits[0] = 1;
    602     var a = x;
    603     var k = y;
    604     while (true) {
    605         if ((k.digits[0] & 1) != 0) result = this.multiplyMod(result, a);
    606         k = RSAUtils.biShiftRight(k, 1);
    607         if (k.digits[0] == 0 && RSAUtils.biHighIndex(k) == 0) break;
    608         a = this.multiplyMod(a, a);
    609     }
    610     return result;
    611 }
    612 
    613 var RSAKeyPair = function(encryptionExponent, decryptionExponent, modulus) {
    614     var $dmath = RSAUtils;
    615     this.e = $dmath.biFromHex(encryptionExponent);
    616     this.d = $dmath.biFromHex(decryptionExponent);
    617     this.m = $dmath.biFromHex(modulus);
    618     // We can do two bytes per digit, so
    619     // chunkSize = 2 * (number of digits in modulus - 1).
    620     // Since biHighIndex returns the high index, not the number of digits, 1 has
    621     // already been subtracted.
    622     this.chunkSize = 2 * $dmath.biHighIndex(this.m);
    623     this.radix = 16;
    624     this.barrett = new $w.BarrettMu(this.m);
    625 };
    626 
    627 RSAUtils.getKeyPair = function(encryptionExponent, decryptionExponent, modulus) {
    628     return new RSAKeyPair(encryptionExponent, decryptionExponent, modulus);
    629 };
    630 
    631 if(typeof $w.twoDigit === 'undefined') {
    632     $w.twoDigit = function(n) {
    633         return (n < 10 ? "0" : "") + String(n);
    634     };
    635 }
    636 
    637 // Altered by Rob Saunders (rob@robsaunders.net). New routine pads the
    638 // string after it has been converted to an array. This fixes an
    639 // incompatibility with Flash MX's ActionScript.
    640 RSAUtils.encryptedString = function(key, s) {
    641     var a = [];
    642     var sl = s.length;
    643     var i = 0;
    644     while (i < sl) {
    645         a[i] = s.charCodeAt(i);
    646         i++;
    647     }
    648 
    649     while (a.length % key.chunkSize != 0) {
    650         a[i++] = 0;
    651     }
    652 
    653     var al = a.length;
    654     var result = "";
    655     var j, k, block;
    656     for (i = 0; i < al; i += key.chunkSize) {
    657         block = new BigInt();
    658         j = 0;
    659         for (k = i; k < i + key.chunkSize; ++j) {
    660             block.digits[j] = a[k++];
    661             block.digits[j] += a[k++] << 8;
    662         }
    663         var crypt = key.barrett.powMod(block, key.e);
    664         var text = key.radix == 16 ? RSAUtils.biToHex(crypt) : RSAUtils.biToString(crypt, key.radix);
    665         result += text + " ";
    666     }
    667     return result.substring(0, result.length - 1); // Remove last space.
    668 };
    669 
    670 RSAUtils.decryptedString = function(key, s) {
    671     var blocks = s.split(" ");
    672     var result = "";
    673     var i, j, block;
    674     for (i = 0; i < blocks.length; ++i) {
    675         var bi;
    676         if (key.radix == 16) {
    677             bi = RSAUtils.biFromHex(blocks[i]);
    678         }
    679         else {
    680             bi = RSAUtils.biFromString(blocks[i], key.radix);
    681         }
    682         block = key.barrett.powMod(bi, key.d);
    683         for (j = 0; j <= RSAUtils.biHighIndex(block); ++j) {
    684             result += String.fromCharCode(block.digits[j] & 255,
    685                                           block.digits[j] >> 8);
    686         }
    687     }
    688     // Remove trailing null, if any.
    689     if (result.charCodeAt(result.length - 1) == 0) {
    690         result = result.substring(0, result.length - 1);
    691     }
    692     return result;
    693 };
    694 
    695 RSAUtils.setMaxDigits(130);
    696 
    697 })(window);
    security.js
     1 <%
     2         HashMap<String, Object> map = RSAUtil.getKeys();    
     3     //生成公钥和私钥    
     4     RSAPublicKey publicKey = (RSAPublicKey) map.get("public");    
     5     RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");  
     6       
     7     session.setAttribute("privateKey", privateKey);//私钥保存在session中,用于解密  
     8       
     9     //公钥信息保存在页面,用于加密  
    10     String publicKeyExponent = publicKey.getPublicExponent().toString(16);  
    11     String publicKeyModulus = publicKey.getModulus().toString(16);  
    12     request.setAttribute("publicKeyExponent", publicKeyExponent);  
    13     request.setAttribute("publicKeyModulus", publicKeyModulus);  
    14 %> 
    15        
    16 .......
    17 
    18             function checkParam(){
    19                 RSAUtils.setMaxDigits(200);
    20                 var key = new RSAUtils.getKeyPair("${publicKeyExponent}", "", "${publicKeyModulus}");
    21                 document.getElementById("userName").value = RSAUtils.encryptedString(key,document.getElementById("userName").value);
    22                 document.getElementById("passWord").value = RSAUtils.encryptedString(key,document.getElementById("passWord").value);
    23                 document.form1.action.value="authenticate";
    24                 return true;
    25             }
    login.jsp

    RSAUtil

      1 package com.bxw.util;
      2 
      3 import java.math.BigInteger;    
      4 import java.security.KeyFactory;    
      5 import java.security.KeyPair;    
      6 import java.security.KeyPairGenerator;    
      7 import java.security.NoSuchAlgorithmException;    
      8 import java.security.interfaces.RSAPrivateKey;    
      9 import java.security.interfaces.RSAPublicKey;    
     10 import java.security.spec.RSAPrivateKeySpec;    
     11 import java.security.spec.RSAPublicKeySpec;    
     12 import java.util.HashMap;   
     13 import javax.crypto.Cipher;   
     14   
     15 public class RSAUtil {  
     16     /**  
     17      * 生成公钥和私钥  
     18      * @throws NoSuchAlgorithmException   
     19      *  
     20      */    
     21     public static HashMap<String, Object> getKeys() throws NoSuchAlgorithmException{    
     22         HashMap<String, Object> map = new HashMap<String, Object>();    
     23         KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());    
     24         keyPairGen.initialize(1024);    
     25         KeyPair keyPair = keyPairGen.generateKeyPair();    
     26         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();    
     27         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();    
     28         map.put("public", publicKey);    
     29         map.put("private", privateKey);    
     30         return map;    
     31     }    
     32     /**  
     33      * 使用模和指数生成RSA公钥  
     34      *   
     35      *   
     36      * @param modulus  
     37      *            模  
     38      * @param exponent  
     39      *            指数  
     40      * @return  
     41      */    
     42     public static RSAPublicKey getPublicKey(String modulus, String exponent) {    
     43         try {    
     44             BigInteger b1 = new BigInteger(modulus);    
     45             BigInteger b2 = new BigInteger(exponent);    
     46             KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());    
     47             RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);    
     48             return (RSAPublicKey) keyFactory.generatePublic(keySpec);    
     49         } catch (Exception e) {    
     50             e.printStackTrace();    
     51             return null;    
     52         }    
     53     }    
     54     
     55     /**  
     56      * 使用模和指数生成RSA私钥  
     57       
     58      * /None/NoPadding】  
     59      *   
     60      * @param modulus  
     61      *            模  
     62      * @param exponent  
     63      *            指数  
     64      * @return  
     65      */    
     66     public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {    
     67         try {    
     68             BigInteger b1 = new BigInteger(modulus);    
     69             BigInteger b2 = new BigInteger(exponent);    
     70             KeyFactory keyFactory = KeyFactory.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());    
     71             RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);    
     72             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);    
     73         } catch (Exception e) {    
     74             e.printStackTrace();    
     75             return null;    
     76         }    
     77     }    
     78     
     79     /**  
     80      * 公钥加密  
     81      *   
     82      * @param data  
     83      * @param publicKey  
     84      * @return  
     85      * @throws Exception  
     86      */    
     87     public static String encryptByPublicKey(String data, RSAPublicKey publicKey)    
     88             throws Exception {    
     89         Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());    
     90         cipher.init(Cipher.ENCRYPT_MODE, publicKey);    
     91         // 模长    
     92         int key_len = publicKey.getModulus().bitLength() / 8;    
     93         // 加密数据长度 <= 模长-11    
     94         String[] datas = splitString(data, key_len - 11);    
     95         String mi = "";    
     96         //如果明文长度大于模长-11则要分组加密    
     97         for (String s : datas) {    
     98             mi += bcd2Str(cipher.doFinal(s.getBytes()));    
     99         }    
    100         return mi;    
    101     }    
    102     
    103     /**  
    104      * 私钥解密  
    105      *   
    106      * @param data  
    107      * @param privateKey  
    108      * @return  
    109      * @throws Exception  
    110      */    
    111     public static String decryptByPrivateKey(String data, RSAPrivateKey privateKey)    
    112             throws Exception {    
    113         Cipher cipher = Cipher.getInstance("RSA", new org.bouncycastle.jce.provider.BouncyCastleProvider());    
    114         cipher.init(Cipher.DECRYPT_MODE, privateKey);    
    115         //模长    
    116         int key_len = privateKey.getModulus().bitLength() / 8;    
    117         byte[] bytes = data.getBytes();    
    118         byte[] bcd = ASCII_To_BCD(bytes, bytes.length);    
    119         //System.err.println(bcd.length);    
    120         //如果密文长度大于模长则要分组解密    
    121         String ming = "";    
    122         byte[][] arrays = splitArray(bcd, key_len);    
    123         for(byte[] arr : arrays){    
    124             ming += new String(cipher.doFinal(arr));    
    125         }    
    126         return ming;    
    127     }    
    128     /**  
    129      * ASCII码转BCD码  
    130      *   
    131      */    
    132     public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {    
    133         byte[] bcd = new byte[asc_len / 2];    
    134         int j = 0;    
    135         for (int i = 0; i < (asc_len + 1) / 2; i++) {    
    136             bcd[i] = asc_to_bcd(ascii[j++]);    
    137             bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));    
    138         }    
    139         return bcd;    
    140     }    
    141     public static byte asc_to_bcd(byte asc) {    
    142         byte bcd;    
    143     
    144         if ((asc >= '0') && (asc <= '9'))    
    145             bcd = (byte) (asc - '0');    
    146         else if ((asc >= 'A') && (asc <= 'F'))    
    147             bcd = (byte) (asc - 'A' + 10);    
    148         else if ((asc >= 'a') && (asc <= 'f'))    
    149             bcd = (byte) (asc - 'a' + 10);    
    150         else    
    151             bcd = (byte) (asc - 48);    
    152         return bcd;    
    153     }    
    154     /**  
    155      * BCD转字符串  
    156      */    
    157     public static String bcd2Str(byte[] bytes) {    
    158         char temp[] = new char[bytes.length * 2], val;    
    159     
    160         for (int i = 0; i < bytes.length; i++) {    
    161             val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);    
    162             temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');    
    163     
    164             val = (char) (bytes[i] & 0x0f);    
    165             temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');    
    166         }    
    167         return new String(temp);    
    168     }    
    169     /**  
    170      * 拆分字符串  
    171      */    
    172     public static String[] splitString(String string, int len) {    
    173         int x = string.length() / len;    
    174         int y = string.length() % len;    
    175         int z = 0;    
    176         if (y != 0) {    
    177             z = 1;    
    178         }    
    179         String[] strings = new String[x + z];    
    180         String str = "";    
    181         for (int i=0; i<x+z; i++) {    
    182             if (i==x+z-1 && y!=0) {    
    183                 str = string.substring(i*len, i*len+y);    
    184             }else{    
    185                 str = string.substring(i*len, i*len+len);    
    186             }    
    187             strings[i] = str;    
    188         }    
    189         return strings;    
    190     }    
    191     /**  
    192      *拆分数组   
    193      */    
    194     public static byte[][] splitArray(byte[] data,int len){    
    195         int x = data.length / len;    
    196         int y = data.length % len;    
    197         int z = 0;    
    198         if(y!=0){    
    199             z = 1;    
    200         }    
    201         byte[][] arrays = new byte[x+z][];    
    202         byte[] arr;    
    203         for(int i=0; i<x+z; i++){    
    204             arr = new byte[len];    
    205             if(i==x+z-1 && y!=0){    
    206                 System.arraycopy(data, i*len, arr, 0, y);    
    207             }else{    
    208                 System.arraycopy(data, i*len, arr, 0, len);    
    209             }    
    210             arrays[i] = arr;    
    211         }    
    212         return arrays;    
    213     }  
    214     public static void main(String[] args) throws Exception{  
    215         HashMap<String, Object> map = getKeys();    
    216         //生成公钥和私钥    
    217         RSAPublicKey publicKey = (RSAPublicKey) map.get("public");    
    218         RSAPrivateKey privateKey = (RSAPrivateKey) map.get("private");    
    219             
    220         //
    221         String modulus = publicKey.getModulus().toString();    
    222         System.out.println("pubkey modulus="+modulus);  
    223         //公钥指数    
    224         String public_exponent = publicKey.getPublicExponent().toString();  
    225         System.out.println("pubkey exponent="+public_exponent);  
    226         //私钥指数    
    227         String private_exponent = privateKey.getPrivateExponent().toString();    
    228         System.out.println("private exponent="+private_exponent);  
    229         //明文    
    230         String ming = "111";    
    231         //使用模和指数生成公钥和私钥    
    232         RSAPublicKey pubKey = RSAUtil.getPublicKey(modulus, public_exponent);    
    233         RSAPrivateKey priKey = RSAUtil.getPrivateKey(modulus, private_exponent);    
    234         //加密后的密文    
    235         String mi = RSAUtil.encryptByPublicKey(ming, pubKey);    
    236         System.err.println("mi="+mi);    
    237         //解密后的明文    
    238         String ming2 = RSAUtil.decryptByPrivateKey(mi, priKey);    
    239         System.err.println("ming2="+ming2);    
    240     }  
    241 }  
    RSAUtil.java

    action层rsa解密

    1             RSAPrivateKey privateKey = (RSAPrivateKey) session.get("privateKey");  //获得秘钥
    2             try {
    3                 userName = new StringBuffer(RSAUtil.decryptByPrivateKey(userName,privateKey)).reverse().toString();
    4                 passWord = new StringBuffer(RSAUtil.decryptByPrivateKey(passWord,privateKey)).reverse().toString();
    5             } catch (Exception e) {
    6                 e.printStackTrace();
    7             }
    LoginAction.java
  • 相关阅读:
    sql经典语句大全
    经典SQL语句大全
    Bat命令学习
    [Microsoft][ODBC 驱动程序管理器] 在指定的 DSN 中,驱动程序和应用程序之间的体系结构不匹配
    配置WebSite的IIS时遇到的问题与解决方法
    数据库SQL优化大总结之 百万级数据库优化方案
    数据库索引以及优化
    搭建android开发环境
    SQL2008根据日志恢复
    WebService处理大数据量数据
  • 原文地址:https://www.cnblogs.com/popcornya/p/6780838.html
Copyright © 2011-2022 走看看