123 lines
2.8 KiB
JavaScript
123 lines
2.8 KiB
JavaScript
async function init() {
|
|
|
|
const operations = crypto.subtle
|
|
|
|
const KEY_LEN = 256
|
|
|
|
const ENCRYPTION_ALGO = "AES-GCM"
|
|
const ENCRYPTION_USAGES = ["encrypt", "decrypt"]
|
|
const ENCRYPTION_PARAMS = { name: ENCRYPTION_ALGO, length: KEY_LEN }
|
|
|
|
const WRAPPING_ALGO = "AES-KW"
|
|
const WRAPPING_USAGES = ["wrapKey", "unwrapKey"]
|
|
|
|
const DERIVATION_ALGO = "ECDH"
|
|
|
|
const { publicKey, privateKey } = await operations.generateKey(
|
|
{
|
|
name: DERIVATION_ALGO,
|
|
namedCurve: "P-384",
|
|
},
|
|
false,
|
|
["derivekey"]
|
|
)
|
|
|
|
const encryptionKey = await operations.deriveKey(
|
|
{
|
|
name: DERIVATION_ALGO,
|
|
public: publicKey,
|
|
},
|
|
privateKey,
|
|
ENCRYPTION_PARAMS,
|
|
false,
|
|
["encrypt"]
|
|
)
|
|
|
|
const decryptionKey = await operations.deriveKey(
|
|
{ name: DERIVATION_ALGO, public: publicKey },
|
|
privateKey,
|
|
ENCRYPTION_PARAMS,
|
|
false,
|
|
['decrypt']
|
|
)
|
|
|
|
return { encryptionKey, decryptionKey }
|
|
|
|
}
|
|
|
|
|
|
function stringToArrayBuffer(str) {
|
|
var buf = new ArrayBuffer(str.length);
|
|
var bufView = new Uint8Array(buf);
|
|
for (var i = 0, strLen = str.length; i < strLen; i++) {
|
|
bufView[i] = str.charCodeAt(i);
|
|
}
|
|
return buf;
|
|
}
|
|
|
|
|
|
function arrayBufferToString(str) {
|
|
var byteArray = new Uint8Array(str);
|
|
var byteString = '';
|
|
for (var i = 0; i < byteArray.byteLength; i++) {
|
|
byteString += String.fromCodePoint(byteArray[i]);
|
|
}
|
|
return byteString;
|
|
}
|
|
|
|
|
|
async function aEncryptWithKey(key, data) {
|
|
// Encrypt data with key. Return a Promise
|
|
return new Promise((resolve) => {
|
|
window.crypto.subtle.encrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv: stringToArrayBuffer(key.uuid),
|
|
},
|
|
key.key,
|
|
stringToArrayBuffer(data)
|
|
).then(text => {
|
|
|
|
resolve(btoa(arrayBufferToString(text)));
|
|
|
|
});
|
|
});
|
|
}
|
|
|
|
function encryptWithKey(key, data) {
|
|
// Encrypt data with key. Return a Promise
|
|
return new Promise((resolve) => {
|
|
window.crypto.subtle.encrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv: stringToArrayBuffer(key.uuid),
|
|
},
|
|
key.key,
|
|
stringToArrayBuffer(data)
|
|
).then(text => {
|
|
|
|
resolve(btoa(arrayBufferToString(text)));
|
|
|
|
});
|
|
});
|
|
}
|
|
|
|
|
|
function decryptWithKey(key, data) {
|
|
// Decrypt data with key. Return a Promise
|
|
return new Promise((resolve) => {
|
|
window.crypto.subtle.decrypt(
|
|
{
|
|
name: "AES-GCM",
|
|
iv: stringToArrayBuffer(key.uuid),
|
|
},
|
|
key.key,
|
|
stringToArrayBuffer(atob(data))
|
|
).then(text => {
|
|
|
|
resolve(arrayBufferToString(text));
|
|
|
|
});
|
|
})
|
|
}
|