Mcrypt加密C#相当于PHP(Rijndael 128 with 32bit hexKey)

时间:2017-12-12 15:13:45

标签: c# php encryption mcrypt rijndael

如果有人在其他地方询问/回答我很抱歉,但我无法找到它。

我目前正在尝试在C#中复制PHP mcrypt的结果。 PHP是后端服务器。我在ECB模式下使用Rijndael 128和256bit(32 char)hexKey。

现在我知道ECB不如CBC那么安全,而且mcrypt已经贬值但是我不是那个开发后端并且没有选择以这种方式做的人(相信我,我问过)。

测试密码: testPassword

hexKey: 2619eeaed2cb05f60f298b7af8e565e4f155dd76821865994d4e660d7c041281

P.S。 hexKey不是我们正在使用的实际密钥;)

这是我在PHP中的代码

$key = $this->hexToStr([key]);
$text = $password;
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $text, MCRYPT_MODE_ECB);

private function hexToStr($hex) {
$string = '';
for ($i = 0; $i < strlen($hex) - 1; $i+=2) {
    $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
}
return $string;
}

我在C#中的代码

    public string EncryptStringRijndael(string value)
    {
        try
        {
            string cipherText;
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(value);

            var rijndael = new RijndaelManaged
            {
                Key = Encoding.ASCII.GetBytes(HexStringToString(hexKey)),
                Mode = CipherMode.ECB,
                BlockSize = 128,
                KeySize = 256,
            };

            var encryptor = rijndael.CreateEncryptor(rijndael.Key, null);
            MemoryStream memoryStream = new MemoryStream();
            CryptoStream cryptoStream = new CryptoStream
            (
                memoryStream,
                encryptor,
                CryptoStreamMode.Write
            );
            cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
            cryptoStream.FlushFinalBlock();
            byte[] cipherTextBytes = memoryStream.ToArray();

            cipherText = Encoding.ASCII.GetString(cipherTextBytes);
            //cipherText = StringToHexString(tempText);

            return cipherText;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public static string HexStringToString(string hexString)
    {
        try
        {
            string ascii = string.Empty;

            for (int i = 0; i < hexString.Length; i += 2)
            {
                String hs = string.Empty;

                hs = hexString.Substring(i, 2);
                uint decval = Convert.ToUInt32(hs, 16);
                char character = Convert.ToChar(decval);
                ascii += character;
            }
            return ascii;
        }
        catch (Exception ex)
        {
            return ex.Message;
        }
    }

    public static string StringToHexString(string originalString)
    {
        string outp = string.Empty;
        char[] value = originalString.ToCharArray();
        foreach (char L in value)
        {
            int V = Convert.ToInt32(L);
            outp += string.Format("{0:x}", V);
        }
        return outp;
    }

PHP结果:G. g / D&gt; Y 5

C#结果:??? u \ 0 ?? 9?`???

我做错了什么?

感谢所有帮助:)

0 个答案:

没有答案