@@ -70,6 +70,7 @@ function assertKey(key: Buffer): void {
7070const SEALED_PREFIX = 'enc:v1:'
7171const SEALED_IV_BYTES = 12
7272const SEALED_KEY_ID_BYTES = 4
73+ const SEALED_ENVELOPE = / ^ e n c : v 1 : [ 0 - 9 a - f ] { 8 } : [ 0 - 9 a - f ] { 24 } : (?: [ 0 - 9 a - f ] { 2 } ) * : [ 0 - 9 a - f ] { 32 } $ /
7374
7475interface SealingKeys {
7576 keyId : string
@@ -90,7 +91,7 @@ function deriveSealingKeys(key: Buffer): SealingKeys {
9091
9192/** Whether `value` is an envelope produced by {@link seal}. */
9293export function isSealed ( value : string ) : boolean {
93- return value . startsWith ( SEALED_PREFIX )
94+ return SEALED_ENVELOPE . test ( value )
9495}
9596
9697/**
@@ -112,17 +113,12 @@ export function seal(plaintext: string, key: Buffer): string {
112113}
113114
114115/**
115- * Opens an envelope produced by {@link seal}. Throws when the value is not an envelope, was sealed
116+ * Opens an envelope produced by {@link seal}. Throws when the value is not a well-formed envelope, was sealed
116117 * under a different key, or fails GCM authentication.
117118 */
118119export function unseal ( value : string , key : Buffer ) : string {
119120 if ( ! isSealed ( value ) ) throw new Error ( 'Value is not a sealed envelope' )
120- const [ keyId , ivHex , ciphertextHex , authTagHex , ...rest ] = value
121- . slice ( SEALED_PREFIX . length )
122- . split ( ':' )
123- if ( ! keyId || ! ivHex || ciphertextHex === undefined || ! authTagHex || rest . length > 0 ) {
124- throw new Error ( 'Malformed sealed envelope' )
125- }
121+ const [ keyId , ivHex , ciphertextHex , authTagHex ] = value . slice ( SEALED_PREFIX . length ) . split ( ':' )
126122 const keys = deriveSealingKeys ( key )
127123 if ( keyId !== keys . keyId ) throw new Error ( 'Sealed envelope was sealed under a different key' )
128124 const decipher = createDecipheriv ( 'aes-256-gcm' , keys . cipherKey , Buffer . from ( ivHex , 'hex' ) , {
0 commit comments