一、加密字符串很短時
比如我們僅僅對用戶名或密碼進行加密,使用步驟
1、下載
首先用npm命令下載jsencrypt:
npm install jsencrypt –-save
2、在vue文件中引入jsencrypt
import { JSEncrypt } from 'jsencrypt'
3、對密碼進行加密
handleLogin() { ... const loginData = { username: this.loginForm.username, password: this.encryptedData(this.loginForm.password), type: this.loginForm.type } this.$store.dispatch('Login', loginData).then((res) => { if (res.success) { // this.$message.success('登陸成功') this.$router.push({ path: this.redirect || '/' }); this.errorCount =0; } else { this.$message.error(res.msg); this.errorCount+=1; console.log(this.errorCount); } }).catch((error) => { console.log(error) }).finally(() => { this.loading = false }) } else { return false } }) },
encryptedData方法:
// 加密 encryptedData(data) { // 私鑰 和后端溝通寫死了 var publicKey = '很長的一串字符' // 新建JSEncrypt對象 const encryptor = new JSEncrypt() // 設置公鑰 encryptor.setPublicKey(publicKey) // 加密數據 return encryptor.encrypt(data) }
安裝jsencrypt報錯:
D:\project\prism\SD_CCB\pts_view_product>npm install jsencrypt --save > node-sass@6.0.1 install D:\project\prism\SD_CCB\pts_view_product\node_modules\node-sass > node scripts/install.js Downloading binary from https://github.com/sass/node-sass/releases/download/v6.0.1/win32-x64-72_binding.node Cannot download "https://github.com/sass/node-sass/releases/download/v6.0.1/win32-x64-72_binding.node": connect ETIMEDOUT 185.199.110.133:443 Timed out whilst downloading the prebuilt binary Hint: If github.com is not accessible in your location try setting a proxy via HTTP_PROXY, e.g. export HTTP_PROXY=http://example.com:1234 or configure npm proxy via npm config set proxy http://example.com:8080 > core-js@2.6.12 postinstall D:\project\prism\SD_CCB\pts_view_product\node_modules\babel-runtime\node_modules\core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js on Open Collective or Patreon: > https://opencollective.com/core-js > https://www.patreon.com/zloirock Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > core-js@3.18.1 postinstall D:\project\prism\SD_CCB\pts_view_product\node_modules\core-js > node -e "try{require('./postinstall')}catch(e){}" Thank you for using core-js ( https://github.com/zloirock/core-js ) for polyfilling JavaScript standard library! The project needs your help! Please consider supporting of core-js: > https://opencollective.com/core-js > https://patreon.com/zloirock > https://paypal.me/zloirock > bitcoin: bc1qlea7544qtsmj2rayg0lthvza9fau63ux0fstcz Also, the author of core-js ( https://github.com/zloirock ) is looking for a good job -) > ejs@2.7.4 postinstall D:\project\prism\SD_CCB\pts_view_product\node_modules\ejs > node ./postinstall.js Thank you for installing EJS: built with the Jake JavaScript build tool (https://jakejs.com/) > node-sass@6.0.1 postinstall D:\project\prism\SD_CCB\pts_view_product\node_modules\node-sass > node scripts/build.js Building: C:\Program Files\nodejs\node.exe D:\project\prism\SD_CCB\pts_view_product\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= gyp info it worked if it ends with ok gyp verb cli [ gyp verb cli 'C:\\Program Files\\nodejs\\node.exe', gyp verb cli 'D:\\project\\prism\\SD_CCB\\pts_view_product\\node_modules\\node-gyp\\bin\\node-gyp.js', gyp verb cli 'rebuild', gyp verb cli '--verbose', gyp verb cli '--libsass_ext=', gyp verb cli '--libsass_cflags=', gyp verb cli '--libsass_ldflags=', gyp verb cli '--libsass_library=' gyp verb cli ] gyp info using node-gyp@7.1.2 gyp info using node@12.13.1 | win32 | x64 gyp verb command rebuild [] gyp verb command clean [] gyp verb clean removing "build" directory gyp verb command configure [] gyp verb find Python Python is not set from command line or npm configuration gyp verb find Python Python is not set from environment variable PYTHON gyp verb find Python checking if "python3" can be used gyp verb find Python - executing "python3" to get executable path gyp verb find Python - "python3" is not in PATH or produced an error gyp verb find Python checking if "python" can be used gyp verb find Python - executing "python" to get executable path gyp verb find Python - "python" is not in PATH or produced an error gyp verb find Python checking if "python2" can be used gyp verb find Python - executing "python2" to get executable path gyp verb find Python - "python2" is not in PATH or produced an error gyp verb find Python checking if Python is C:\Python37\python.exe gyp verb find Python - executing "C:\Python37\python.exe" to get version gyp verb find Python - "C:\Python37\python.exe" could not be run gyp verb find Python checking if Python is C:\Python27\python.exe gyp verb find Python - executing "C:\Python27\python.exe" to get version gyp verb find Python - "C:\Python27\python.exe" could not be run gyp verb find Python checking if the py launcher can be used to find Python gyp verb find Python - executing "py.exe" to get Python executable path gyp verb find Python - "py.exe" is not in PATH or produced an error gyp ERR! find Python gyp ERR! find Python Python is not set from command line or npm configuration gyp ERR! find Python Python is not set from environment variable PYTHON gyp ERR! find Python checking if "python3" can be used gyp ERR! find Python - "python3" is not in PATH or produced an error gyp ERR! find Python checking if "python" can be used gyp ERR! find Python - "python" is not in PATH or produced an error gyp ERR! find Python checking if "python2" can be used gyp ERR! find Python - "python2" is not in PATH or produced an error gyp ERR! find Python checking if Python is C:\Python37\python.exe gyp ERR! find Python - "C:\Python37\python.exe" could not be run gyp ERR! find Python checking if Python is C:\Python27\python.exe gyp ERR! find Python - "C:\Python27\python.exe" could not be run gyp ERR! find Python checking if the py launcher can be used to find Python gyp ERR! find Python - "py.exe" is not in PATH or produced an error gyp ERR! find Python gyp ERR! find Python ********************************************************** gyp ERR! find Python You need to install the latest version of Python. gyp ERR! find Python Node-gyp should be able to find and use Python. If not, gyp ERR! find Python you can try one of the following options: gyp ERR! find Python - Use the switch --python="C:\Path\To\python.exe" gyp ERR! find Python (accepted by both node-gyp and npm) gyp ERR! find Python - Set the environment variable PYTHON gyp ERR! find Python - Set the npm configuration variable python: gyp ERR! find Python npm config set python "C:\Path\To\python.exe" gyp ERR! find Python For more information consult the documentation at: gyp ERR! find Python https://github.com/nodejs/node-gyp#installation gyp ERR! find Python ********************************************************** gyp ERR! find Python gyp ERR! configure error gyp ERR! stack Error: Could not find any Python installation to use gyp ERR! stack at PythonFinder.fail (D:\project\prism\SD_CCB\pts_view_product\node_modules\node-gyp\lib\find-python.js:302:47) gyp ERR! stack at PythonFinder.runChecks (D:\project\prism\SD_CCB\pts_view_product\node_modules\node-gyp\lib\find-python.js:136:21) gyp ERR! stack at PythonFinder.<anonymous> (D:\project\prism\SD_CCB\pts_view_product\node_modules\node-gyp\lib\find-python.js:200:18) gyp ERR! stack at PythonFinder.execFileCallback (D:\project\prism\SD_CCB\pts_view_product\node_modules\node-gyp\lib\find-python.js:266:16) gyp ERR! stack at exithandler (child_process.js:302:5) gyp ERR! stack at ChildProcess.errorhandler (child_process.js:314:5) gyp ERR! stack at ChildProcess.emit (events.js:210:5) gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:270:12) gyp ERR! stack at onErrorNT (internal/child_process.js:456:16) gyp ERR! stack at processTicksAndRejections (internal/process/task_queues.js:80:21) gyp ERR! System Windows_NT 10.0.19043 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\project\\prism\\SD_CCB\\pts_view_product\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library=" gyp ERR! cwd D:\project\prism\SD_CCB\pts_view_product\node_modules\node-sass gyp ERR! node -v v12.13.1 gyp ERR! node-gyp -v v7.1.2 gyp ERR! not ok Build failed with error code: 1 npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! node-sass@6.0.1 postinstall: `node scripts/build.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the node-sass@6.0.1 postinstall script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Program Files\nodejs\npm_cache\_logs\2022-02-11T04_09_14_259Z-debug.log D:\project\prism\SD_CCB\pts_view_product>
這是由於缺少python依賴導致的,在python官網下載並安裝后,刪除依賴重新執行npm install即可
官網:https://www.python.org/downloads/


下載后的文件如下:

雙擊安裝

再重新執行npm install jsencrypt --save命令,
D:\project\prism\SD_CCB\pts_view_product>npm install jsencrypt --save > node-sass@6.0.1 install D:\project\prism\SD_CCB\pts_view_product\node_modules\node-sass > node scripts/install.js Downloading binary from https://github.com/sass/node-sass/releases/download/v6.0.1/win32-x64-72_binding.node Cannot download "https://github.com/sass/node-sass/releases/download/v6.0.1/win32-x64-72_binding.node": connect ETIMEDOUT 185.199.109.133:443 Timed out whilst downloading the prebuilt binary Hint: If github.com is not accessible in your location try setting a proxy via HTTP_PROXY, e.g. export HTTP_PROXY=http://example.com:1234 or configure npm proxy via npm config set proxy http://example.com:8080 > node-sass@6.0.1 postinstall D:\project\prism\SD_CCB\pts_view_product\node_modules\node-sass > node scripts/build.js Building: C:\Program Files\nodejs\node.exe D:\project\prism\SD_CCB\pts_view_product\node_modules\node-gyp\bin\node-gyp.js rebuild --verbose --libsass_ext= --libsass_cflags= --libsass_ldflags= --libsass_library= gyp info it worked if it ends with ok gyp verb cli [ gyp verb cli 'C:\\Program Files\\nodejs\\node.exe', gyp verb cli 'D:\\project\\prism\\SD_CCB\\pts_view_product\\node_modules\\node-gyp\\bin\\node-gyp.js', gyp verb cli 'rebuild', gyp verb cli '--verbose', gyp verb cli '--libsass_ext=', gyp verb cli '--libsass_cflags=', gyp verb cli '--libsass_ldflags=', gyp verb cli '--libsass_library=' gyp verb cli ] gyp info using node-gyp@7.1.2 gyp info using node@12.13.1 | win32 | x64 gyp verb command rebuild [] gyp verb command clean [] gyp verb clean removing "build" directory gyp verb command configure [] gyp verb find Python Python is not set from command line or npm configuration gyp verb find Python Python is not set from environment variable PYTHON gyp verb find Python checking if "python3" can be used gyp verb find Python - executing "python3" to get executable path gyp verb find Python - "python3" is not in PATH or produced an error gyp verb find Python checking if "python" can be used gyp verb find Python - executing "python" to get executable path gyp verb find Python - "python" is not in PATH or produced an error gyp verb find Python checking if "python2" can be used gyp verb find Python - executing "python2" to get executable path gyp verb find Python - "python2" is not in PATH or produced an error gyp verb find Python checking if Python is C:\Python37\python.exe gyp verb find Python - executing "C:\Python37\python.exe" to get version gyp verb find Python - "C:\Python37\python.exe" could not be run gyp verb find Python checking if Python is C:\Python27\python.exe gyp verb find Python - executing "C:\Python27\python.exe" to get version gyp verb find Python - "C:\Python27\python.exe" could not be run gyp verb find Python checking if the py launcher can be used to find Python gyp verb find Python - executing "py.exe" to get Python executable path gyp verb find Python - executable path is "C:\Users\miracle\AppData\Local\Programs\Python\Python39\python.exe" gyp verb find Python - executing "C:\Users\miracle\AppData\Local\Programs\Python\Python39\python.exe" to get version gyp verb find Python - version is "3.9.10" gyp info find Python using Python version 3.9.10 found at "C:\Users\miracle\AppData\Local\Programs\Python\Python39\python.exe" gyp verb get node dir no --target version specified, falling back to host node version: 12.13.1 gyp verb command install [ '12.13.1' ] gyp verb install input version string "12.13.1" gyp verb install installing version: 12.13.1 gyp verb install --ensure was passed, so won't reinstall if already installed gyp verb install version not already installed, continuing with install 12.13.1 gyp verb ensuring nodedir is created C:\Users\miracle\AppData\Local\node-gyp\Cache\12.13.1 gyp http GET https://nodejs.org/download/release/v12.13.1/node-v12.13.1-headers.tar.gz gyp WARN install got an error, rolling back install gyp verb command remove [ '12.13.1' ] gyp verb remove using node-gyp dir: C:\Users\miracle\AppData\Local\node-gyp\Cache gyp verb remove removing target version: 12.13.1 gyp verb remove removing development files for version: 12.13.1 gyp ERR! configure error gyp ERR! stack Error: connect ETIMEDOUT 104.20.22.46:443 gyp ERR! stack at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1129:14) gyp ERR! System Windows_NT 10.0.19043 gyp ERR! command "C:\\Program Files\\nodejs\\node.exe" "D:\\project\\prism\\SD_CCB\\pts_view_product\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild" "--verbose" "--libsass_ext=" "--libsass_cflags=" "--libsass_ldflags=" "--libsass_library=" gyp ERR! cwd D:\project\prism\SD_CCB\pts_view_product\node_modules\node-sass gyp ERR! node -v v12.13.1 gyp ERR! node-gyp -v v7.1.2 gyp ERR! not ok Build failed with error code: 1 npm WARN sass-loader@6.0.7 requires a peer of node-sass@^4.0.0 but none is installed. You must install peer dependencies yourself. npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents): npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"}) npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! node-sass@6.0.1 postinstall: `node scripts/build.js` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the node-sass@6.0.1 postinstall script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! C:\Program Files\nodejs\npm_cache\_logs\2022-02-11T04_55_46_763Z-debug.log D:\project\prism\SD_CCB\pts_view_product>node -v
報錯超時,應該是網絡不好,重新執行一次即可。
二、加密字符串很長時
如果我們對要加密的請求體進行加密,而請求體很長時,則需要進行分段加密
前端分段加密的js方法:
import JSEncrypt from 'jsencrypt' // 分段加密,支持中文 JSEncrypt.prototype.encryptLong = function(string) { var k = this.getKey(); try { var lt = ""; var ct = ""; //RSA每次加密117bytes,需要輔助方法判斷字符串截取位置 //1.獲取字符串截取點 var bytes = new Array(); bytes.push(0); var byteNo = 0; var len, c; len = string.length; var temp = 0; for (var i = 0; i < len; i++) { c = string.charCodeAt(i); if (c >= 0x010000 && c <= 0x10FFFF) { byteNo += 4; } else if (c >= 0x000800 && c <= 0x00FFFF) { byteNo += 3; } else if (c >= 0x000080 && c <= 0x0007FF) { byteNo += 2; } else { byteNo += 1; } if ((byteNo % 117) >= 114 || (byteNo % 117) == 0) { if (byteNo - temp >= 114) { bytes.push(i); temp = byteNo; } } } //2.截取字符串並分段加密 if (bytes.length > 1) { for (var i = 0; i < bytes.length - 1; i++) { var str; if (i == 0) { str = string.substring(0, bytes[i + 1] + 1); } else { str = string.substring(bytes[i] + 1, bytes[i + 1] + 1); } var t1 = k.encrypt(str); ct += addPreZero(t1, 256); }; if (bytes[bytes.length - 1] != string.length - 1) { var lastStr = string.substring(bytes[bytes.length - 1] + 1); let rsaStr = k.encrypt(lastStr) ct += addPreZero(rsaStr, 256); } return hex2b64(ct); } var t = k.encrypt(string); var y = hex2b64(t); return y; } catch (ex) { return false; } }; function hex2b64(hex) { const hexString = hex.toString(); let b64 = ''; for (let i = 0; i < hexString.length; i += 2) { const byte1 = parseInt(hexString.charAt(i), 16); const byte2 = parseInt(hexString.charAt(i + 1), 16); const byte = (byte1 << 4) | byte2; b64 += String.fromCharCode(byte); } return btoa(b64); } function addPreZero(num, length) { var t = (num + '').length, s = ''; for (var i = 0; i < length - t; i++) { s += '0'; } return s + num; } export {JSEncrypt}
長文本和短文本都可以使用該方法。
使用:
var userData = {username:this.user.username,password:this.user.password,sourceType:2,equipmentCode:"1232132132136"}; let jsEncrypt = new JSEncrypt(); const pubKey = "xxx"; jsEncrypt.setPublicKey(pubKey); let test = jsEncrypt.encryptLong(JSON.stringify(userData));
官網:https://www.npmjs.com/package/encryptlong
(1)、npm 安裝:
npm i encryptlong -S
瀏覽器使用:
<script src="./bin/jsencrypt.js"></script>
(2)、基本使用:
注意:使用長文本加密時最好公私鑰都要設置,避免有概率加密失敗
這里只擴展了長文本的分段加解密,其它 api 請查看官網 http://travistidwell.com/jsencrypt
encryptLong() 長文本加密
decryptLong() 長文本解密
示例:
let startTime = new Date(); //公鑰 const PUBLIC_KEY = ` -----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKX1Fs2JUD25zrAEwPnjnZC0az rl1XjGzGrJ64eb1lr9QVVOO2zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZb UrqUziHE5YGC02wObiZEzfa6V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMz etn7mcCeLw8/vmxz3QIDAQAB -----END PUBLIC KEY-----`; //私鑰 const PRIVATE_KEY = ` -----BEGIN PUBLIC KEY----- MIICXgIBAAKBgQDKX1Fs2JUD25zrAEwPnjnZC0azrl1XjGzGrJ64eb1lr9QVVOO2 zGKZdqDLZD4Ut4Mp6GHMaqqFXKm+zN7IAXu+mqZbUrqUziHE5YGC02wObiZEzfa6 V9a8ZvqpB+Z8KO+hAkkjzjMl+E+hDORpZmez3SMzetn7mcCeLw8/vmxz3QIDAQAB AoGBAJBr6b4V6nJwXdHPyngy4PGl/HTqcK60BkTamALqzmEtU9tNU5z2yz7dy+6a wTsjo7Vao8CwNrUp5fHGXw65EEc1/3Iu2Fiix0XF7RP4NFSoxbBmzQW1nUK/5DFi 4VR1uhEmdbgLwGabsdqzeUqhRKkRGAPVCotBjaDBOu0J3Mu5AkEA+SM7Ctu7evOv ZwjWrp9a5MGxJ9yLLabbIuWL+420jr2G6ojaTZ2ROA2DWWQPx4JqWxDHttomrb38 dk2emP2WAwJBAM/yU58YRQ+dTeuTzNYC1JdWcs35n9+hoVP7y+x29CmcqDTPp3nR Bbbq88yMb2nZdlwthWi7BurNHsRJFqj0GJ8CQF5gJCuW1UxcJ2PGi1yW7R2e6fcJ qoden8B2aDKgmXdBAGyz7s5cE/jB1bH1H60aECPzFVSFCwXh5FMEUEHwPfUCQQC7 JqZ57lbhebrSRcA58GwzFFvY40wu8gIHWvwqgti2xsZgWW+qZCPXf9gSBWaUhmJP Da0fGAxesGN7VyhswNuTAkEAzCFNqL/zwHXcwh9YyHTdk/bRWIJq49jTA+vbgGv0 szKIvGRKoRbub3NEUiI80TDsCAvbJ6R80J7RjnpmShOwcA== -----END PUBLIC KEY-----`; // 使用設置公私鑰 const enc = new JSEncrypt(); enc.setPublicKey(PUBLIC_KEY); enc.setPublicKey(PRIVATE_KEY); // 一段長文本json let data = { code: 200, result: { timestamp: 1572321851823, inter1: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter2: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter3: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter4: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter5: ["123123123", "123123123", "123123123", "123123123", "123123123"], inter6: ["123123123", "123123123", "123123123", "123123123", "123123123"], stream: {}, caton: {}, card: [] } }; data = JSON.stringify(data); let encrypted = enc.encryptLong(data); let endTime = new Date(); console.log("加密后數據:%o", encrypted); console.log("加密時間" + (endTime - startTime) + "ms"); //使用私鑰解密 let uncrypted = enc.decryptLong(encrypted); console.log("解密后數據:%o", uncrypted);
