This repository has been archived on 2022-08-19. You can view files and clone it, but cannot push or open issues or pull requests.
hydrogen-web/src/matrix/ssss/SecretStorage.js

71 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-09-17 15:09:40 +05:30
/*
Copyright 2020 The Matrix.org Foundation C.I.C.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
export class SecretStorage {
2021-02-11 21:59:48 +05:30
constructor({key, platform}) {
2020-09-17 15:09:40 +05:30
this._key = key;
2021-02-11 21:59:48 +05:30
this._platform = platform;
2020-09-17 15:09:40 +05:30
}
async readSecret(name, txn) {
2020-09-17 15:09:40 +05:30
const accountData = await txn.accountData.get(name);
if (!accountData) {
return;
}
const encryptedData = accountData?.content?.encrypted?.[this._key.id];
if (!encryptedData) {
throw new Error(`Secret ${accountData.type} is not encrypted for key ${this._key.id}`);
}
if (this._key.algorithm === "m.secret_storage.v1.aes-hmac-sha2") {
2020-09-17 16:03:57 +05:30
return await this._decryptAESSecret(accountData.type, encryptedData);
2020-09-17 15:09:40 +05:30
} else {
throw new Error(`Unsupported algorithm for key ${this._key.id}: ${this._key.algorithm}`);
}
}
async _decryptAESSecret(type, encryptedData) {
const {base64, utf8} = this._platform.encoding;
2020-09-17 15:09:40 +05:30
// now derive the aes and mac key from the 4s key
2021-02-11 21:59:48 +05:30
const hkdfKey = await this._platform.crypto.derive.hkdf(
2020-09-17 15:09:40 +05:30
this._key.binaryKey,
new Uint8Array(8).buffer, //zero salt
utf8.encode(type), // info
2020-09-17 15:09:40 +05:30
"SHA-256",
512 // 512 bits or 64 bytes
);
const aesKey = hkdfKey.slice(0, 32);
const hmacKey = hkdfKey.slice(32);
const ciphertextBytes = base64.decode(encryptedData.ciphertext);
2021-02-11 21:59:48 +05:30
const isVerified = await this._platform.crypto.hmac.verify(
2020-09-17 15:09:40 +05:30
hmacKey, base64.decode(encryptedData.mac),
ciphertextBytes, "SHA-256");
if (!isVerified) {
throw new Error("Bad MAC");
}
2021-02-11 21:59:48 +05:30
const plaintextBytes = await this._platform.crypto.aes.decryptCTR({
key: aesKey,
iv: base64.decode(encryptedData.iv),
data: ciphertextBytes
});
2020-09-17 15:09:40 +05:30
return utf8.decode(plaintextBytes);
2020-09-17 15:09:40 +05:30
}
}