使用C#AES加密加密;从这些PHP代码解密

时间:2014-01-08 12:19:32

标签: c# php encryption aes rijndael

我在使用PHP进行AES加密时会遇到一些问题,并使用C#对其进行解码。我的参考site

这是PHP代码:

function encrypt_string($input, $key)
   {
       $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
       return preg_replace('/=/', "", base64_encode($iv . mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hash("sha256", $key, true), $input, MCRYPT_MODE_CBC, $iv)));
   }

function decrypt_string($input, $key)
   {
       $input .= "=";
       $data = base64_decode($input);
       $iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
       return rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128,hash('sha256', $key, true),substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),MCRYPT_MODE_CBC,$iv),"\0");
   }

这是我尝试过的C#代码:

private static byte[] sha256_data(string input)
{
    SHA256 hash = SHA256Managed.Create();
    Encoding encode = Encoding.UTF8;
    return hash.ComputeHash(encode.GetBytes(input));
}

private string encode_data(string data, string key)
{
    byte[] buff;

    RijndaelManaged rij = new RijndaelManaged();

    rij.BlockSize = 256;
    rij.KeySize = 256;

    rij.GenerateIV();
    rij.Key = sha256_data(key);

    rij.Mode = CipherMode.CBC;
    ICryptoTransform encoder = rij.CreateEncryptor(rij.Key, rij.IV);
    using (MemoryStream mem = new MemoryStream())
    {
        using (CryptoStream crypt = new CryptoStream(mem, encoder, CryptoStreamMode.Write))
        {
            byte[] temp = Encoding.UTF8.GetBytes(data);
            crypt.Write(temp, 0, temp.Length);

        }
        buff = mem.ToArray();
    }
    return Convert.ToBase64String(result);
} 

private string decode_data(string input, string key)
{
    RijndaelManaged rij = new RijndaelManaged();

    rij.KeySize = 256;
    rij.BlockSize = 256;

    rij.Key = sha256_data(key);
    rij.GenerateIV();

    rij.Mode = CipherMode.CBC;
    rij.Padding = PaddingMode.PKCS7;

    ICryptoTransform decrypter = rij.CreateDecryptor();

    byte[] buff;
    using (MemoryStream mem = new MemoryStream())
    {
        using (CryptoStream cstream = new CryptoStream(mem, decrypter, CryptoStreamMode.Write))
        {
            byte[] data = Convert.FromBase64String(input);
            cstream.Write(data, 0, data.Length);
        }
        buff = mem.ToArray();
    }
    return Encoding.UTF8.GetString(buff);
}

我做错了什么?

1 个答案:

答案 0 :(得分:0)

解码时,必须解析用于编码的IV而不生成新的。