21 Ekim 2016 Cuma

c# ile php arasında şifreli iletişim

Encryption
$iv_to_pass_to_decryption = '';
function encrypt($text, $key)
{
    $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC), MCRYPT_RAND); 
    $iv_to_pass_to_decryption = base64_encode($iv);
    return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv); 
}
Decryption
function decrypt($text, $key, $iv)
{ 
    $text = base64_decode($text);
    $iv = base64_decode($iv);
    return mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
}
C#
Encryption
iv_to_pass_to_decryption = "";
public string encrypt(string text, string key)
{
    byte[] _encdata;
    MemoryStream ms = new MemoryStream();
    RijndaelManaged aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;
    aes.Padding = PaddingMode.Zeros;
    aes.Mode = CipherMode.CBC;
    aes.GenerateIV();
    iv_to_pass_to_decryption = Convert.ToBase64String(aes.IV);
    ICryptoTransform encryptor = aes.CreateEncryptor(Encoding.Default.GetBytes(key), aes.IV);
    byte[] _text = Encoding.Default.GetBytes(text);
 
    CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write);
    cs.Write(_text, 0, _text.Length);
    cs.FlushFinalBlock();
 
    _encdata = ms.ToArray();
    ms.Close();
    cs.Close();
 
    return Convert.ToBase64String(_encdata);
}
Decryption
public string decrypt(string text, string key, string iv)
{
    byte[] _data;
    int i = 0;
    MemoryStream ms = new MemoryStream(Convert.FromBase64String(text));
    RijndaelManaged aes = new RijndaelManaged();
    aes.KeySize = 256;
    aes.BlockSize = 256;
    aes.Padding = PaddingMode.Zeros;
    aes.Mode = CipherMode.CBC;
    ICryptoTransform decryptor = aes.CreateDecryptor(
            Encoding.Default.GetBytes(key), Convert.FromBase64String(iv));
    CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
    _data = new byte[ms.Length];
    i = cs.Read(_data, 0, _data.Length);
    return Encoding.Default.GetString(_data, 0, i);
}
Tip!