CarpeNC
CarpeNC

Reputation: 1

CryptoJS Decrypt Of C# DES Encrypted File Failing

We have an xml file that tracks a users progress through lessons in a stand-alone training application. The xml is DES encrypted -> converted to base64 string -> written to file via the following c# code

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));                                   
}

Decrypting works fine in the standalone application with the following code:

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;
}

As a simpler test, I DES encrypted a DateTime string "10/2/2014 10:54:25 AM" in this format. It's base64 string after encryption is P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z. If I manually set this base64 string in the js/cryptojs (see below), I'm able to successfully decrypt the originally (c#) encrypted datetime in js/cryptojs.

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

I just can't seem to load the data back from a saved file using either readAsArrayBuffer or readAsBinaryString. If I use readAsBinaryString with the js below, the base64 string I get after reading the file->converting to base64 is slightly different than the value I see in c# prior to saving the file. ( "P3Zjw6zDkVDDsnUdM3FcwoVTMVhBEQdKMjrCvjM=" in javascript and "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);
            }

Upvotes: 0

Views: 990

Answers (1)

伯虎唐
伯虎唐

Reputation: 11

I have the same issue here. My password are stored by Unity but I have to read them using JS. Thanks to your post, it espired me. And I finally come out with some result.

Are you sure "10/2/2014 10:54:25 AM" after Base64 will be "P3Zj7NFQ8nUdM3FchVMxWEERB0oyOr4z" ? I think this is your problem.

BTW, I use this function, it works fine:

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);
};

hope this can help you

Upvotes: 1

Related Questions