在C#和PHP之间进行Rijndael 256位加密/解密?

11

更新

我已经更改了C#代码,使其使用块大小为256。但现在,你好世界看起来像这样http://pastebin.com/5sXhMV11,我无法弄清楚应该使用什么来与rtrim()配合以去除末尾的混乱。

另外,当您说IV应该是随机的时候,您是否意味着不要多次使用相同的IV,或者我编写的方法是错误的?

再次感谢!

嗨,

我正在尝试使用PHP解密由C#加密的字符串。我似乎无法使用mcrypt解密它,所以需要一些帮助。我得到以下错误,因此我猜测我没有正确设置IV。

错误:IV参数必须与块大小一样长

两个函数都使用相同的密码,密钥,IV并设置为CBC模式:

C#中的加密文本= UmzUCnAzThH0nMkIuMisqg==
32位长的密钥= qwertyuiopasdfghjklzxcvbnmqwerty
16位长的iv = 1234567890123456

C#

    public static string EncryptString(string message, string KeyString, string IVString)
    {
        byte[] Key = ASCIIEncoding.UTF8.GetBytes(KeyString);
        byte[] IV = ASCIIEncoding.UTF8.GetBytes(IVString);

        string encrypted = null;
        RijndaelManaged rj = new RijndaelManaged();
        rj.Key = Key;
        rj.IV = IV;
        rj.Mode = CipherMode.CBC;

        try
        {
            MemoryStream ms = new MemoryStream();

            using (CryptoStream cs = new CryptoStream(ms, rj.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
            {
                using (StreamWriter sw = new StreamWriter(cs))
                {
                    sw.Write(message);
                    sw.Close();
                }
                cs.Close();
            }
            byte[] encoded = ms.ToArray();
            encrypted = Convert.ToBase64String(encoded);

            ms.Close();
        }
        catch (CryptographicException e)
        {
            Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
            return null;
        }
        catch (UnauthorizedAccessException e)
        {
            Console.WriteLine("A file error occurred: {0}", e.Message);
            return null;
        }
        catch (Exception e)
        {
            Console.WriteLine("An error occurred: {0}", e.Message);
        }
        finally
        {
            rj.Clear();
        }

        return encrypted;
    }

PHP

var $mcrypt_cipher = MCRYPT_RIJNDAEL_256;
var $mcrypt_mode = MCRYPT_MODE_CBC;

function decrypt($key, $iv, $encrypted)
{
    $encrypted = base64_decode($encrypted);

    $decrypted = rtrim(mcrypt_decrypt($this->mcrypt_cipher, $key, $encrypted, $this->mcrypt_mode, $iv), "\0");;
    return $decrypted;
}

谢谢


1
IV 应该真正被随机化。如果没有随机化,它就失去了存在的意义。 - quantumSoup
Rijndael使用256位块是非标准的。 - kroiz
2个回答

11
如果你想在C#应用程序中使用Rijndael256,你需要将BlockSize设置为256。
RijndaelManaged rj = new RijndaelManaged();
rj.BlockSize = 256;

接下来,您的iv也必须是256位长。
请参见SymmetricAlgorithm.BlockSize Property


或者反过来说:当前您的C#应用程序使用Rijndael128,因此您的php脚本也必须使用Rijndael128。

<?php
class Foo {
  protected $mcrypt_cipher = MCRYPT_RIJNDAEL_128;
  protected $mcrypt_mode = MCRYPT_MODE_CBC;

  public function decrypt($key, $iv, $encrypted)
  {
    $iv_utf = mb_convert_encoding($iv, 'UTF-8');
    return mcrypt_decrypt($this->mcrypt_cipher, $key, base64_decode($encrypted), $this->mcrypt_mode, $iv_utf);
  }
}



$encrypted = "UmzUCnAzThH0nMkIuMisqg==";
$key = "qwertyuiopasdfghjklzxcvbnmqwerty";
$iv = "1234567890123456";

$foo = new Foo;
echo $foo->decrypt($key, $iv, $encrypted);

打印出 hello world


3
我知道这不是你的错,但静脉注射应该真正随机化。如果不这样做,它的存在就没有意义了。 - quantumSoup
1
同意。请参见http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.generateiv.aspx和http://docs.php.net/function.mcrypt-create-iv。 - VolkerK
请问您能看到这个吗? https://dev59.com/g3fZa4cB1Zd3GeqPMw58 - hsuk
真的,但这只是一个例子 ;) - Digital Human

-1

使用PHP进行加密;

/Generate public key for encrytion
$path = "keys/";

    $crt = openssl_x509_read(file_get_contents($path."cert.crt"));
    $publickey = openssl_get_publickey($crt);

    //Encrypt using public key
    openssl_public_encrypt($source, $crypted, $publickey);

    //openssl_private_encrypt($source, $crypted, $privkey);
    echo base64_encode($crypted);

使用C#进行解密

    X509Certificate2 x509cert = new X509Certificate2(pKeyFilename);
    RSACryptoServiceProvider.UseMachineKeyStore = false;
    RSACryptoServiceProvider crypt = (RSACryptoServiceProvider)x509cert.PrivateKey;                

    byte[] decrypted = crypt.Decrypt(Convert.FromBase64String(data), false);
    return ASCIIEncoding.UTF8.GetString(decrypted);

其中pKeyFilename是使用证书文件cert.crt创建的个人信息交换文件。此示例使用AES-256加密。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接