Skip to content

Instantly share code, notes, and snippets.

@loufq
Created May 12, 2014 07:49
Show Gist options
  • Save loufq/ad61d070cabeda6b26c3 to your computer and use it in GitHub Desktop.
Save loufq/ad61d070cabeda6b26c3 to your computer and use it in GitHub Desktop.
C# aes-256-cbc DecryptEncrypt
/// <summary>
/// aes-256-cbc 解码
/// </summary>
/// <param name="cipherData"></param>
/// <param name="keyString"></param>
/// <param name="ivString"></param>
/// <returns></returns>
public static string Decrypt(string cipherData, string keyString, string ivString)
{
byte[] key = Encoding.UTF8.GetBytes(keyString);
byte[] iv = Encoding.UTF8.GetBytes(ivString);
try
{
using (var rijndaelManaged =
new RijndaelManaged { Key = key, IV = iv, Mode = CipherMode.CBC })
using (var memoryStream =
new MemoryStream(Convert.FromBase64String(cipherData)))
using (var cryptoStream =
new CryptoStream(memoryStream,
rijndaelManaged.CreateDecryptor(key, iv),
CryptoStreamMode.Read))
{
return new StreamReader(cryptoStream).ReadToEnd();
}
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
// You may want to catch more exceptions here...
}
/// <summary>
/// aes-256-cbc 加密
/// </summary>
/// <param name="message"></param>
/// <param name="KeyString"></param>
/// <param name="IVString"></param>
/// <returns></returns>
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;
}
//call
string reta = DeEncode.EncryptString("中文cnn", "12345678901234561234567890123456", "1234567890123456");
string retb = DeEncode.Decrypt(reta, "12345678901234561234567890123456", "1234567890123456");
@pluveto
Copy link

pluveto commented Mar 11, 2020

牛逼! 完美适配 php 的相关函数.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment