jwk key support for aesjs

This commit is contained in:
Bruno Windels 2020-10-27 13:21:12 +01:00
parent a3aa25449b
commit a61d7fc68a

View file

@ -158,8 +158,8 @@ class AESCrypto {
} }
/** /**
* [decrypt description] * [decrypt description]
* @param {string} keyFormat "raw" or "jwk" * @param {BufferSource} key [description]
* @param {BufferSource | Object} key [description] * @param {Object} jwkKey [description]
* @param {BufferSource} iv [description] * @param {BufferSource} iv [description]
* @param {BufferSource} data [description] * @param {BufferSource} data [description]
* @param {Number} counterLength the size of the counter, in bits * @param {Number} counterLength the size of the counter, in bits
@ -200,6 +200,8 @@ class AESCrypto {
} }
import base64 from "../../../../lib/base64-arraybuffer/index.js";
class AESLegacyCrypto { class AESLegacyCrypto {
constructor(aesjs) { constructor(aesjs) {
this._aesjs = aesjs; this._aesjs = aesjs;
@ -213,18 +215,25 @@ class AESLegacyCrypto {
* @return {BufferSource} [description] * @return {BufferSource} [description]
*/ */
async decryptCTR({key, jwkKey, iv, data, counterLength = 64}) { async decryptCTR({key, jwkKey, iv, data, counterLength = 64}) {
// TODO: support counterLength and jwkKey
const aesjs = this._aesjs; const aesjs = this._aesjs;
// This won't work as aesjs throws with iv.length !== 16 if (counterLength !== 64) {
// const nonceLength = 8; throw new Error(`Unsupported counter length: ${counterLength}`);
// const expectedIVLength = (counterLength / 8) + nonceLength; }
// if (iv.length < expectedIVLength) { if (jwkKey) {
// const newIV = new Uint8Array(expectedIVLength); if (jwkKey.alg !== "A256CTR") {
// for(let i = 0; i < iv.length; ++i) { throw new Error(`Unknown algorithm: ${jwkKey.alg}`);
// newIV[i] = iv[i]; }
// } if (!jwkKey.key_ops.includes("decrypt")) {
// iv = newIV; throw new Error(`decrypt missing from key_ops`);
// } }
if (jwkKey.kty !== "oct") {
throw new Error(`Invalid key type, "oct" expected: ${jwkKey.kty}`);
}
// need //var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
const base64Key = jwkKey.k.replace(/-/g, "+").replace(/_/g, "/");
key = base64.decode(base64Key);
}
var aesCtr = new aesjs.ModeOfOperation.ctr(new Uint8Array(key), new aesjs.Counter(new Uint8Array(iv))); var aesCtr = new aesjs.ModeOfOperation.ctr(new Uint8Array(key), new aesjs.Counter(new Uint8Array(iv)));
return aesCtr.decrypt(new Uint8Array(data)); return aesCtr.decrypt(new Uint8Array(data));
} }