window.crypto.subtle仅支持https站点,和 127.0.0.1这样的可信任站点
const pemEncodedKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAxiuhgssxHclogWzB7OGy
vkIB+HGUO4hODykrz3c0/SBLJZc78mq7VaL3EnicGpoXFJkao3I+1C7MD5Jpa27b
Sc22veI0frbd/nbiSutvwAnf3rpVJEQtFTMz3v4OpSRcjOhIxKsL6iZ0JTt5++gk
sqeyrMtk5myAgho9JTnK7fPCrT7AZb/VaGc9NlWL2+9nTypLr2pew53o24nhWS5w
IgJM4X0M08YB3meXR/Q/CamgtI7+DEdubTfNwc9YCTuH6q3P7oqP/1X5Al+UHnoY
OITJJfFRBQ4zrzJU8lMQm3hy3ZSdsiP1vVqfoqQ2pu5IoL3OSgQEGVSp/OndwVz7
AQIDAQAB
-----END PUBLIC KEY-----`;
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 importPrivateKey(pem) {
const pemHeader = "-----BEGIN PRIVATE KEY-----";
const pemFooter = "-----END PRIVATE KEY-----";
const pemContents = pem.substring(pemHeader.length, pem.length - pemFooter.length);
const binaryDerString = window.atob(pemContents);
const binaryDer = str2ab(binaryDerString);
return window.crypto.subtle.importKey(
"spki",
binaryDer,
{
name: "RSA-OAEP",
hash: "SHA-1", // 需要注意散列方式要和后端解密对其,python默认是SHA-1
},
true,
["encrypt"]
);
}
function encryptMessage(publicKey) {
let enc = new TextEncoder();
const data = enc.encode('admin@123456');
return window.crypto.subtle.encrypt({
name: "RSA-OAEP",
hash: 'SHA-1'
},
publicKey,
data);
}
async function encrpt(){
const key = await importPrivateKey(pemEncodedKey);
const password = await encryptMessage(key);
const _password = window.btoa(String.fromCharCode(...new Uint8Array(password)));
console.log(_password)
}
encrpt()