C#的AES加密解密(ECB)

测试网站:在线AES加密解密、AES在线加密解密、AES encryption and decryption

输出类型不同,则选择不同的获得byte数组方式    

    //base64
    Byte[] encryptedBytes = Convert.FromBase64String(Data);
    //hex
    //Byte[] encryptedBytes = hexStringToByteArray(Data);

本段代码来源:AES加密解密通用版Object-C / C# / JAVA

///   
/// AES加密(无向量)  
///   
/// 被加密的明文  
/// 密钥  
/// 密文  
private static string AESEncrypt(String Data, String Key)
{
	MemoryStream mStream = new MemoryStream();
	RijndaelManaged aes = new RijndaelManaged();
	byte[] plainBytes = Encoding.UTF8.GetBytes(Data);
	Byte[] bKey = new Byte[32];
	Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

	aes.Mode = CipherMode.ECB;
	aes.Padding = PaddingMode.PKCS7;
	aes.KeySize = 128;
	//aes.Key = _key;  
	aes.Key = bKey;
	//aes.IV = _iV;  
	CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
	try
	{
		cryptoStream.Write(plainBytes, 0, plainBytes.Length);
		cryptoStream.FlushFinalBlock();
		return Convert.ToBase64String(mStream.ToArray());
	}
	finally
	{
		cryptoStream.Close();
		mStream.Close();
		aes.Clear();
	}
}

/// AES解密(无向量)  
///   
/// 被加密的明文  
/// 密钥  
/// 明文  
private static string AESDecrypt(String Data, String Key)
{
    //base64
	Byte[] encryptedBytes = Convert.FromBase64String(Data);
    //hex
    //Byte[] encryptedBytes = hexStringToByteArray(Data);
	Byte[] bKey = new Byte[32];
	Array.Copy(Encoding.UTF8.GetBytes(Key.PadRight(bKey.Length)), bKey, bKey.Length);

	MemoryStream mStream = new MemoryStream(encryptedBytes);
	//mStream.Write( encryptedBytes, 0, encryptedBytes.Length );  
	//mStream.Seek( 0, SeekOrigin.Begin );  
	RijndaelManaged aes = new RijndaelManaged();
	aes.Mode = CipherMode.ECB;
	aes.Padding = PaddingMode.PKCS7;
	aes.KeySize = 128;
	aes.Key = bKey;
	//aes.IV = _iV;  
	CryptoStream cryptoStream = new CryptoStream(mStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
	try
	{
		byte[] tmp = new byte[encryptedBytes.Length + 32];
		int len = cryptoStream.Read(tmp, 0, encryptedBytes.Length + 32);
		byte[] ret = new byte[len];
		Array.Copy(tmp, 0, ret, 0, len);
		return Encoding.UTF8.GetString(ret);
	}
	finally
	{
		cryptoStream.Close();
		mStream.Close();
		aes.Clear();
	}
}

十六进制字符串转byte数组

/// 
/// 
/// 
/// 
/// 
private byte[] hexStringToByteArray(string strHex)
{
	strHex = strHex.Replace(" ", "");
	byte[] buffer = new byte[strHex.Length / 2];
	for (int i = 0; i < strHex.Length; i += 2)
	{
		buffer[i / 2] = (byte)Convert.ToByte(strHex.Substring(i, 2), 16);
	}
	return buffer;
}

 

你可能感兴趣的:(C#,AES,ECB)