keeweb/app/scripts/util/data/signature-verifier.js

75 lines
2.7 KiB
JavaScript
Raw Normal View History

2021-05-08 11:38:23 +02:00
import * as kdbxweb from 'kdbxweb';
2019-09-15 14:16:32 +02:00
import { Logger } from 'util/logger';
2019-09-28 14:40:46 +02:00
import publicKeyData from 'public-key.pem';
import publicKeyDataNew from 'public-key-new.pem';
2017-05-13 22:36:07 +02:00
const SignatureVerifier = {
logger: new Logger('signature-verifier'),
2019-09-28 14:40:46 +02:00
publicKeys: null,
2017-05-14 17:14:21 +02:00
2017-05-14 00:24:06 +02:00
verify(data, signature, pk) {
2019-09-28 14:40:46 +02:00
if (!pk) {
const pks = this.getPublicKeys();
2020-06-01 16:53:51 +02:00
return this.verify(data, signature, pks[0]).then((isValid) => {
2019-09-28 14:40:46 +02:00
if (isValid || !pks[1]) {
return isValid;
}
return this.verify(data, signature, pks[1]);
});
}
2017-05-13 22:36:07 +02:00
return new Promise((resolve, reject) => {
2019-08-16 23:05:39 +02:00
const algo = { name: 'RSASSA-PKCS1-v1_5', hash: { name: 'SHA-256' } };
2017-05-13 22:36:07 +02:00
try {
2019-09-28 14:17:55 +02:00
if (typeof signature === 'string') {
signature = kdbxweb.ByteUtils.base64ToBytes(signature);
}
2019-04-13 11:04:31 +02:00
const subtle = window.crypto.subtle;
const keyFormat = 'spki';
pk = kdbxweb.ByteUtils.base64ToBytes(pk);
2019-08-16 23:05:39 +02:00
subtle
.importKey(keyFormat, pk, algo, false, ['verify'])
2020-06-01 16:53:51 +02:00
.then((cryptoKey) => {
2019-08-16 23:05:39 +02:00
try {
subtle
.verify(
algo,
cryptoKey,
kdbxweb.ByteUtils.arrayToBuffer(signature),
kdbxweb.ByteUtils.arrayToBuffer(data)
)
2020-06-01 16:53:51 +02:00
.then((isValid) => {
2019-08-16 23:05:39 +02:00
resolve(isValid);
})
2020-06-01 16:53:51 +02:00
.catch((e) => {
2019-08-16 23:05:39 +02:00
this.logger.error('Verify error', e);
2019-09-28 14:17:55 +02:00
reject(e);
2019-08-16 23:05:39 +02:00
});
} catch (e) {
this.logger.error('Signature verification error', e);
2019-09-28 14:17:55 +02:00
reject(e);
2019-08-16 23:05:39 +02:00
}
})
2020-06-01 16:53:51 +02:00
.catch((e) => {
2019-08-16 23:05:39 +02:00
this.logger.error('ImportKey error', e);
2019-09-28 14:17:55 +02:00
reject(e);
2019-08-16 23:05:39 +02:00
});
2017-05-13 22:36:07 +02:00
} catch (e) {
2017-05-14 17:04:14 +02:00
this.logger.error('Signature key verification error', e);
2019-09-28 14:17:55 +02:00
reject(e);
2017-05-13 22:36:07 +02:00
}
});
2017-05-14 00:24:06 +02:00
},
2019-09-28 14:40:46 +02:00
getPublicKeys() {
if (!this.publicKeys) {
2020-06-01 16:53:51 +02:00
this.publicKeys = [publicKeyData, publicKeyDataNew].map((pk) =>
2019-09-28 14:40:46 +02:00
pk.match(/-+BEGIN PUBLIC KEY-+([\s\S]+?)-+END PUBLIC KEY-+/)[1].replace(/\s+/g, '')
);
2017-05-14 17:14:21 +02:00
}
2019-09-28 14:40:46 +02:00
return this.publicKeys;
2017-05-13 22:36:07 +02:00
}
};
2019-09-15 14:16:32 +02:00
export { SignatureVerifier };