你的位置:首页 > Java教程

[Java教程]JS到PHP使用RSA算法进行加密通讯


我们平时做用户登录表单提交,用户名密码都是明文直接POST到后端,这样很容易被别人从监听到。

在js上做rsa,感觉jsencrypt这个是封装的比较好的,但用起来还是遇到了些坑,所以踩进代码里填填坑~

项目在这里 https://github.com/travist/jsencrypt

关于jsencrypt和RSA我就不多介绍了,直接上代码

因为jsencrypt与最新的PHP不兼容所以折腾了好久,在js上做了些改动

可直接下载修改过的js:http://pan.baidu.com/s/1qYu0FA8

1,编辑jsencrypt.js,添加3个方法:

 1 function RSAEncryptLong(text) { 2  var length = ((this.n.bitLength()+7)>>3) - 11; 3  if (length <= 0) return false; 4  var ret = ""; 5  var i = 0; 6  while(i + length < text.length) { 7   ret += this._short_encrypt(text.substring(i,i+length)); 8   i += length; 9  }10  ret += this._short_encrypt(text.substring(i,text.length));11  return ret;12 }13 14 /**15   * base64编码16   * @param {Object} str17  */18  function base64encode(str){19   var out, i, len;20   var c1, c2, c3;21   len = str.length;22   i = 0;23   out = "";24   while (i < len) {25    c1 = str.charCodeAt(i++) & 0xff;26    if (i == len) {27     out += base64EncodeChars.charAt(c1 >> 2);28     out += base64EncodeChars.charAt((c1 & 0x3) << 4);29     out += "==";30     break;31    }32    c2 = str.charCodeAt(i++);33    if (i == len) {34     out += base64EncodeChars.charAt(c1 >> 2);35     out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));36     out += base64EncodeChars.charAt((c2 & 0xF) << 2);37     out += "=";38     break;39    }40    c3 = str.charCodeAt(i++);41    out += base64EncodeChars.charAt(c1 >> 2);42    out += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));43    out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));44    out += base64EncodeChars.charAt(c3 & 0x3F);45   }46   return out;47  }48 49  /**50   * base64解码51   * @param {Object} str52  */53  function base64decode(str){54   var c1, c2, c3, c4;55   var i, len, out;56   len = str.length;57   i = 0;58   out = "";59   while (i < len) {60    /* c1 */61    do {62     c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];63    }64    while (i < len && c1 == -1);65    if (c1 == -1)66     break;67    /* c2 */68    do {69     c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];70    }71    while (i < len && c2 == -1);72    if (c2 == -1)73     break;74    out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));75    /* c3 */76    do {77     c3 = str.charCodeAt(i++) & 0xff;78     if (c3 == 61)79      return out;80     c3 = base64DecodeChars[c3];81    }82    while (i < len && c3 == -1);83    if (c3 == -1)84     break;85    out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));86    /* c4 */87    do {88     c4 = str.charCodeAt(i++) & 0xff;89     if (c4 == 61)90      return out;91     c4 = base64DecodeChars[c4];92    }93    while (i < len && c4 == -1);94    if (c4 == -1)95     break;96    out += String.fromCharCode(((c3 & 0x03) << 6) | c4);97   }98   return out;99  }

2,找到这一行

RSAKey.prototype.encrypt = RSAEncrypt;

修改为:

RSAKey.prototype.encrypt = RSAEncryptLong;RSAKey.prototype._short_encrypt = RSAEncrypt;

3,找到这一行代码

JSEncrypt.prototype.encrypt = function (string) { // Return the encrypted string. try {  return hex2b64(this.getKey().encrypt(string)); }

修改为:

JSEncrypt.prototype.encrypt = function (string) { // Return the encrypted string. try {  return base64encode(this.getKey().encrypt(string)); }

 

4,页面js加密代码

1 <script type="text/javascript" src="jsencrypt.js"></script>2 <script>3 function encrypt(msg) {4   var rsa = new JSEncrypt();5   rsa.setPublic('
-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC6LHB0pVFfBSUkTtzQVXvX4ohF3M0jb/7JdTs3GJccf+VhYjIIdOmFFGrJFXAI459VbTuobG/yoCN5OOWs7NrCZvFQ3gS9u7RU2Mf7vK3So+hP56ijWMMzVkmBwyKF9U6NQ4Q4NhUMIpe/8HA87eps1n2emxEbxrNanvSQi3c1VwIDAQAB-----END PUBLIC KEY-----
', '10001'); 
6 return rsa.encrypt(msg);
7 }
8 </script>

 

5,PHP解密代码

 1 require_once('Crypt/RSA.php'); 2 define("KEY_PRIVATE", "
-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQC6LHB0pVFfBSUkTtzQVXvX4ohF3M0jb/7JdTs3GJccf+VhYjII
dOmFFGrJFXAI459VbTuobG/yoCN5OOWs7NrCZvFQ3gS9u7RU2Mf7vK3So+hP56ij
WMMzVkmBwyKF9U6NQ4Q4NhUMIpe/8HA87eps1n2emxEbxrNanvSQi3c1VwIDAQAB
AoGAR/EWP60Gha5qTN6Aq6zs3161hDGvv8rubRD1IfRJqISvsfMNHIF5H6jlHvE+
yuCS2KMOU6YbmGlTa+uVrT4VxjKqDhvRoym4oOXdZURlr2hHsQjB5A20Ud6mh2dA
TpbXodxBHz9xA/KJanesFUipQMftzfjezDCSOtM/DwiqZ+ECQQDltR45mSpmK9/k
Izk76iQiQe3Elxvhu/FFo/g23fMk4dG2ZObUmTnGED81VOp8TqR9/WJ0NFHywoGy
J/sdZdORAkEAz3uxMWWsG0ywSb6tRuxr1zVBRPkzH3v0tuNxFl09dKq2HS4U2uAD
nXFnyseSpWEZB9asrH1+frYIFjxFSra2ZwJAL/kWeeMCFtp85NFyZ4/rwffQ52jD
mu48YlXvRc4utHow6Q3Do4zoovPLr6CvZAysj992S1yN7Mwwd/uflzEn8QJADRtX
OjOeB6t0h3QQJibROSsYEG9dl2ORNexwPGVveGtATd+XWaxFDjEXyWuKDAByQFiD
V/Ilh4OgRydPiUS5iQJAdSjhqtN1kz5nyiP8tYbmwxhMojLl7qSNkYJEarhml6Wy
gvInF7gsoOg/MUC8Ytgv+f93gi2aHGR/rn0ODRkqqg==
-----END RSA PRIVATE KEY-----
"); 
10
11 function decrypt(msg) {
12 $rsa = new Crypt_RSA();
13 $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
14 $rsa->loadKey(KEY_PRIVATE, CRYPT_RSA_PRIVATE_FORMAT_PKCS1);
15 $s = new Math_BigInteger(base64_decode(msg), 16);
16 retrun $rsa->decrypt($s->toBytes());
17 }

 

在线生成RSA秘钥对:http://travistidwell.com/jsencrypt/demo/

 

最后 我希望这个解决方案能帮助你们中的一些人。如果我的文章有什么问题,请随时联系帮助我纠正它。

 

参考:

http://travistidwell.com/jsencrypt/

http://travistidwell.com/jsencrypt/demo/

http://bestmike007.com/2011/08/secure-data-transmission-between-pure-php-and-javascript-using-rsa/