【问题标题】:CryptoJS Decrypt Of C# DES Encrypted File FailingC# DES 加密文件的 CryptoJS 解密失败
【发布时间】:2014-10-02 17:03:57
【问题描述】:

我们有一个 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/cryptojs 中最初(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 从保存的文件中加载数据。如果我将 readAsBinaryString 与下面的 js 一起使用,则在读取文件->转换为 base64 后得到的 base64 字符串与我在保存文件之前在 c# 中看到的值略有不同。 ( "P3Zjw6zDkVDDsnUdM3FcwoVTMVhBEQdKMjrCvjM=" in javascript 和 "P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z" in c# 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);
            }

【问题讨论】:

  • 我无法理解你想用base 64做什么。在解密之前,你首先encode到base 64?然后解密成功?你确定你不只是回收垃圾吗?
  • 感谢您回复 owlstead。在 c# 方面(教学应用程序),我正在使用 xml 字符串 -> 使用上面列出的 8 字节密钥/iv(默认块大小)加密到 DES。结果将转换为 base64 字符串。 File.WriteAllBytes 将此 base64 字符串转换为无符号 int [] 并写入文件。我只是想扭转 javascript/cryptojs 方面的过程。也许更简单地问一下 cryptoJS/JS 想在下面读回什么: EncryptToFile(DateTime.Now.ToString(), @"c:\temp\testdatetime.bin"); (使用上面定义的 EncryptToFile)
  • @CarpeNC 实际上保存到磁盘的是什么?

标签: javascript c# encryption cryptojs


【解决方案1】:

我也有同样的问题。我的密码由 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);
};

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 2014-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多