js登录密码加密处理,加入公钥
时间: 2023-08-12 18:43:16 浏览: 70
在前端中,我们可以使用 JavaScript 的 crypto.subtle API 和 RSA 加密算法来对密码进行加密处理,并加入公钥。具体步骤如下:
1. 生成 RSA 密钥对,包括公钥和私钥。
```
const keyPair = await window.crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: "SHA-256"
},
true,
["encrypt", "decrypt"]
);
```
2. 将密码字符串转换为 Uint8Array 对象。
```
const password = "myPassword";
const passwordBuffer = new TextEncoder().encode(password);
const passwordArray = new Uint8Array(passwordBuffer);
```
3. 使用公钥对密码进行加密处理。这里我们使用 RSA-OAEP 算法进行加密。
```
const encryptedArray = await window.crypto.subtle.encrypt(
{
name: "RSA-OAEP"
},
keyPair.publicKey,
passwordArray
);
```
4. 将加密后的密码转换为 Base64 字符串。
```
const encryptedBuffer = new Uint8Array(encryptedArray);
const encryptedBase64 = btoa(String.fromCharCode.apply(null, encryptedBuffer));
console.log(encryptedBase64);
```
最后得到的 encryptedBase64 即为加密后的密码,并已经加入了公钥。注意,私钥应该保存在后端,不能暴露给前端。前端只需要使用公钥进行加密处理即可。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)