Код: Выделить всё
// Generate RSA key pair
const keyPair = await crypto.subtle.generateKey({
name: "RSA-OAEP",
modulusLength: 4096,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-512"
}, true, ["encrypt", "decrypt"]);
// Save private key
// Encrypt the private key
const textEncoder = new TextEncoder();
const salt = new Uint8Array(16);
crypto.getRandomValues(salt);
const passwordKey = await crypto.subtle.importKey("raw", textEncoder.encode(passwordInput.value), "PBKDF2", true, ["deriveKey"]);
const derivedKey = await crypto.subtle.deriveKey({
name: "PBKDF2",
hash: "SHA-512",
salt,
iterations: 210000
}, passwordKey, {
name: "AES-CBC",
length: 256
}, true, ["wrapKey", "unwrapKey"]);
const iv = new Uint8Array(16);
crypto.getRandomValues(iv);
const wrappedPrivateKey = await crypto.subtle.wrapKey("pkcs8", keyPair.privateKey, derivedKey, {
name: "AES-CBC",
iv
});
const userId = resData.id;
sessionStorage.setItem("crypto-key", bufferToBase64(privateKey));
localStorage.setItem(`crypto-key-${userId}`, bufferToBase64(wrappedPrivateKey));
localStorage.setItem(`crypto-key-${userId}-salt`, bufferToBase64(salt));
localStorage.setItem(`crypto-key-${userId}-iv`, bufferToBase64(iv));
}
< /code>
при входе в систему: < /p>
// Decrypt the private key
const userId = resData.id;
const textEncoder = new TextEncoder();
const encryptedPrivateKey = base64ToArrayBuffer(localStorage.getItem(`crypto-key-${userId}`));
const salt = base64ToArrayBuffer(localStorage.getItem(`crypto-key-${userId}-salt`));
const iv = base64ToArrayBuffer(localStorage.getItem(`crypto-key-${userId}-iv`));
const passwordKey = await crypto.subtle.importKey("raw", textEncoder.encode(passwordInput.value), "PBKDF2", true, ["deriveKey"]);
const unwrappingKey = await crypto.subtle.deriveKey({
name: "PBKDF2",
hash: "SHA-512",
salt,
iterations: 210000
}, passwordKey, {
name: "AES-CBC",
length: 256
}, true, ["unwrapKey"]);
const privateKey = await crypto.subtle.unwrapKey("pkcs8", encryptedPrivateKey, unwrappingKey, {
name: "AES-CBC",
iv
}, {
name: "RSA-OAEP",
hash: "SHA-512"
}, true, ["encrypt", "decrypt"]);
sessionStorage.setItem("crypto-key", bufferToBase64(privateKey));
location.reload();
Код: Выделить всё
const base64ToArrayBuffer = (data) => {
const binaryKey = atob(data);
const keyBytes = new Uint8Array(binaryKey.length);
for (let i = 0; i < binaryKey.length; i++) {
keyBytes[i] = binaryKey.charCodeAt(i);
}
return keyBytes.buffer;
}
const bufferToBase64 = (data) => btoa(String.fromCharCode(... new Uint8Array(data)));
Подробнее здесь: https://stackoverflow.com/questions/796 ... ping-fails