blog's People
blog's Issues
前端采用RSA加密方法与后台传输数据
最近在做系统的登录功能,由于是前后端分离的项目,所以需要将用户名、密码这些信息放在请求参数中传给后台,那自然就要对密码进行加密再传输,而项目中就是用到RSA算法来进行加密解密。
RSA简单介绍
RSA算法是一种不对称加密算法,就是说加密和解密是采用不同的方法,RSA算法会生成公钥和私钥,数据接收方将公钥告诉我们,我们通过公钥对需要传输的内容进行加密处理后发给对方,对方拿到我们加密过的内容后再用私钥去解密。因为向外暴露的只有公钥,而用来解密的私钥只有数据接收方知道,这样就大大增加了安全性。RSA算法的具体解释
实战
在了解了原理后,就要在项目中去实际应用了,之后我在Github上找到了这个库,阅读过它的文档后,也大致知道了使用方法。
首先,我们从后台拿到了加密需要用的公钥,也就是RSA算法中的n(modulus)和e(exponent),然后按照文档编写以下代码
let key = new NodeRSA()
key.setOptions({
encryptionScheme: 'pkcs1' // 设置默认加密方法
})
key.importKey({
// 由于我们只是做加密,不需要解密,所以这里只需要传n和e两个参数就可以了
n: new Buffer(modulus, 'base64'), // 后台的数据格式是base64
e: new Buffer(exponent, 'base64')
})
let enPassword = key.encrypt(password, 'base64') // enPassword就是最后得到加密过的密码了
踩坑
一开始调试的时候,发现后台并不能解密我们加密过的密码,后来发现我们后台的JAVA同事使用的工具类用的解密方法是'pkcs1'
,而node-rsa这个库默认的加密方法是'pkcs1_oaep'
,两边的方法不一致导致了这个问题,所以就有上述设置默认加密方法的代码。
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.