【发布时间】:2022-01-27 03:33:07
【问题描述】:
我有用 C# 加密的文件(使用 DES、PKCS7)。我需要在 Node JS 中解码这些文件。
我在 C# 中用来解密的代码如下所示:
public string SSFile_Reader( string fileToDecrypt )
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider
{
Key = Encoding.UTF8.GetBytes( "13^07v90" ),
IV = Encoding.UTF8.GetBytes( "13^07v90" ),
Padding = PaddingMode.PKCS7
};
using( FileStream streamToDecrypt = new FileStream( fileToDecrypt, FileMode.Open, FileAccess.Read, FileShare.ReadWrite ) )
{
ICryptoTransform cryptoTransform = provider.CreateDecryptor();
string outputString = "";
using( CryptoStream stream2 = new CryptoStream( streamToDecrypt, cryptoTransform, CryptoStreamMode.Read ) )
{
try
{
using( StreamReader reader = new StreamReader( stream2 ) )
{
try
{
outputString = reader.ReadToEnd();
}
catch
{
//handle error here
}
stream2.Close();
streamToDecrypt.Close();
return outputString;
}
}
catch( Exception exception )
{
//handle error here
}
}
}
return '';
}
我确实需要将以上内容转换为 Node JS。我试过下面的 Node JS 代码,但输出只是一些随机的东西,而不是原始的加密字符串:
const { Readable } = require("stream");
const { scrypt, scryptSync, randomFill, createCipheriv, createDecipheriv } = require('crypto');
const fs = require('fs');
const [, , pathToEncryptedFile] = process.argv;
if (!pathToEncryptedFile) {
console.log('No file to decrypt')
exit()
}
const keyAndIv = '31335e3037763930'; //hex equivalence of 13^07v90
const key = Buffer.from(keyAndIv, 'hex');
const iv = Buffer.from(keyAndIv, 'hex');
const decryptedData = '';
const decipher = createDecipheriv('des', key, iv);
const readableStream = Readable.from(fs.createReadStream(pathToEncryptedFile)
.pipe(decipher));
readableStream.on("data", (chunk) => {
decryptedData += chunk.toString()
})
readableStream.on('end', function () {
console.log({decryptedData})
});
readableStream.on('error', function (err) {
console.log({err})
});
我也尝试使用crypto-js 无济于事 (https://github.com/brix/crypto-js/issues/396)。
这是我需要解密的文件之一的示例:https://files.fm/u/6pewftkk2
如果上面给出的用于解密的 C# 代码不够用,我也可以给出进行加密的 C# 代码
【问题讨论】:
-
...我尝试过下面的 Node JS 代码:... 还有...发生了什么?
-
...输出只是一些随机的东西,而不是原始的加密字符串(抱歉信息不完整。问题也更新了)
-
问题不清楚,encoding is not encryption。您是对文件进行编码还是加密?你能指定你想使用的算法吗?
-
由于您将明文存储在
outputString中,因此您实际上可以直接加载密文而无需流,例如使用readFileSync()并使用createDecipheriv()解密数据。对于从文件系统连续读取的较大密文,以及连续写入文件系统的明文,pipe()将是一个简单的解决方案。 -
@Thecave3 很抱歉这个错误(我清楚地说如何 *decrypt*... 所以编码是我的错误)。算法是带有 PKCS7 填充的 DES。 This is the gist for the code that I use for the encryption
标签: javascript node.js encryption cryptography cryptojs