曹耘豪的博客

JavaScript使用OpenSSL加密

  1. Windows安装OpenSSL
  2. 生成SSL私钥和公钥
  3. JS加密代码
  4. 参考

Windows安装OpenSSL

http://slproweb.com/products/Win32OpenSSL.html

生成SSL私钥和公钥

无密码私钥

1
openssl genrsa -out private.key 2048

生成公钥

1
openssl rsa -in private.key -pubout -out public.pem

JS加密代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i ++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}

function importRsaKey(pem) {
// fetch the part of the PEM string between header and footer
const pemHeader = "---
--BEGIN PUBLIC KEY---
--";
const pemFooter = "---
--END PUBLIC KEY---
--";
const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length);
// base64 decode the string to get the binary data
const binaryDerString = window.atob(pemContents);
// convert from a binary string to an ArrayBuffer
const binaryDer = str2ab(binaryDerString);

return window.crypto.subtle.importKey(
'spki',
binaryDer,
{
name: 'RSA-OAEP',
hash: 'SHA-256'
},
true,
['encrypt']
)
}

async function encryptMessage(value) {
let encoder = new TextEncoder();
const data = encoder.encode(value);
const key = await importRsaKey(pem_text);
return window.crypto.subtle.encrypt({
name: 'RSA-OAEP',
hash: 'SHA-256'
}, key, data)
}

参考

   /