c# - Rijndael:C++加密,C#解密

标签 c# c++ encryption cryptography rijndael

我的情况:我正在用 C# 重写一个服务器,它是用 C++ 编写的,用于学习目的。在某些时候,客户端将向服务器发送一个加密的密码。他们使用 Rijndael 加密作为密码。 你可以在这里找到原始的加密类:

Rijndael.h:https://github.com/astorks/FlyFF/blob/master/Source/_Common/Rijndael.h

Rijndael.cpp:https://github.com/astorks/FlyFF/blob/master/Source/_Common/Rijndael.cpp#L926

如您在 .cpp 文件中所见,他们使用此 key 和 IV:

char const* CRijndael::sm_chain0 = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";

char    szDefaultKey[32] = "dldhsvmflvm";

这是他们实际解密原始服务器中密码的部分 ( https://github.com/astorks/FlyFF/blob/master/Source/CERTIFIER/DPCertifier.cpp#L256 )

// MAX_PASSWORD is actually 42. So 16*42 = 672 byte
char szEnc[ 16 * MAX_PASSWORD ] = {0, };
char szDec[ 16 * MAX_PASSWORD ] = {0, };

ar.Read( szEnc, 16 * MAX_PASSWORD );

g_xRijndael->ResetChain();
g_xRijndael->Decrypt( szEnc, szDec, 16 * MAX_PASSWORD, CRijndael::CBC );

现在我正处于从客户端正确获取数据包以及需要解密密码的部分。我当前的 C# 代码没有正确解密数据,我也不知道为什么。这是我的代码:

public static class Rijndael
    {
        private static ICryptoTransform decryptor { get; set; }
        private static RijndaelManaged rijndael { get; set; }

        public static void Init()
        {
            byte[] decryptKey = Encoding.ASCII.GetBytes("dldhsvmflvm").Concat(Enumerable.Repeat((byte)0, 21).ToArray()).ToArray();
            byte[] decryptIV = Enumerable.Repeat((byte)0, 16).ToArray();
            // I've tried BlockSize 128 and 256. It actually should be 128 since it's 16 on the original server (16 * 8 = 128)
            rijndael = new RijndaelManaged() { Padding = PaddingMode.Zeros, Mode = CipherMode.CBC, KeySize = 256, BlockSize = 128, Key = decryptKey, IV = decryptIV };
            decryptor = rijndael.CreateDecryptor(decryptKey, decryptIV);
        }


        public static string decrypt(byte[] data)
        {
            string password = null;
            using (MemoryStream ms = new MemoryStream(data))
                using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    using (StreamReader sr = new StreamReader(cs))
                        password = sr.ReadToEnd();
            return password;
        }
    }

他们在服务器端选择了 32 个字节,但只填充了 11 个字符:dldhsvmflvm。这就是为什么我用 0 填充其他 21 个字节。 32*8 = 256 位 = key 大小

当我使用像 byte[32] 这样的 IV 并用 0 填充它时,我得到一个错误。它说 smth 就像 IV 不适合 block 大小。这就是为什么它现在有 16 个字节并填充了 0。这可能是问题所在,如果是,我该如何解决?

除此之外,我不知道哪里出了问题。希望你能拯救我的一天,Stackoverflow。 :)

最佳答案

正如 xanatos 所说,我添加了 5 个零而不是 21 个,因为它们的 key 应该只有 16 个字节而不是 32 个字节。 它现在工作没有问题。感谢大家!

关于c# - Rijndael:C++加密,C#解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35450834/

相关文章:

c++ - vtkRenderer 错误

c++ - eclipse ncurses 和 xterm,打印未知字符

使用C语言破解凯撒密码

encryption - 为什么使用 3DES 和 Blowfish 而不是 AES

c# - Azure Web 角色——如何保护开源项目?

c# - PerlEmbed - C# - 单声道 - Linux

c# - ApiController 中的异步初始化

c# - 如何在请求过滤器的 ViewResult 上设置 View 模型?

c# - “找不到路径 '/favicon.ico' 的 Controller ...”错误

c++ - 类内枚举