CryptoJS解密C#DES加密文件失败

本文关键字:文件 失败 加密 C#DES 解密 CryptoJS | 更新日期: 2023-09-27 18:25:19

我们有一个xml文件,用于跟踪用户在独立培训应用程序中的课程进度。xml经过DES加密->转换为base64字符串->通过以下c#代码写入文件

protected static byte[] key = new byte[] { 0x8c, 0x04, 0xD1, 0x1E, 0x14, 0xE2, 0x51, 0xDD };
protected static byte[] iv  = new byte[] { 0x96, 0xCF, 0x3A, 0x0D, 0x7D, 0x80, 0xDA, 0xA8 };
protected static int DefBlockSize = 64;
public static string Encrypt(string originalString)
{
    if (String.IsNullOrEmpty(originalString))
    {
        throw new ArgumentNullException("Cannot decrypt a null input string");
    }
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    cryptoProvider.BlockSize = DefBlockSize;
    MemoryStream memoryStream = new MemoryStream();
    CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, iv), CryptoStreamMode.Write);
    StreamWriter writer = new StreamWriter(cryptoStream);
    writer.Write(originalString);
    writer.Flush();
    cryptoStream.FlushFinalBlock();
    writer.Flush();
    return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int) memoryStream.Length);
}
public static void EncryptToFile(string originalString, string filePath)    
{
    string base64String = DESEncryption.Encrypt(originalString);
    File.WriteAllBytes(filePath, Convert.FromBase64String(base64String));                                   
}

解密在独立应用程序中运行良好,代码如下:

protected override StreamReader LoadAsTextFile (string fileSystemPath)
{                   
    String base64EncryptedString = Convert.ToBase64String(File.ReadAllBytes(fileSystemPath));                               
    CryptoStream cs =  DESEncryption.DecryptToCryptoStream(base64EncryptedString);          
    StreamReader sr = new StreamReader(cs, true);
    return sr;
}
public static CryptoStream DecryptToCryptoStream(string base64EncryptedString)
{
    if (string.IsNullOrEmpty(base64EncryptedString))
    {
        throw new ArgumentNullException("Cannot decrypt a null input string");
    }
    DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
    cryptoProvider.BlockSize = DefBlockSize;
    MemoryStream memoryStream = new MemoryStream(Convert.FromBase64String(base64EncryptedString));
    CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateDecryptor(key, iv), CryptoStreamMode.Read);
    return cryptoStream;
}

作为一个更简单的测试,我以这种格式对DateTime字符串"10/2/2014 10:54:25 AM"进行了DES加密。加密后的base64字符串为P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z。如果我在js/cryptojs中手动设置这个base64字符串(见下文),我就可以成功解密js/crytojs中最初(c#)加密的日期时间。

var base64 = "P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z";
var utf8 = base64.toString(CryptoJS.enc.Utf8);  
var decrypted = CryptoJS.DES.decrypt(utf8, key, { iv: iv });                        
var decText = decrypted.toString(CryptoJS.enc.Utf8);
// decrypts correctly to 10/2/2014 10:54:25 AM

我似乎无法使用readAsArrayBuffer或readAsBinaryString从保存的文件中加载回数据。如果我在下面的js中使用readAsBinaryString,那么在读取文件->转换为base64后得到的base64字符串与保存文件之前在c#中看到的值略有不同。(javascript中的"P3Zjw6zkVDDsnUdM3FcwoVTMVhBEQdKMjrCvjM="和c#中的"P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z"pre-write to file)。

            if (window.File && window.FileReader && window.FileList && window.Blob) 
            {
                var r = new FileReader();
                var parser = new DOMParser();
                r.onload = function(e)
                {
                    var key = CryptoJS.enc.Hex.parse('8c04D11E14E251DD');
                    var iv  = CryptoJS.enc.Hex.parse('96CF3A0D7D80DAA8');       
                    var data = e.target.result;
                    var parsedWordArray = CryptoJS.enc.Utf8.parse(data);
                    var base64string = CryptoJS.enc.Base64.stringify(parsedWordArray);
                    var utf8 = base64string.toString(CryptoJS.enc.Utf8);    
                    var decrypted = CryptoJS.DES.decrypt(utf8, key, { iv: iv });                        
                    var decText = decrypted.toString(CryptoJS.enc.Utf8);
                    alert("Made it past decryption");                       
                }
                //r.readAsArrayBuffer(gXMLFile);    
                r.readAsBinaryString(gXMLFile);
            }

CryptoJS解密C#DES加密文件失败

我也有同样的问题。我的密码由Unity存储,但我必须使用JS读取它们。多亏了你的帖子,它激发了我的灵感。我终于有了一些结果。

您确定Base64之后的"10/2/2014 10:54:25 AM"将是"P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z"吗?我认为这是你的问题。

顺便说一句,我使用这个功能,它工作得很好:

CryptoJS.decodePasswardForUnity = function (encryted, key = '71617A7365646366', iv = "1234567890abcdef") {
    let C = CryptoJS;
    encrytedBase64 = C.enc.Base64.parse(encryted);
    toDecrypt = C.enc.Hex.parse(encrytedBase64.toString());
    let res = C.DES.decrypt(C.lib.CipherParams.create({ ciphertext: toDecrypt }), C.enc.Hex.parse(key), { iv: C.enc.Hex.parse(iv), mode: C.mode.CBC});
    return C.enc.Utf8.stringify(C.enc.Hex.parse(res.toString()));
};
CryptoJS.encodePasswardAsUnity = function (password, key = '71617A7365646366', iv = "1234567890abcdef") {
    let C = CryptoJS;
    toEncode = C.enc.Hex.parse(C.enc.Utf8.parse(password).toString());
    let res = C.DES.encrypt(toEncode, C.enc.Hex.parse(key), { iv: C.enc.Hex.parse(iv), mode: C.mode.CBC}).ciphertext;
    return C.enc.Base64.stringify(res);
};

希望这能帮助你