0

I have code to encrypt and decrypt the files in C#. Now I need to move the encryption task to front end an I need to write javascript code to encrypt the .xlsx files. Below is the C# code for encrypt and decrypt:

    private void EncryptFile(string inputFile, string outputFile)
    {

        try
        {
            string password = @"myKey123"; // Your Key Here
            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            string cryptFile = outputFile;
            FileStream fsCrypt = new FileStream(cryptFile, FileMode.Create);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateEncryptor(key, key),
                CryptoStreamMode.Write);

            FileStream fsIn = new FileStream(inputFile, FileMode.Open);

            int data;
            while ((data = fsIn.ReadByte()) != -1)
                cs.WriteByte((byte)data);


            fsIn.Close();
            cs.Close();
            fsCrypt.Close();
        }
        catch(Exception ex)
        {
           // MessageBox.Show("Encryption failed!", "Error");
        }
    }

    private void DecryptFile(string inputFile, string outputFile)
    {

        {
            string password = @"myKey123"; // Your Key Here

            UnicodeEncoding UE = new UnicodeEncoding();
            byte[] key = UE.GetBytes(password);

            FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);

            RijndaelManaged RMCrypto = new RijndaelManaged();

            CryptoStream cs = new CryptoStream(fsCrypt,
                RMCrypto.CreateDecryptor(key, key),
                CryptoStreamMode.Read);

            FileStream fsOut = new FileStream(outputFile, FileMode.Create);

            int data;
            while ((data = cs.ReadByte()) != -1)
                fsOut.WriteByte((byte)data);

            fsOut.Close();
            cs.Close();
            fsCrypt.Close();

        }
    }

I tried to create a encryption in javascript as below:

    var reader = new FileReader();
    reader.onload = function (e) {

        var encrypted = CryptoJS.AES.encrypt(e.target.result, 'myKey123');

        var data = new FormData();


        var encryptedFile = new File([encrypted], file.name, { type: "text/plain", lastModified: new Date() });

        data.append('file', encryptedFile);

        $.ajax({
            url: 'http://localhost:57691/api/WithKey/UploadFile',
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            type: 'POST',
            success: function (data) {
                debugger;
            }
        });
    };

    reader.readAsDataURL(file);

I also tried converting key to utf16 as below:

    function wordsToBytes (words) {
        for (var bytes = [], b = 0; b < words.length * 32; b += 8)
            bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF);
        return bytes;
    }
  var temp = CryptoJS.enc.Utf16.parse('myKey123');
  var key = wordsToBytes(temp.words);

But no luck. Can you please someone help me where I am doing wrong. What is the right way to encrypt the file in javascript as same in C#?

2
  • Why do you want to do this instead of using HTTPS? Your C# code leaks, you don't dispose all the things you need to dispose. Commented Oct 17, 2016 at 13:00
  • I wonder why you've created a new account to ask a similar question like this one. Anyway, why do you need to port this C# code? It's terrible. Why don't you simply use RNCryptor which has implementations in several languages? Commented Oct 17, 2016 at 18:47

1 Answer 1

1

This is the JavaScript code that would produce the same ciphertext as the C# code. The problem that remains is that you need to transmit this somehow.

var keyWords = CryptoJS.enc.Utf16LE.parse("myKey123");
var encryptedWords = CryptoJS.AES.encrypt("some string", keyWords, { iv: keyWords }).ciphertext;
console.log("Hex: " + encryptedWords.toString());
console.log("Base64: " + encryptedWords.toString(CryptoJS.enc.Base64));
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/rollups/aes.js"></script>
<script src="https://cdn.rawgit.com/CryptoStore/crypto-js/3.1.2/build/components/enc-utf16-min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.