0

I can“t make the file encryption with crypto-js work.

function encrypt(input) {
    var file = input.files[0];
    var reader = new FileReader();
    reader.onload = () => {
        var key = "1234567887654321";
        var wordArray = CryptoJS.lib.WordArray.create(reader.result);           // Convert: ArrayBuffer -> WordArray
        var encrypted = CryptoJS.AES.encrypt(wordArray, key).toString();        // Encryption: I: WordArray -> O: -> Base64 encoded string (OpenSSL-format)

        var fileEnc = new Blob([encrypted]);                                    // Create blob from string

        var a = document.createElement("a");
        var url = window.URL.createObjectURL(fileEnc);
        var filename = file.name + ".enc";
        a.href = url;
        a.download = filename;
        a.click();
        window.URL.revokeObjectURL(url);
    };
    reader.readAsArrayBuffer(file);
}

(code from https://stackoverflow.com/a/60550134/18373233)

For me the reader.resultproduces this error:

Argument of type 'string | ArrayBuffer | null' is not assignable to parameter of type 'number[] | undefined'. Type 'null' is not assignable to type 'number[] | undefined'.ts(2345)

Do you have a better and a working way to encrypt (and decrypt) files with crypto-js in the frontend? Thanks in advance!

1 Answers1

0

You simply have to use reader.readAsDataURL(file)

For the encryption:

private async encrypt(dataType: string, data: any) {
    var key = 'test';

    //Text encryption
    if (dataType == 'text') {
      var encryptedData = crypto.AES.encrypt(data, key);
      this.encryptedData = encryptedData;
    }

    //File encryption
    else if (dataType == 'file') {
      var file: File = data.files[0];
      var reader: FileReader = new FileReader();
      
      reader.readAsDataURL(file);

      reader.onloadend = () => {
        const result: string = reader.result! as string;
        var encryptedData = crypto.AES.encrypt(result, key);
        this.encryptedData = encryptedData;
      };
   };
}

For the decryption:

private decryptFile(encryptedData: string) {
  var decryptedData = crypto.AES.decrypt(encryptedData, key).toString(crypto.enc.Utf8);
  var file = decryptedData.split(',');
  var fileType = file[0];
  var fileContent = file[1];

  var a = document.createElement('a');
  a.href = `${fileType},` + fileContent;
  a.download = 'QKD_download';
  a.click();
}