@signumjs/crypto
Version:
Cryptographic functions for building Signum Network apps.
49 lines • 1.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.WebCryptoAdapter = void 0;
const base_1 = require("../base");
const js_sha256_1 = require("js-sha256");
class WebCryptoAdapter {
crypto;
constructor() {
if (typeof window !== 'undefined') {
this.crypto = window.crypto;
}
else {
throw new Error('WebCryptoAdapter: Looks like you are not in a web environment...');
}
}
getRandomValues(array) {
return this.crypto.getRandomValues(array);
}
async getKey(rawkey) {
return this.crypto.subtle.importKey('raw', rawkey, 'AES-CBC', true, ['encrypt', 'decrypt']);
}
async decryptAes256Cbc(ciphertext, key) {
const cryptoKey = await this.getKey(key);
const iv = ciphertext.slice(0, base_1.CryptoParams.IvLength);
const decryptedBuffer = await this.crypto.subtle.decrypt({
name: 'AES-CBC',
iv
}, cryptoKey, ciphertext.slice(base_1.CryptoParams.IvLength));
return new Uint8Array(decryptedBuffer);
}
async encryptAes256Cbc(plaintext, key) {
const cryptoKey = await this.getKey(key);
const iv = this.getRandomValues(new Uint8Array(base_1.CryptoParams.IvLength));
const ciphertextBuffer = await this.crypto.subtle.encrypt({
name: 'AES-CBC',
iv
}, cryptoKey, plaintext);
const ciphertext = new Uint8Array(ciphertextBuffer);
const ivAndCiphertext = new Uint8Array(iv.length + ciphertext.length);
ivAndCiphertext.set(iv);
ivAndCiphertext.set(ciphertext, iv.length);
return ivAndCiphertext;
}
sha256(data) {
return Uint8Array.from(js_sha256_1.sha256.digest(data));
}
}
exports.WebCryptoAdapter = WebCryptoAdapter;
//# sourceMappingURL=webCryptoAdapter.js.map