js 如何加密

JavaScript 中加密數(shù)據(jù)有多種方法,以下是一些常見(jiàn)的加密方式: 1. 使用 `CryptoJS``CryptoJS` 是一個(gè)廣泛使用的JavaScript加密庫(kù)...
JavaScript 中加密數(shù)據(jù)有多種方法,以下是一些常見(jiàn)的加密方式:
1. 使用 `CryptoJS`
`CryptoJS` 是一個(gè)廣泛使用的JavaScript加密庫(kù),支持多種加密算法。
安裝(如果你使用npm)
```bash
npm install crypto-js
```
使用示例
```javascript
// 引入CryptoJS
var CryptoJS = require("crypto-js");
// 對(duì)數(shù)據(jù)進(jìn)行加密
var ciphertext = CryptoJS.AES.encrypt("my secret message", "secret key 123").toString();
console.log(ciphertext);
```
2. 使用 Web Crypto API
現(xiàn)代瀏覽器支持Web Crypto API,可以用于加密。
使用示例
```javascript
async function encryptData(data, key) {
const encoder = new TextEncoder();
const dataBuffer = encoder.encode(data);
const keyBuffer = await window.crypto.subtle.importKey(
"raw",
key,
{ name: "AES-CBC", length: 256
本文鏈接:http:///bian/344766.html