import sjcl from "../internal/sjcl.js" ; import { base64ToBase64Url , base64ToUint8Array , concat , hexToUint8Array , uint8ArrayToArrayBuffer , uint8ArrayToBase64 , } from "@tutao/tutanota-utils" ; import type { Base64 , Base64Url } from "@tutao/tutanota-utils" ; import { CryptoError } from "./CryptoError.js" ; import { sha256Hash } from "../hashes/Sha256.js" ; import { Aes128Key , Aes256Key } from "../encryption/Aes.js" ; export type BitArray = number [ ] ; const PADDING_BLOCK_LENGTH = 16 ; export function padAes ( bytes ) { let paddingLength = PADDING_BLOCK_LENGTH - ( bytes . byteLength % PADDING_BLOCK_LENGTH ) ; let padding = new Uint8Array ( paddingLength ) ; padding . fill ( paddingLength ) ; return concat ( bytes , padding ) ; } export function unpadAes ( bytes ) { let paddingLength = bytes [ bytes . byteLength - 1 ] ; if ( paddingLength === 0 || paddingLength > bytes . byteLength || paddingLength > PADDING_BLOCK_LENGTH ) { throw new CryptoError ( "invalid padding: " + paddingLength ) ; } let length = bytes . byteLength - paddingLength ; let result = new Uint8Array ( length ) ; result . set ( bytes . subarray ( 0 , length ) ) ; return result ; } param passwordKey returns export function createAuthVerifier ( passwordKey ) { return sha256Hash ( bitArrayToUint8Array ( passwordKey ) ) ; } export function createAuthVerifierAsBase64Url ( passwordKey ) { return base64ToBase64Url ( uint8ArrayToBase64 ( createAuthVerifier ( passwordKey ) ) ) ; } param key returns throws export function checkIs128BitKey ( key ) { let bitLength = sjcl . bitArray . bitLength ( key ) ; if ( bitLength === 128 ) { return true ; } else if ( bitLength === 256 ) { return false ; } else { throw new CryptoError ( "invalid key bit length: " + bitLength ) ; } } param bits return export function bitArrayToUint8Array ( bits ) { return new Uint8Array ( sjcl . codec . arrayBuffer . fromBits ( bits , false ) ) ; } param uint8Array return export function uint8ArrayToBitArray ( uint8Array ) { return sjcl . codec . arrayBuffer . toBits ( uint8ArrayToArrayBuffer ( uint8Array ) ) ; } param key return export function keyToBase64 ( key ) { return sjcl . codec . base64 . fromBits ( key ) ; } param base64 return throws export function base64ToKey ( base64 ) { try { return sjcl . codec . base64 . toBits ( base64 ) ; } catch ( e ) { throw new CryptoError ( "hex to aes key failed" , e as Error ) ; } } export function uint8ArrayToKey ( array ) { return base64ToKey ( uint8ArrayToBase64 ( array ) ) ; } export function keyToUint8Array ( key ) { return base64ToUint8Array ( keyToBase64 ( key ) ) ; } export const fixedIv = hexToUint8Array ( "88888888888888888888888888888888" ) ;