将c#加密机制代码转换为javascript
本文关键字:转换 javascript 代码 机制 加密 | 更新日期: 2023-09-27 18:13:31
我有代码加密和解密c#中的文件。现在我需要将加密任务移到前端,我需要编写javascript代码来加密.xlsx文件。下面是加密和解密的c#代码:
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();
}
}
我尝试在javascript中创建一个加密,如下所示:
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);
我还尝试将key转换为utf16,如下所示:
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);
但是运气不好。我哪里做错了,你能帮帮我吗?在javascript中加密文件的正确方法是什么?
这是将产生与c#代码相同的密文的JavaScript代码。剩下的问题是,你需要以某种方式传输它。
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>