0

我看过一些关于这个的帖子,但我似乎无法让它工作,有什么想法吗?

结果:

C# Encrypted string test = O6qzYiLPCpbXUf8PjMHpcg==
php Encrypted string test = SdS1dN1ugyAVYGFzHiTayg==

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

string enctext = EncryptString("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");

PHP

function aesenc($message, $keystring, $ivstring){
    $IV_UTF = mb_convert_encoding($ivstring, 'UTF-8');
    $KEY_UTF = mb_convert_encoding($keystring, 'UTF-8');

    return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, $message, MCRYPT_MODE_CBC, $IV_UTF));
}

$enctext = aesenc("test", "qwertyuiopasdfghjklzxcvbnmqwerty", _"1234567890123456");
4

1 回答 1

3

找到了答案,需要在 php 中的 $message 中添加填充

function aesenc($message, $keystring, $ivstring){
    $IV_UTF = mb_convert_encoding($ivstring, 'UTF-8');
    $KEY_UTF = $keystring;

    return base64_encode( mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $KEY_UTF, addpadding($message), MCRYPT_MODE_CBC, $IV_UTF));
}
function addpadding($string, $blocksize = 16)
{
    $len = strlen($string);
    $pad = $blocksize - ($len % $blocksize);
    $string .= str_repeat(chr($pad), $pad);
    return $string;
}
于 2013-09-13T22:38:53.967 回答