Read, Decrypt, and Reconstruct Files in TypeScript Using FileReader, CryptoJS, and Blob

Modern web and mobile applications increasingly rely on secure file storage. Whether you’re protecting user documents, encrypted media, or sensitive configuration files, the ability to read, decrypt, and rebuild these files in the browser or a hybrid environment (Ionic, Capacitor, Electron, etc.) is essential.

This guide explains how to handle encrypted files using:

  • FileReader API
  • CryptoJS AES decryption
  • Base64 decoding
  • Typed Arrays (Uint8Array)
  • JavaScript Blob reconstruction

We will walk through a real-world scenario where an application loads an encrypted file from device storage, decrypts it, extracts its data, and rebuilds it into a usable binary format.


📂 1. Reading Files From Local Storage

Hybrid applications often access files via a file system API. After obtaining a FileEntry, the first step is to convert it into a browser-readable File object:

fileEntry.file(file => {
  const reader = new FileReader();
  reader.readAsText(file);
});

readAsText() loads the encrypted content as text, which is required before the decryption phase.


🔐 2. Decrypting the File Using CryptoJS AES

Once the file is read, the FileReader.onload event gives access to its content.
With AES-encrypted data, CryptoJS can be used to decrypt it:

const decrypted = CryptoJS.AES.decrypt(e.target.result, key)
  .toString(CryptoJS.enc.Latin1);

Why Latin1?
Encrypted payloads frequently contain byte sequences that do not map cleanly to UTF-8, and Latin1 is safer for raw binary-like strings.


✂️ 3. Cleaning the Decrypted Payload

Encrypted payloads sometimes include metadata or headers. In the example scenario, the first 30 characters are removed:

const cleaned = decrypted.slice(30);

After trimming the metadata, the string becomes a valid data URI, such as:

data:application/pdf;base64,JVBERi0xLjQKJcfs...

🔍 4. Detecting and Decoding Base64

Determine whether the data URI is Base64 encoded:

let byteString;

if (cleaned.split(',')[0].includes('base64')) {
  byteString = atob(cleaned.split(',')[1]); // Base64 → binary
} else {
  byteString = unescape(cleaned.split(',')[1]); // URL-encoded → binary
}

The result is a raw binary string representing the file.


🧬 5. Extracting the MIME Type

To rebuild the file correctly, the MIME type must be extracted:

const mimeString = cleaned.split(',')[0].split(':')[1].split(';')[0];

Examples:

  • application/pdf
  • image/png
  • image/jpeg
  • text/plain

🔧 6. Rebuilding Binary Data Using Uint8Array

Binary strings cannot be used directly.
They are transformed into a typed array:

const ia = new Uint8Array(byteString.length);
for (let i = 0; i < byteString.length; i++) {
  ia[i] = byteString.charCodeAt(i);
}

This typed array holds the exact byte sequence of the original file.


📦 7. Creating a Blob (Final Reconstructed File)

The typed array is wrapped into a Blob:

const blob = new Blob([ia], { type: mimeString });

A Blob is a browser-native object representing binary data—perfect for:

  • Downloading the file
  • Displaying it in <img> or <iframe>
  • Uploading it to a server
  • Saving it back to device storage

🖥️ 8. Using the Reconstructed File

In our scenario, the final Blob is passed to a display or processing function:

this.showFile(product, blob);

Every application can use this Blob differently—preview, validation, storage, or upload.


🔎 Why This Approach Works

This pipeline is robust because it:

✔️ Works on all major browsers

Chrome, Edge, Firefox, Safari

✔️ Works on hybrid environments

  • Ionic / Capacitor
  • Electron
  • React Native WebViews
  • Progressive Web Apps

✔️ Ensures full security

  • AES encryption
  • Safe local storage
  • No temporary file exposure

✔️ Handles any file type

PDF, PNG, DOCX, MP3, ZIP, etc.


🚀 Conclusion

Secure file handling is a critical capability for modern applications.
By combining FileReader, CryptoJS, typed arrays, and Blob, developers can safely:

  • Store encrypted files
  • Read and decrypt them on demand
  • Convert them into usable binary form
  • Display or upload them as needed

This method is adaptable, scalable, and suited for a wide range of cross-platform applications.

This article is inspired by real-world challenges we tackle in our projects. If you're looking for expert solutions or need a team to bring your idea to life,

Let's talk!

    Please fill your details, and we will contact you back

      Please fill your details, and we will contact you back