@@ -13,6 +13,18 @@ import * as errors from '../exceptions.ts'
1313import type { AES256CBCConfig , CypherText , EncryptionDriverContract } from '../types/main.ts'
1414import { base64UrlDecode , base64UrlEncode } from '../base64.ts'
1515
16+ export interface AES256CBCDriverConfig {
17+ id : string
18+ keys : string [ ]
19+ }
20+
21+ export function aes256cbc ( config : AES256CBCDriverConfig ) {
22+ return {
23+ driver : ( key : string ) => new AES256CBC ( { id : config . id , key } ) ,
24+ keys : config . keys ,
25+ }
26+ }
27+
1628export class AES256CBC extends BaseDriver implements EncryptionDriverContract {
1729 #config: AES256CBCConfig
1830
@@ -46,7 +58,7 @@ export class AES256CBC extends BaseDriver implements EncryptionDriverContract {
4658 */
4759 const iv = randomBytes ( 16 )
4860
49- const { encryptionKey, authenticationKey } = this . #deriveKey( this . getFirstKey ( ) . key , iv )
61+ const { encryptionKey, authenticationKey } = this . #deriveKey( this . cryptoKey , iv )
5062
5163 /**
5264 * Creating chiper
@@ -121,30 +133,28 @@ export class AES256CBC extends BaseDriver implements EncryptionDriverContract {
121133 * Make sure the hash is correct, it means the first 2 parts of the
122134 * string are not tampered.
123135 */
124- for ( const { key } of this . cryptoKeys ) {
125- const { encryptionKey, authenticationKey } = this . #deriveKey( key , iv )
126-
127- const isValidHmac = new Hmac ( authenticationKey ) . compare (
128- `${ cipherEncoded } ${ this . separator } ${ ivEncoded } ` ,
129- macEncoded
130- )
131-
132- if ( ! isValidHmac ) {
133- continue
134- }
135-
136- /**
137- * The Decipher can raise exceptions with malformed input, so we wrap it
138- * to avoid leaking sensitive information
139- */
140- try {
141- const decipher = createDecipheriv ( 'aes-256-cbc' , encryptionKey , iv )
142- const plainTextBuffer = Buffer . concat ( [ decipher . update ( cipherText ) , decipher . final ( ) ] )
143- return new MessageBuilder ( ) . verify ( plainTextBuffer , purpose )
144- } catch { }
136+ const { encryptionKey, authenticationKey } = this . #deriveKey( this . cryptoKey , iv )
137+
138+ const isValidHmac = new Hmac ( authenticationKey ) . compare (
139+ `${ cipherEncoded } ${ this . separator } ${ ivEncoded } ` ,
140+ macEncoded
141+ )
142+
143+ if ( ! isValidHmac ) {
144+ return null
145145 }
146146
147- return null
147+ /**
148+ * The Decipher can raise exceptions with malformed input, so we wrap it
149+ * to avoid leaking sensitive information
150+ */
151+ try {
152+ const decipher = createDecipheriv ( 'aes-256-cbc' , encryptionKey , iv )
153+ const plainTextBuffer = Buffer . concat ( [ decipher . update ( cipherText ) , decipher . final ( ) ] )
154+ return new MessageBuilder ( ) . verify ( plainTextBuffer , purpose )
155+ } catch {
156+ return null
157+ }
148158 }
149159
150160 #deriveKey( masterKey : Buffer , iv : Buffer ) {
0 commit comments