js需要引入一个js包
<!DOCTYPE html> <html> <head> <title>测试rsa</title> <script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script> </head> <body> <script> var publickey='-----BEGIN PUBLIC KEY-----\n'+ 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCWqCWHhsk5l1sbmdfh8ja//rbQ\n'+ 'ibrrGoGQeeEOImK/FcupV0r9fO/uSb2JNxjN9JtlBSiU0Uk41G0hYZUAf7RtFnh7\n'+ '5sCWhtlTj2NS92jtOj0cmpm1UK7k7bCgfVQyVNXxFAL/rb5N958ix/Lnq3TAok/S\n'+ 'TdvrDjODnbIJtFFQcwIDAQAB\n'+ '-----END PUBLIC KEY-----'; var privkey='-----BEGIN PRIVATE KEY-----\n'+ 'MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJaoJYeGyTmXWxuZ\n'+ '1+HyNr/+ttCJuusagZB54Q4iYr8Vy6lXSv187+5JvYk3GM30m2UFKJTRSTjUbSFh\n'+ 'lQB/tG0WeHvmwJaG2VOPY1L3aO06PRyambVQruTtsKB9VDJU1fEUAv+tvk33nyLH\n'+ '8uerdMCiT9JN2+sOM4Odsgm0UVBzAgMBAAECgYBRe8RAluAC7B/0v7KJnC2MjkFm\n'+ 'bPfR7NYixCi7MlHiM/GhN3txur8yTGPc8RXTXvclHjMiukc2G36izVp/mJKGkWVj\n'+ 'Mc4XIsZuDz/TwFid+Q/B8++dMkB4GdWVHPomZ4dbSJPz/8CxjEGR/V+DdjiOsp+W\n'+ 'wlBrF+vEBrh8OTedkQJBAMgNDDwQFHCq+Zr4iHGeOFWDHX9zy8F/7OB4rNtqrfLn\n'+ 'FB8NOtJmU2YLyt5ArkpCS9b7MK8wQmtNETCRSVJFD9cCQQDAyqZuhNI38OX/HxDW\n'+ 'VOx+IRCv7f1OUMuh8QW2g+7xJu5KbwbE67jlpiJJvcYSMy+u5tfUq4hzlpVr+64Z\n'+ 'MODFAkBzCT291ClM2KSL/trHKwqN8cWmornKXXujYQFVczTv9v1VFdB7aKgQiDty\n'+ 'LpOK1DC0QOGv+/pVpY169jDJhDklAkEAv2r2IJmD18M5uTrxDr23KexOkz8q2A1k\n'+ 'gd+7GmKYZZuP0Ru3juG07V8sgCcKeJuV5oSRGzlM++cxaMu1KpHbOQJAGNZXGhbu\n'+ 'B0ZBKfsT9XJ+xGCo+je8j5Fkh7ee50bMsea9PJdqy/SLCW7gqBnK4QfpbkB2ni0d\n'+ 'r6XOPkLh5CHd9Q==\n'+ '-----END PRIVATE KEY-----\n'; console.log('B0ZBKfsT9XJ+xGCo+je8j5Fkh7ee50bMsea9PJdqy/SLCW7gqBnK4QfpbkB2ni0d'.length); console.log(publickey); var encrypt = new JSEncrypt(); encrypt.setPublicKey(publickey); //var rsamaxStr='B0ZBKfsT9XJ+xGCo+je8j5Fkh7ee50bMsea9PJdqy/SLCW7gqBnK4QfpbkB2ni0dB0ZBKfsT9XJ+xGCo+je8j5Fkh7ee50bMsea9PJdqy/SLCW7bbbccc'; var rsamaxStr='B0ZBKfsT9XJ+xGCo+je8j5Fkh7ee50bMsea9PJdqy/SLCW7gqBnK4QfpbkB2ni0dB0ZBKfsT9XJ+xGCo+je8j5Fkh7ee50bMsea9PJdqy/SLCW7bbbccc'; var text='基本结构和配置和配置基本结构和配置和配置基本结构和配置和配置基本结构和和配和配磊123'; console.log('rsamaxStr 长度是:'+rsamaxStr.length); console.log('text 长度是:'+text.length); var data = encrypt.encrypt(rsamaxStr); console.log("加密后的字符长度是"+data.length+" :\n"+data); encrypt.setPrivateKey(privkey); console.log(encrypt.decrypt(data)); //($data, '+/', '-_') var str="abc/bba+ccc+edf".replace(/\+/g,'-'); alert(str); </script> </body> </html>
在js中替换字符串是一个懒惰型的,只替换一个,后面的就不替换了。
如何解决?
alert("abc/bba+ccc+edf"); var result="abc/bba+ccc+edf".replace(/\+/g,'-').replace(/\//g,'_'); alert(result); //safe 解密 var srcStr=result.replace(/-/g,'+').replace(/_/g,'/'); alert(srcStr); //扩展自己的一个方法,进行替换吧 String.protected.rreplce=function(){ }
问题:
为什么rsa 加密长字符串后,就不能解密了呢?
RSA加密有一个长度的限制,最大加密117位
加密长字符串实现:
https://www.cnblogs.com/Lrn14616/p/10154529.html