您好,欢迎访问一九零五行业门户网

PHP+JS+rsa数据加密传输实现代码

js端代码:
//文件base64.js: var b64map="abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz0123456789+/"; var b64pad="="; function hex2b64(h) { var i; var c; var ret = ""; for(i = 0; i+3 <= h.length; i+=3) { c = parseint(h.substring(i,i+3),16); ret += b64map.charat(c >> 6) + b64map.charat(c & 63); } if(i+1 == h.length) { c = parseint(h.substring(i,i+1),16); ret += b64map.charat(c << 2); } else if(i+2 == h.length) { c = parseint(h.substring(i,i+2),16); ret += b64map.charat(c >> 2) + b64map.charat((c & 3) << 4); } while((ret.length & 3) > 0) ret += b64pad; return ret; } // convert a base64 string to hex function b64tohex(s) { var ret = "" var i; var k = 0; // b64 state, 0-3 var slop; for(i = 0; i < s.length; ++i) { if(s.charat(i) == b64pad) break; v = b64map.indexof(s.charat(i)); if(v < 0) continue; if(k == 0) { ret += int2char(v >> 2); slop = v & 3; k = 1; } else if(k == 1) { ret += int2char((slop << 2) | (v >> 4)); slop = v & 0xf; k = 2; } else if(k == 2) { ret += int2char(slop); ret += int2char(v >> 2); slop = v & 3; k = 3; } else { ret += int2char((slop << 2) | (v >> 4)); ret += int2char(v & 0xf); k = 0; } } if(k == 1) ret += int2char(slop << 2); return ret; } // convert a base64 string to a byte/number array function b64toba(s) { //piggyback on b64tohex for now, optimize later var h = b64tohex(s); var i; var a = new array(); for(i = 0; 2*i < h.length; ++i) { a[i] = parseint(h.substring(2*i,2*i+2),16); } return a; } #文件jsbn.js // copyright (c) 2005 tom wu // all rights reserved. // see "license" for details. // basic javascript bn library - subset useful for rsa encryption. // bits per digit var dbits; // javascript engine analysis var canary = 0xdeadbeefcafe; var j_lm = ((canary&0xffffff)==0xefcafe); // (public) constructor function biginteger(a,b,c) { if(a != null) if("number" == typeof a) this.fromnumber(a,b,c); else if(b == null && "string" != typeof a) this.fromstring(a,256); else this.fromstring(a,b); } // return new, unset biginteger function nbi() { return new biginteger(null); } // am: compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // we need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i,x,w,j,c,n) { while(--n >= 0) { var v = x*this[i++]+w[j]+c; c = math.floor(v/0x4000000); w[j++] = v&0x3ffffff; } return c; } // am2 avoids a big mult-and-extract completely. // max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i,x,w,j,c,n) { var xl = x&0x7fff, xh = x>>15; while(--n >= 0) { var l = this[i]&0x7fff; var h = this[i++]>>15; var m = xh*l+h*xl; l = xl*l+((m&0x7fff)<<15)+w[j]+(c&0x3fffffff); c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); w[j++] = l&0x3fffffff; } return c; } // alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i,x,w,j,c,n) { var xl = x&0x3fff, xh = x>>14; while(--n >= 0) { var l = this[i]&0x3fff; var h = this[i++]>>14; var m = xh*l+h*xl; l = xl*l+((m&0x3fff)<<14)+w[j]+c; c = (l>>28)+(m>>14)+xh*h; w[j++] = l&0xfffffff; } return c; } if(j_lm && (navigator.appname == "microsoft internet explorer")) { biginteger.prototype.am = am2; dbits = 30; } else if(j_lm && (navigator.appname != "netscape")) { biginteger.prototype.am = am1; dbits = 26; } else { // mozilla/netscape seems to prefer am3 biginteger.prototype.am = am3; dbits = 28; } biginteger.prototype.db = dbits; biginteger.prototype.dm = ((1<<dbits)-1); biginteger.prototype.dv = (1<<dbits); var bi_fp = 52; biginteger.prototype.fv = math.pow(2,bi_fp); biginteger.prototype.f1 = bi_fp-dbits; biginteger.prototype.f2 = 2*dbits-bi_fp; // digit conversions var bi_rm = "0123456789abcdefghijklmnopqrstuvwxyz"; var bi_rc = new array(); var rr,vv; rr = "0".charcodeat(0); for(vv = 0; vv <= 9; ++vv) bi_rc[rr++] = vv; rr = "a".charcodeat(0); for(vv = 10; vv < 36; ++vv) bi_rc[rr++] = vv; rr = "a".charcodeat(0); for(vv = 10; vv < 36; ++vv) bi_rc[rr++] = vv; function int2char(n) { return bi_rm.charat(n); } function intat(s,i) { var c = bi_rc[s.charcodeat(i)]; return (c==null)?-1:c; } // (protected) copy this to r function bnpcopyto(r) { for(var i = this.t-1; i >= 0; --i) r[i] = this[i]; r.t = this.t; r.s = this.s; } // (protected) set from integer value x, -dv <= x < dv function bnpfromint(x) { this.t = 1; this.s = (x<0)?-1:0; if(x > 0) this[0] = x; else if(x < -1) this[0] = x+dv; else this.t = 0; } // return bigint initialized to value function nbv(i) { var r = nbi(); r.fromint(i); return r; } // (protected) set from string and radix function bnpfromstring(s,b) { var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 256) k = 8; // byte array else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else { this.fromradix(s,b); return; } this.t = 0; this.s = 0; var i = s.length, mi = false, sh = 0; while(--i >= 0) { var x = (k==8)?s[i]&0xff:intat(s,i); if(x < 0) { if(s.charat(i) == "-") mi = true; continue; } mi = false; if(sh == 0) this[this.t++] = x; else if(sh+k > this.db) { this[this.t-1] |= (x&((1<<(this.db-sh))-1))<<sh; this[this.t++] = (x>>(this.db-sh)); } else this[this.t-1] |= x<<sh; sh += k; if(sh >= this.db) sh -= this.db; } if(k == 8 && (s[0]&0x80) != 0) { this.s = -1; if(sh > 0) this[this.t-1] |= ((1<<(this.db-sh))-1)<<sh; } this.clamp(); if(mi) biginteger.zero.subto(this,this); } // (protected) clamp off excess high words function bnpclamp() { var c = this.s&this.dm; while(this.t > 0 && this[this.t-1] == c) --this.t; } // (public) return string representation in given radix function bntostring(b) { if(this.s < 0) return "-"+this.negate().tostring(b); var k; if(b == 16) k = 4; else if(b == 8) k = 3; else if(b == 2) k = 1; else if(b == 32) k = 5; else if(b == 4) k = 2; else return this.toradix(b); var km = (1<<k)-1, d, m = false, r = "", i = this.t; var p = this.db-(i*this.db)%k; if(i-- > 0) { if(p < this.db && (d = this[i]>>p) > 0) { m = true; r = int2char(d); } while(i >= 0) { if(p < k) { d = (this[i]&((1<<p)-1))<<(k-p); d |= this[--i]>>(p+=this.db-k); } else { d = (this[i]>>(p-=k))&km; if(p <= 0) { p += this.db; --i; } } if(d > 0) m = true; if(m) r += int2char(d); } } return m?r:"0"; } // (public) -this function bnnegate() { var r = nbi(); biginteger.zero.subto(this,r); return r; } // (public) |this| function bnabs() { return (this.s<0)?this.negate():this; } // (public) return + if this > a, - if this < a, 0 if equal function bncompareto(a) { var r = this.s-a.s; if(r != 0) return r; var i = this.t; r = i-a.t; if(r != 0) return r; while(--i >= 0) if((r=this[i]-a[i]) != 0) return r; return 0; } // returns bit length of the integer x function nbits(x) { var r = 1, t; if((t=x>>>16) != 0) { x = t; r += 16; } if((t=x>>8) != 0) { x = t; r += 8; } if((t=x>>4) != 0) { x = t; r += 4; } if((t=x>>2) != 0) { x = t; r += 2; } if((t=x>>1) != 0) { x = t; r += 1; } return r; } // (public) return the number of bits in "this" function bnbitlength() { if(this.t <= 0) return 0; return this.db*(this.t-1)+nbits(this[this.t-1]^(this.s&this.dm)); } // (protected) r = this << n*db function bnpdlshiftto(n,r) { var i; for(i = this.t-1; i >= 0; --i) r[i+n] = this[i]; for(i = n-1; i >= 0; --i) r[i] = 0; r.t = this.t+n; r.s = this.s; } // (protected) r = this >> n*db function bnpdrshiftto(n,r) { for(var i = n; i < this.t; ++i) r[i-n] = this[i]; r.t = math.max(this.t-n,0); r.s = this.s; } // (protected) r = this << n function bnplshiftto(n,r) { var bs = n%this.db; var cbs = this.db-bs; var bm = (1<<cbs)-1; var ds = math.floor(n/this.db), c = (this.s<<bs)&this.dm, i; for(i = this.t-1; i >= 0; --i) { r[i+ds+1] = (this[i]>>cbs)|c; c = (this[i]&bm)<<bs; } for(i = ds-1; i >= 0; --i) r[i] = 0; r[ds] = c; r.t = this.t+ds+1; r.s = this.s; r.clamp(); } // (protected) r = this >> n function bnprshiftto(n,r) { r.s = this.s; var ds = math.floor(n/this.db); if(ds >= this.t) { r.t = 0; return; } var bs = n%this.db; var cbs = this.db-bs; var bm = (1<<bs)-1; r[0] = this[ds]>>bs; for(var i = ds+1; i < this.t; ++i) { r[i-ds-1] |= (this[i]&bm)<<cbs; r[i-ds] = this[i]>>bs; } if(bs > 0) r[this.t-ds-1] |= (this.s&bm)<<cbs; r.t = this.t-ds; r.clamp(); } // (protected) r = this - a function bnpsubto(a,r) { var i = 0, c = 0, m = math.min(a.t,this.t); while(i < m) { c += this[i]-a[i]; r[i++] = c&this.dm; c >>= this.db; } if(a.t < this.t) { c -= a.s; while(i < this.t) { c += this[i]; r[i++] = c&this.dm; c >>= this.db; } c += this.s; } else { c += this.s; while(i < a.t) { c -= a[i]; r[i++] = c&this.dm; c >>= this.db; } c -= a.s; } r.s = (c<0)?-1:0; if(c < -1) r[i++] = this.dv+c; else if(c > 0) r[i++] = c; r.t = i; r.clamp(); } // (protected) r = this * a, r != this,a (hac 14.12) // "this" should be the larger one if appropriate. function bnpmultiplyto(a,r) { var x = this.abs(), y = a.abs(); var i = x.t; r.t = i+y.t; while(--i >= 0) r[i] = 0; for(i = 0; i < y.t; ++i) r[i+x.t] = x.am(0,y[i],r,i,0,x.t); r.s = 0; r.clamp(); if(this.s != a.s) biginteger.zero.subto(r,r); } // (protected) r = this^2, r != this (hac 14.16) function bnpsquareto(r) { var x = this.abs(); var i = r.t = 2*x.t; while(--i >= 0) r[i] = 0; for(i = 0; i < x.t-1; ++i) { var c = x.am(i,x[i],r,2*i,0,1); if((r[i+x.t]+=x.am(i+1,2*x[i],r,2*i+1,c,x.t-i-1)) >= x.dv) { r[i+x.t] -= x.dv; r[i+x.t+1] = 1; } } if(r.t > 0) r[r.t-1] += x.am(i,x[i],r,2*i,0,1); r.s = 0; r.clamp(); } // (protected) divide this by m, quotient and remainder to q, r (hac 14.20) // r != q, this != m. q or r may be null. function bnpdivremto(m,q,r) { var pm = m.abs(); if(pm.t <= 0) return; var pt = this.abs(); if(pt.t < pm.t) { if(q != null) q.fromint(0); if(r != null) this.copyto(r); return; } if(r == null) r = nbi(); var y = nbi(), ts = this.s, ms = m.s; var nsh = this.db-nbits(pm[pm.t-1]); // normalize modulus if(nsh > 0) { pm.lshiftto(nsh,y); pt.lshiftto(nsh,r); } else { pm.copyto(y); pt.copyto(r); } var ys = y.t; var y0 = y[ys-1]; if(y0 == 0) return; var yt = y0*(1<<this.f1)+((ys>1)?y[ys-2]>>this.f2:0); var d1 = this.fv/yt, d2 = (1<<this.f1)/yt, e = 1<<this.f2; var i = r.t, j = i-ys, t = (q==null)?nbi():q; y.dlshiftto(j,t); if(r.compareto(t) >= 0) { r[r.t++] = 1; r.subto(t,r); } biginteger.one.dlshiftto(ys,t); t.subto(y,y); // "negative" y so we can replace sub with am later while(y.t < ys) y[y.t++] = 0; while(--j >= 0) { // estimate quotient digit var qd = (r[--i]==y0)?this.dm:math.floor(r[i]*d1+(r[i-1]+e)*d2); if((r[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // try it out y.dlshiftto(j,t); r.subto(t,r); while(r[i] < --qd) r.subto(t,r); } } if(q != null) { r.drshiftto(ys,q); if(ts != ms) biginteger.zero.subto(q,q); } r.t = ys; r.clamp(); if(nsh > 0) r.rshiftto(nsh,r); // denormalize remainder if(ts < 0) biginteger.zero.subto(r,r); } // (public) this mod a function bnmod(a) { var r = nbi(); this.abs().divremto(a,null,r); if(this.s < 0 && r.compareto(biginteger.zero) > 0) a.subto(r,r); return r; } // modular reduction using "classic" algorithm function classic(m) { this.m = m; } function cconvert(x) { if(x.s < 0 || x.compareto(this.m) >= 0) return x.mod(this.m); else return x; } function crevert(x) { return x; } function creduce(x) { x.divremto(this.m,null,x); } function cmulto(x,y,r) { x.multiplyto(y,r); this.reduce(r); } function csqrto(x,r) { x.squareto(r); this.reduce(r); } classic.prototype.convert = cconvert; classic.prototype.revert = crevert; classic.prototype.reduce = creduce; classic.prototype.multo = cmulto; classic.prototype.sqrto = csqrto; // (protected) return "-1/this % 2^db"; useful for mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // js multiply "overflows" differently from c/c++, so care is needed here. function bnpinvdigit() { if(this.t < 1) return 0; var x = this[0]; if((x&1) == 0) return 0; var y = x&3; // y == 1/x mod 2^2 y = (y*(2-(x&0xf)*y))&0xf; // y == 1/x mod 2^4 y = (y*(2-(x&0xff)*y))&0xff; // y == 1/x mod 2^8 y = (y*(2-(((x&0xffff)*y)&0xffff)))&0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod dv directly; // assumes 16 < db <= 32 and assumes ability to handle 48-bit ints y = (y*(2-x*y%this.dv))%this.dv; // y == 1/x mod 2^dbits // we really want the negative inverse, and -dv < y < dv return (y>0)?this.dv-y:-y; } // montgomery reduction function montgomery(m) { this.m = m; this.mp = m.invdigit(); this.mpl = this.mp&0x7fff; this.mph = this.mp>>15; this.um = (1<<(m.db-15))-1; this.mt2 = 2*m.t; } // xr mod m function montconvert(x) { var r = nbi(); x.abs().dlshiftto(this.m.t,r); r.divremto(this.m,null,r); if(x.s < 0 && r.compareto(biginteger.zero) > 0) this.m.subto(r,r); return r; } // x/r mod m function montrevert(x) { var r = nbi(); x.copyto(r); this.reduce(r); return r; } // x = x/r mod m (hac 14.32) function montreduce(x) { while(x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0; for(var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod dv var j = x[i]&0x7fff; var u0 = (j*this.mpl+(((j*this.mph+(x[i]>>15)*this.mpl)&this.um)<<15))&x.dm; // use am to combine the multiply-shift-add into one call j = i+this.m.t; x[j] += this.m.am(0,u0,x,i,0,this.m.t); // propagate carry while(x[j] >= x.dv) { x[j] -= x.dv; x[++j]++; } } x.clamp(); x.drshiftto(this.m.t,x); if(x.compareto(this.m) >= 0) x.subto(this.m,x); } // r = "x^2/r mod m"; x != r function montsqrto(x,r) { x.squareto(r); this.reduce(r); } // r = "xy/r mod m"; x,y != r function montmulto(x,y,r) { x.multiplyto(y,r); this.reduce(r); } montgomery.prototype.convert = montconvert; montgomery.prototype.revert = montrevert; montgomery.prototype.reduce = montreduce; montgomery.prototype.multo = montmulto; montgomery.prototype.sqrto = montsqrto; // (protected) true iff this is even function bnpiseven() { return ((this.t>0)?(this[0]&1):this.s) == 0; } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (hac 14.79) function bnpexp(e,z) { if(e > 0xffffffff || e < 1) return biginteger.one; var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; g.copyto(r); while(--i >= 0) { z.sqrto(r,r2); if((e&(1<<i)) > 0) z.multo(r2,g,r); else { var t = r; r = r2; r2 = t; } } return z.revert(r); } // (public) this^e % m, 0 <= e < 2^32 function bnmodpowint(e,m) { var z; if(e < 256 || m.iseven()) z = new classic(m); else z = new montgomery(m); return this.exp(e,z); } // protected biginteger.prototype.copyto = bnpcopyto; biginteger.prototype.fromint = bnpfromint; biginteger.prototype.fromstring = bnpfromstring; biginteger.prototype.clamp = bnpclamp; biginteger.prototype.dlshiftto = bnpdlshiftto; biginteger.prototype.drshiftto = bnpdrshiftto; biginteger.prototype.lshiftto = bnplshiftto; biginteger.prototype.rshiftto = bnprshiftto; biginteger.prototype.subto = bnpsubto; biginteger.prototype.multiplyto = bnpmultiplyto; biginteger.prototype.squareto = bnpsquareto; biginteger.prototype.divremto = bnpdivremto; biginteger.prototype.invdigit = bnpinvdigit; biginteger.prototype.iseven = bnpiseven; biginteger.prototype.exp = bnpexp; // public biginteger.prototype.tostring = bntostring; biginteger.prototype.negate = bnnegate; biginteger.prototype.abs = bnabs; biginteger.prototype.compareto = bncompareto; biginteger.prototype.bitlength = bnbitlength; biginteger.prototype.mod = bnmod; biginteger.prototype.modpowint = bnmodpowint; // "constants" biginteger.zero = nbv(0); biginteger.one = nbv(1); #文件prng4.js // prng4.js - uses arcfour as a prng function arcfour() { this.i = 0; this.j = 0; this.s = new array(); } // initialize arcfour context from key, an array of ints, each from [0..255] function arc4init(key) { var i, j, t; for(i = 0; i < 256; ++i) this.s[i] = i; j = 0; for(i = 0; i < 256; ++i) { j = (j + this.s[i] + key[i % key.length]) & 255; t = this.s[i]; this.s[i] = this.s[j]; this.s[j] = t; } this.i = 0; this.j = 0; } function arc4next() { var t; this.i = (this.i + 1) & 255; this.j = (this.j + this.s[this.i]) & 255; t = this.s[this.i]; this.s[this.i] = this.s[this.j]; this.s[this.j] = t; return this.s[(t + this.s[this.i]) & 255]; } arcfour.prototype.init = arc4init; arcfour.prototype.next = arc4next; // plug in your rng constructor here function prng_newstate() { return new arcfour(); } // pool size must be a multiple of 4 and greater than 32. // an array of bytes the size of the pool will be passed to init() var rng_psize = 256; 文件:rng.js // random number generator - requires a prng backend, e.g. prng4.js // for best results, put code like // <body onclick='rng_seed_time();' onkeypress='rng_seed_time();'> // in your main html document. var rng_state; var rng_pool; var rng_pptr; // mix in a 32-bit integer into the pool function rng_seed_int(x) { rng_pool[rng_pptr++] ^= x & 255; rng_pool[rng_pptr++] ^= (x >> 8) & 255; rng_pool[rng_pptr++] ^= (x >> 16) & 255; rng_pool[rng_pptr++] ^= (x >> 24) & 255; if(rng_pptr >= rng_psize) rng_pptr -= rng_psize; } // mix in the current time (w/milliseconds) into the pool function rng_seed_time() { rng_seed_int(new date().gettime()); } // initialize the pool with junk if needed. if(rng_pool == null) { rng_pool = new array(); rng_pptr = 0; var t; if(navigator.appname == "netscape" && navigator.appversion < "5" && window.crypto) { // extract entropy (256 bits) from ns4 rng if available var z = window.crypto.random(32); for(t = 0; t < z.length; ++t) rng_pool[rng_pptr++] = z.charcodeat(t) & 255; } while(rng_pptr < rng_psize) { // extract some randomness from math.random() t = math.floor(65536 * math.random()); rng_pool[rng_pptr++] = t >>> 8; rng_pool[rng_pptr++] = t & 255; } rng_pptr = 0; rng_seed_time(); //rng_seed_int(window.screenx); //rng_seed_int(window.screeny); } function rng_get_byte() { if(rng_state == null) { rng_seed_time(); rng_state = prng_newstate(); rng_state.init(rng_pool); for(rng_pptr = 0; rng_pptr < rng_pool.length; ++rng_pptr) rng_pool[rng_pptr] = 0; rng_pptr = 0; //rng_pool = null; } // todo: allow reseeding after first request return rng_state.next(); } function rng_get_bytes(ba) { var i; for(i = 0; i < ba.length; ++i) ba[i] = rng_get_byte(); } function securerandom() {} securerandom.prototype.nextbytes = rng_get_bytes; #文件:rsa.js // depends on jsbn.js and rng.js // version 1.1: support utf-8 encoding in pkcs1pad2 // convert a (hex) string to a bignum object function parsebigint(str,r) { return new biginteger(str,r); } function linebrk(s,n) { var ret = ""; var i = 0; while(i + n < s.length) { ret += s.substring(i,i+n) + "\n"; i += n; } return ret + s.substring(i,s.length); } function byte2hex(b) { if(b < 0x10) return "0" + b.tostring(16); else return b.tostring(16); } // pkcs#1 (type 2, random) pad input string s to n bytes, and return a bigint function pkcs1pad2(s,n) { if(n < s.length + 11) { // todo: fix for utf-8 alert("message too long for rsa"); return null; } var ba = new array(); var i = s.length - 1; while(i >= 0 && n > 0) { var c = s.charcodeat(i--); if(c < 128) { // encode using utf-8 ba[--n] = c; } else if((c > 127) && (c < 2048)) { ba[--n] = (c & 63) | 128; ba[--n] = (c >> 6) | 192; } else { ba[--n] = (c & 63) | 128; ba[--n] = ((c >> 6) & 63) | 128; ba[--n] = (c >> 12) | 224; } } ba[--n] = 0; var rng = new securerandom(); var x = new array(); while(n > 2) { // random non-zero pad x[0] = 0; while(x[0] == 0) rng.nextbytes(x); ba[--n] = x[0]; } ba[--n] = 2; ba[--n] = 0; return new biginteger(ba); } // "empty" rsa key constructor function rsakey() { this.n = null; this.e = 0; this.d = null; this.p = null; this.q = null; this.dmp1 = null; this.dmq1 = null; this.coeff = null; } // set the public key fields n and e from hex strings function rsasetpublic(n,e) { if(n != null && e != null && n.length > 0 && e.length > 0) { this.n = parsebigint(n,16); this.e = parseint(e,16); } else alert("invalid rsa public key"); } // perform raw public operation on "x": return x^e (mod n) function rsadopublic(x) { return x.modpowint(this.e, this.n); } // return the pkcs#1 rsa encryption of "text" as an even-length hex string function rsaencrypt(text) { var m = pkcs1pad2(text,(this.n.bitlength()+7)>>3); if(m == null) return null; var c = this.dopublic(m); if(c == null) return null; var h = c.tostring(16); if((h.length & 1) == 0) return h; else return "0" + h; } // return the pkcs#1 rsa encryption of "text" as a base64-encoded string //function rsaencryptb64(text) { // var h = this.encrypt(text); // if(h) return hex2b64(h); else return null; //} // protected rsakey.prototype.dopublic = rsadopublic; // public rsakey.prototype.setpublic = rsasetpublic; rsakey.prototype.encrypt = rsaencrypt; //rsakey.prototype.encrypt_b64 = rsaencryptb64; html代码部分: 复制代码代码如下: <!doctype html public "-//w3c//dtd html 4.01 transitional//en"> <html> <head> <title>javascript rsa encryption demo</title> </head> <script language="javascript" type="text/javascript" src="./js/jsbn.js"></script> <script language="javascript" type="text/javascript" src="./js/prng4.js"></script> <script language="javascript" type="text/javascript" src="./js/rng.js"></script> <script language="javascript" type="text/javascript" src="./js/rsa.js"></script> <script language="javascript" type="text/javascript" src="./js/base64.js"></script> <script language="javascript"> //publc key and public length 16 binary data var public_key="00b0c2732193eebde5b2e278736a22977a5ee1bb99bea18c0681ad97484b4c7f681e963348eb80667b954534293b0a6cbe2f9651fc98c9ee833f343e719c97c670ead8bec704282f94d9873e083cfd41554f356f00aea38d2b07551733541b64790c2c8f400486fd662a3e95fd5edd2acf4d59ca97fad65cc59b8d10cbc5430c53"; var public_length="10001"; function do_encrypt() { var before = new date(); var rsa = new rsakey(); rsa.setpublic(public_key, public_length); var res = rsa.encrypt(document.rsatest.plaintext.value); var after = new date(); if(res) { document.rsatest.ciphertext.value =res; document.rsatest.cipherb64.value = hex2b64(res); document.rsatest.status.value = "time: " + (after - before) + "ms"; } } //--> </script> <form name="rsatest" action="rsa-example.php" method="post"> plaintext (string):<br> <input name="plaintext" type="text" value="test" size=40> <input type="button" value="encrypt" onclick="do_encrypt();"><p> ciphertext (hex):<br> <textarea name="ciphertext" rows=4 cols=70></textarea><p> ciphertext (base64):(not used)<br> <textarea name="cipherb64" rows=3 cols=70></textarea><p> status:<br> <input name="status" type="text" size=40><p> <input type="submit" value="go php" /> </form> </body> </html> 后端php部分: rsa库: 复制代码代码如下: <?php /* * php implementation of the rsa algorithm * (c) copyright 2004 edsko de vries, ireland * * licensed under the gnu public license (gpl) * * this implementation has been verified against [3] * (tested java/php interoperability). * * references: * [1] "applied cryptography", bruce schneier, john wiley & sons, 1996 * [2] "prime number hide-and-seek", brian raiter, muppetlabs (online) * [3] "the bouncy castle crypto package", legion of the bouncy castle, * (open source cryptography library for java, online) * [4] "pkcs #1: rsa encryption standard", rsa laboratories technical note, * version 1.5, revised november 1, 1993 */ /* * functions that are meant to be used by the user of this php module. * * notes: * - $key and $modulus should be numbers in (decimal) string format * - $message is expected to be binary data * - $keylength should be a multiple of 8, and should be in bits * - for rsa_encrypt/rsa_sign, the length of $message should not exceed * ($keylength / 8) - 11 (as mandated by [4]). * - rsa_encrypt and rsa_sign will automatically add padding to the message. * for rsa_encrypt, this padding will consist of random values; for rsa_sign, * padding will consist of the appropriate number of 0xff values (see [4]) * - rsa_decrypt and rsa_verify will automatically remove message padding. * - blocks for decoding (rsa_decrypt, rsa_verify) should be exactly * ($keylength / 8) bytes long. * - rsa_encrypt and rsa_verify expect a public key; rsa_decrypt and rsa_sign * expect a private key. */ /** * 于2010-11-12 1:06分于lonely修改 */ function rsa_encrypt($message, $public_key, $modulus, $keylength) { $padded = add_pkcs1_padding($message, true, $keylength / 8); $number = binary_to_number($padded); $encrypted = pow_mod($number, $public_key, $modulus); $result = number_to_binary($encrypted, $keylength / 8); return $result; } function rsa_decrypt($message, $private_key, $modulus, $keylength) { $number = binary_to_number($message); $decrypted = pow_mod($number, $private_key, $modulus); $result = number_to_binary($decrypted, $keylength / 8); return remove_pkcs1_padding($result, $keylength / 8); } function rsa_sign($message, $private_key, $modulus, $keylength) { $padded = add_pkcs1_padding($message, false, $keylength / 8); $number = binary_to_number($padded); $signed = pow_mod($number, $private_key, $modulus); $result = number_to_binary($signed, $keylength / 8); return $result; } function rsa_verify($message, $public_key, $modulus, $keylength) { return rsa_decrypt($message, $public_key, $modulus, $keylength); } function rsa_kyp_verify($message, $public_key, $modulus, $keylength) { $number = binary_to_number($message); $decrypted = pow_mod($number, $public_key, $modulus); $result = number_to_binary($decrypted, $keylength / 8); return remove_kyp_padding($result, $keylength / 8); } /* * some constants */ define("bccomp_larger", 1); /* * the actual implementation. * requires bcmath support in php (compile with --enable-bcmath) */ //-- // calculate (p ^ q) mod r // // we need some trickery to [2]: // (a) avoid calculating (p ^ q) before (p ^ q) mod r, because for typical rsa // applications, (p ^ q) is going to be _way_ too large. // (i mean, __way__ too large - won't fit in your computer's memory.) // (b) still be reasonably efficient. // // we assume p, q and r are all positive, and that r is non-zero. // // note that the more simple algorithm of multiplying $p by itself $q times, and // applying "mod $r" at every step is also valid, but is o($q), whereas this // algorithm is o(log $q). big difference. // // as far as i can see, the algorithm i use is optimal; there is no redundancy // in the calculation of the partial results. //-- function pow_mod($p, $q, $r) { // extract powers of 2 from $q $factors = array(); $div = $q; $power_of_two = 0; while(bccomp($div, "0") == bccomp_larger) { $rem = bcmod($div, 2); $div = bcdiv($div, 2); if($rem) array_push($factors, $power_of_two); $power_of_two++; } // calculate partial results for each factor, using each partial result as a // starting point for the next. this depends of the factors of two being // generated in increasing order. $partial_results = array(); $part_res = $p; $idx = 0; foreach($factors as $factor) { while($idx < $factor) { $part_res = bcpow($part_res, "2"); $part_res = bcmod($part_res, $r); $idx++; } array_push($partial_results, $part_res); } // calculate final result $result = "1"; foreach($partial_results as $part_res) { $result = bcmul($result, $part_res); $result = bcmod($result, $r); } return $result; } //-- // function to add padding to a decrypted string // we need to know if this is a private or a public key operation [4] //-- function add_pkcs1_padding($data, $ispublickey, $blocksize) { $pad_length = $blocksize - 3 - strlen($data); if($ispublickey) { $block_type = "\x02"; $padding = ""; for($i = 0; $i < $pad_length; $i++) { $rnd = mt_rand(1, 255); $padding .= chr($rnd); } } else { $block_type = "\x01"; $padding = str_repeat("\xff", $pad_length); } return "\x00" . $block_type . $padding . "\x00" . $data; } //-- // remove padding from a decrypted string // see [4] for more details. //-- function remove_pkcs1_padding($data, $blocksize) { //以下部分于原版的rsa有所不同,修复了原版的一个bug //assert(strlen($data) == $blocksize); $data = substr($data, 1); // we cannot deal with block type 0 if($data{0} == '\0') die("block type 0 not implemented."); // then the block type must be 1 or 2 //assert(($data{0} == "\x01") || ($data{0} == "\x02")); // echo $data; // remove the padding $i=1; while (1){ $offset = strpos($data, "\0", $i); if(!$offset){ $offset=$i; break; } $i=$offset+1; } //$offset = strpos($data, "\0", 100); return substr($data, $offset); } //-- // remove "kyp" padding // (non standard) //-- function remove_kyp_padding($data, $blocksize) { assert(strlen($data) == $blocksize); $offset = strpos($data, "\0"); return substr($data, 0, $offset); } //-- // convert binary data to a decimal number //-- function binary_to_number($data) { $base = "256"; $radix = "1"; $result = "0"; for($i = strlen($data) - 1; $i >= 0; $i--) { $digit = ord($data{$i}); $part_res = bcmul($digit, $radix); $result = bcadd($result, $part_res); $radix = bcmul($radix, $base); } return $result; } //-- // convert a number back into binary form //-- function number_to_binary($number, $blocksize) { $base = "256"; $result = ""; $div = $number; while($div > 0) { $mod = bcmod($div, $base); $div = bcdiv($div, $base); $result = chr($mod) . $result; } return str_pad($result, $blocksize, "\x00", str_pad_left); } ?>
处理的php代码:
<?php //decimal data include "rsa.php"; $modulus='124124790696783899579957666732205416556275207289308772677367395397704314099727565633927507139389670490184904760526156031441045563225987129220634807383637837918320623518532877734472159024203477820731033762885040862183213160281165618500092483026873487507336293388981515466164416989192069833140532570993394388051.0000000000'; $private='59940207454900542501281722336097731406274284149290386158861762508911700758780200454438527029729836453810395133453343700246367853044479311924174899432036400630350527132581124575735909908195078492323048176864577497230467497768502277772070557874686662727818507841304646138785432507752788647631021854537869399041.0000000000'; $public="65537"; $keylength="1024"; //php encrypt create //$encrypted = rsa_encrypt("vzxcvz bdxf", $public, $modulus, $keylength); //$str= bin2hex($encrypted);//bin data to hex data $str=$_post['ciphertext']; //echo $str."<br>"; $encrypted=convert($str); //hex data to bin data $decrypted = rsa_decrypt($encrypted, $private, $modulus, $keylength); echo $decrypted."<br>"; /** * 16 to 2 * @param unknown_type $hexstring * @return string|unknown */ function convert($hexstring) { $hexlenght = strlen($hexstring); // only hex numbers is allowed if ($hexlenght % 2 != 0 || preg_match("/[^\da-fa-f]/",$hexstring)) return false; unset($binstring); for ($x = 1; $x <= $hexlenght/2; $x++) { $binstring .= chr(hexdec(substr($hexstring,2 * $x - 2,2))); } return $binstring; } ?>
生成prm文件及生产需要的密钥及公钥的php文件:
<?php //create pem file //run openssl genrsa -out key.pem 1024 //this file is generated variables needed for the operation list($keylength, $modulus, $public, $private,$modulus_js,$private_js) = read_ssl_key("key.pem"); echo "keylength:(php and js)(private length)<br>"; echo $keylength; echo "<br>"; echo "modulus:(php)(10)(pubic key)<br>"; echo $modulus; echo "<br>"; echo "modulus:(js)(16)(pubic key)<br>"; echo $modulus_js; echo "<br>"; echo "public:(php)(10)(public exponent)<br>"; echo $public; echo "<br>"; echo "public:(js)(16)(public exponent)<br>"; echo "10001"; echo "<br>"; echo "private:(php)(10)(private key)<br>"; echo $private; echo "<br>"; echo "private:(js)(16)(private key)<br>"; echo $private_js; //function function read_ssl_key($filename) { exec("openssl rsa -in $filename -text -noout", $raw); // read the key length $keylength = (int) expect($raw[0], "private-key: ("); // read the modulus expect($raw[1], "modulus:"); for($i = 2; $raw[$i][0] == ' '; $i++) $modulusraw .= trim($raw[$i]); // read the public exponent $public = (int) expect($raw[$i], "publicexponent: "); // read the private exponent expect($raw[$i + 1], "privateexponent:"); for($i += 2; $raw[$i][0] == ' '; $i++) $privateraw .= trim($raw[$i]); // just to make sure expect($raw[$i], "prime1:"); // conversion to decimal format for bcmath $modulus = bc_hexdec($modulusraw); $private = bc_hexdec($privateraw); return array($keylength, $modulus['php'], $public, $private['php'],$modulus['js'], $private['js']); } /* * convert a hexadecimal number of the form "xx:yy:zz:..." to decimal * uses bcmath, but the standard normal hexdec function for the components */ function bc_hexdec($hex) { $coefficients = explode(":", $hex); $result_js= implode("",$coefficients); $i = 0; $result = 0; foreach(array_reverse($coefficients) as $coefficient) { $mult = bcpow(256, $i++); $result = bcadd($result, bcmul(hexdec($coefficient), $mult)); } return array('php'=>$result,'js'=>$result_js); } /* * if the string has the given prefix, return the remainder. * if not, die with an error */ function expect($str, $prefix) { if(substr($str, 0, strlen($prefix)) == $prefix) return substr($str, strlen($prefix)); else die("error: expected $prefix"); }
整套加密及解密的方法都在上面了,本人的测试环境为php5.3+win7
更多php+js+rsa数据加密传输实现代码。
其它类似信息

推荐信息