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#?