C# 加密解密類

來源:互聯網
上載者:User

using System.Security.Cryptography;

#region RC2
/// <summary>
/// 進行RC2加密。
/// </summary>
/// <param name="pToEncrypt">要加密的字串。</param>
/// <param name="sKey">初始化向量</param>
/// <param name="IV">密鑰,且必須為8位。</param>
/// <returns>以Base64格式返回的加密字串。</returns>
public static string Encrypt(string pToEncrypt, byte[] key, byte[] IV)
{
//建立UTF-16 編碼,用來在byte[]和string之間轉換
System.Text.UnicodeEncoding textConverter = new UnicodeEncoding();
byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
using (RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider())
{
System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateEncryptor(key, IV);

System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, Encryptor, CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Convert.ToBase64String(ms.ToArray());
ms.Close();
return str;
}
}

/// <summary>
/// 進行RC2解密。
/// </summary>
/// <param name="pToDecrypt">要解密的以Base64</param>
/// <param name="sKey">初始化向量</param>
/// <param name="IV">密鑰,且必須為8位。</param>
/// <returns>已解密的字串。</returns>
public static string Decrypt(string pToDecrypt, byte[] key, byte[] IV)
{
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
using (RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider())
{
System.Security.Cryptography.ICryptoTransform Encryptor = rc2CSP.CreateDecryptor(key, IV);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, Encryptor, CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}

#endregion

#region RSA

/// <summary>
/// RSA加密
/// </summary>
/// <param name="DataToEncrypt"></param>
/// <param name="DoOAEPPadding"></param>
/// <returns></returns>
static public byte[] RSAEncrypt(byte[] DataToEncrypt, bool DoOAEPPadding)
{
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

StreamReader reader = new StreamReader(@"d:\PublicKey.xml");
string PKey = reader.ReadToEnd();
RSA.FromXmlString(PKey);
reader.Close();

return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);

return null;
}

}

/// <summary>
/// RSA解密
/// </summary>
/// <param name="DataToDecrypt"></param>
/// <param name="DoOAEPPadding"></param>
/// <returns></returns>
static public byte[] RSADecrypt(byte[] DataToDecrypt, bool DoOAEPPadding)
{
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

StreamReader reader = new StreamReader(@"d:\PublicAndPrivateKey.xml");
string PPKey = reader.ReadToEnd();
RSA.FromXmlString(PPKey);
reader.Close();

return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
}
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());

return null;
}

}

#endregion

#region DES

/// <summary>
/// 進行DES加密。
/// </summary>
/// <param name="pToEncrypt">要加密的字串。</param>
/// <param name="sKey">密鑰,且必須為8位。</param>
/// <returns>以Base64格式返回的加密字串。</returns>
public static string Encrypt(string pToEncrypt, string sKey)
{
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
byte[] inputByteArray = Encoding.UTF8.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Convert.ToBase64String(ms.ToArray());
ms.Close();
return str;
}
}

/// <summary>
/// 進行DES解密。
/// </summary>
/// <param name="pToDecrypt">要解密的以Base64</param>
/// <param name="sKey">密鑰,且必須為8位。</param>
/// <returns>已解密的字串。</returns>
public static string Decrypt(string pToDecrypt, string sKey)
{
byte[] inputByteArray = Convert.FromBase64String(pToDecrypt);
using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
{
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cs.Close();
}
string str = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return str;
}
}

#endregion

#region MD5

[Test]
public void TestMD5()
{
Console.WriteLine(this.EncodePassword("1"));
}

string EncodePassword(string originalPassword)
{
//Declarations
Byte[] originalBytes;
Byte[] encodedBytes;
MD5 md5;

//Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
md5 = new MD5CryptoServiceProvider();
originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
encodedBytes = md5.ComputeHash(originalBytes);

//Convert encoded bytes back to a 'readable' string
return BitConverter.ToString(encodedBytes);
}

#endregion

#region RC4

