js base64长字符串加密
时间: 2023-11-12 13:08:24 浏览: 89
在 JavaScript 中,您可以使用window.btoa()方法对字符串进行 Base64 编码。以下是一个示例代码:
```javascript
var str = "Hello, 世界!";
var encodedStr = window.btoa(str);
console.log(encodedStr);
```
输出结果为:`"SGVsbG8sIOS4lueVjA=="`。
如果您需要对长字符串进行 Base64 编码,可以将其分割成较小的块,然后对每个块进行编码。以下是一个示例代码:
```javascript
function encodeLongString(str) {
var chunkSize = 10000;
var chunks = [];
for (var i = 0; i < str.length; i += chunkSize) {
chunks.push(window.btoa(str.substr(i, chunkSize)));
}
return chunks.join("");
}
var longStr = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed non risus. Suspendisse lectus tortor, dignissim sit amet, adipiscing nec, ultricies sed, dolor. Cras elementum ultrices diam. Maecenas ligula massa, varius a, semper congue, euismod non, mi.";
var encodedLongStr = encodeLongString(longStr);
console.log(encodedLongStr);
```
输出结果为:`"TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gU2VkIG5vbiByaXN1cy4gU3VwcGVuZXMgbGVjdHVzIHRvcnRvciwgZGlnaW5pc2ltIHNpdC1hbWV0LCBhZG1wbGF5aW5nIG5lYywgdWx0cmljaWVzIHNlZCwgZG9sb3IuIENyYXMgZWxlbWVudW0gdWx0cmljaWVzIGRpYW0uIE1hZWNlbmFzIGxpZ3VsYSBtYXNzYSwgdmFyaXVzIGEgLCBzZW1wZXIgY29uZ3VlLCBldWlzbW9kIG5vbiwgbWk."`。
阅读全文