/// <summary>
/// 加密或解密(對稱)
/// </summary>
/// <param name="data">明文或密文</param>
/// <param name="pass">密鑰</param>
/// <returns>密文或明文</returns>
public Byte[] EncryptEx(Byte[] data, String pass)
{
if (data == null || pass == null) return null;
Byte[] output = new Byte[data.Length];
Int64 i = 0;
Int64 j = 0;
Byte[] mBox = GetKey(Encoding.UTF8.GetBytes(pass), 256);

// 加密
for (Int64 offset = 0; offset < data.Length; offset++)
{
i = (i + 1) % mBox.Length;
j = (j + mBox[i]) % mBox.Length;
Byte temp = mBox[i];
mBox[i] = mBox[j];
mBox[j] = temp;
Byte a = data[offset];
//Byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];
// mBox[j] 一定比 mBox.Length 小,不需要在模數
Byte b = mBox[(mBox[i] + mBox[j]) % mBox.Length];
output[offset] = (Byte)((Int32)a ^ (Int32)b);
}

return output;
}

/// <summary>
/// 解密
/// </summary>
/// <param name="data"></param>
/// <param name="pass"></param>
/// <returns></returns>
public Byte[] DecryptEx(Byte[] data, String pass)
{
return EncryptEx(data, pass);
}

/// <summary>
/// 打亂密碼
/// </summary>
/// <param name="pass">密碼</param>
/// <param name="kLen">密碼箱長度</param>
/// <returns>打亂後的密碼</returns>
static private Byte[] GetKey(Byte[] pass, Int32 kLen)
{
Byte[] mBox = new Byte[kLen];

for (Int64 i = 0; i < kLen; i++)
{
mBox[i] = (Byte)i;
}
Int64 j = 0;
for (Int64 i = 0; i < kLen; i++)
{
j = (j + mBox[i] + pass[i % pass.Length]) % kLen;
Byte temp = mBox[i];
mBox[i] = mBox[j];
mBox[j] = temp;
}
return mBox;
}

#endregion

#region AES

/// <summary>
/// 擷取密鑰
/// </summary>
private static string Key
{
get { return @")O[NB]6,YF}+efcaj{+oESb9d8>Z'e9M"; }
}

/// <summary>
/// 擷取向量
/// </summary>
private static string IV
{
get { return @"L+\~f4,Ir)b$=pkf"; }
}

/// <summary>
/// AES加密
/// </summary>
/// <param name="plainStr">明文字串</param>
/// <param name="returnNull">加密失敗時是否返回 null,false 返回 String.Empty</param>
/// <returns>密文</returns>
public string AESEncrypt(string plainStr, bool returnNull)
{
string encrypt = AESEncrypt(plainStr);
return returnNull ? encrypt : (encrypt == null ? String.Empty : encrypt);
}

/// <summary>
/// AES加密
/// </summary>
/// <param name="plainStr">明文字串</param>
/// <returns>密文</returns>
public string AESEncrypt(string plainStr)
{
byte[] bKey = Encoding.UTF8.GetBytes(Key);
byte[] bIV = Encoding.UTF8.GetBytes(IV);
byte[] byteArray = Encoding.UTF8.GetBytes(plainStr);

string encrypt = null;
Rijndael aes = Rijndael.Create();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateEncryptor(bKey, bIV), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
encrypt = Convert.ToBase64String(mStream.ToArray());
}
}
}
catch { }
aes.Clear();

return encrypt;
}

/// <summary>
/// AES解密
/// </summary>
/// <param name="encryptStr">密文字串</param>
/// <param name="returnNull">解密失敗時是否返回 null,false 返回 String.Empty</param>
/// <returns>明文</returns>
public string AESDecrypt(string encryptStr, bool returnNull)
{
string decrypt = AESDecrypt(encryptStr);
return returnNull ? decrypt : (decrypt == null ? String.Empty : decrypt);
}

/// <summary>
/// AES解密
/// </summary>
/// <param name="encryptStr">密文字串</param>
/// <returns>明文</returns>
public string AESDecrypt(string encryptStr)
{
byte[] bKey = Encoding.UTF8.GetBytes(Key);
byte[] bIV = Encoding.UTF8.GetBytes(IV);
byte[] byteArray = Convert.FromBase64String(encryptStr);

string decrypt = null;
Rijndael aes = Rijndael.Create();
try
{
using (MemoryStream mStream = new MemoryStream())
{
using (CryptoStream cStream = new CryptoStream(mStream, aes.CreateDecryptor(bKey, bIV), CryptoStreamMode.Write))
{
cStream.Write(byteArray, 0, byteArray.Length);
cStream.FlushFinalBlock();
decrypt = Encoding.UTF8.GetString(mStream.ToArray());
}
}
}
catch { }
aes.Clear();

return decrypt;
}

#endregion

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.