DES(Data Encryption Standard):数据加密标准,速度较快,适用于加密大量数据的场合;3DES(Triple DES):是基于DES,对一块数据用三个不一样的密钥进行三次加密,强度更高;RC2和 RC4:用变长密钥对大量数据进行加密,比 DES 快;IDEA(International Data Encryption Algorithm)国际数据加密算法,使用 128 位密钥提供很是强的安全性;RSA:由 RSA 公司发明,是一个支持变长密钥的公共密钥算法,须要加密的文件快的长度也是可变的;DSA(Digital Signature Algorithm):数字签名算法,是一种标准的 DSS(数字签名标准);AES(Advanced Encryption Standard):高级加密标准,是下一代的加密算法标准,速度快,安全级别高,目前 AES 标准的一个实现是 Rijndael 算法;BLOWFISH,它使用变长的密钥,长度可达448位,运行速度很快;
MD5(Message Digest Algorithm 5):是RSA数据安全公司开发的一种单向散列算法,MD5被普遍使用,能够用来把不一样长度的数据块进行暗码运算成一个128位的数值;SHA(Secure Hash Algorithm)这是一种较新的散列算法,能够对任意长度的数据运算生成一个160位的数值;MAC(Message Authentication Code):消息认证代码,是一种使用密钥的单向函数,能够用它们在系统上或用户之间认证文件或消息。HMAC(用于消息认证的密钥散列法)就是这种函数的一个例子。CRC(Cyclic Redundancy Check):循环冗余校验码,CRC校验因为实现简单,检错能力强,被普遍使用在各类数据校验应用中。占用系统资源少,用软硬件均能实现,是进行数据传输差错检测地一种很好的手段(CRC 并非严格意义上的散列算法,但它的做用与散列算法大体相同,因此归于此类)。
DES:DESCryptoServiceProviderRC2:RC2CryptoServiceProviderRijndael(AES):RijndaelManaged3DES:TripleDESCryptoServiceProvider
DSA:DSACryptoServiceProviderRSA:RSACryptoServiceProvider
HMAC:HMACSHA1 (HMAC 为一种使用密钥的 Hash 算法)MAC:MACTripleDESMD5:MD5CryptoServiceProviderSHA1:SHA1Managed、SHA256Managed、SHA384Managed、SH7747.net12Managed
示例:html
public string GetMD5_32(string s, string _input_charset) { MD5 md5 = new MD5CryptoServiceProvider(); byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s)); StringBuilder sb = new StringBuilder(32); for (int i = 0; i < t.Length; i++) { sb.Append(t[i].ToString("x").PadLeft(2, '0'));//ToString("x")为十六进制表示,详细参考:https://msdn.microsoft.com/zh-cn/library/dwhawy9k } return sb.ToString(); } public string GetMD5_16(string ConvertString) { MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); t2 = t2.Replace("-", ""); return t2; }
/// <summary> /// use sha1 to encrypt string /// </summary> public string SHA1_Encrypt(string Source_String) { byte[] StrRes = Encoding.Default.GetBytes(Source_String); HashAlgorithm iSHA = new SHA1CryptoServiceProvider(); StrRes = iSHA.ComputeHash(StrRes); StringBuilder EnText = new StringBuilder(); foreach (byte iByte in StrRes) { EnText.AppendFormat("{0:x2}", iByte); } return EnText.ToString(); }
/// <summary> /// DES加密方法 /// </summary> /// <param name="strPlain">明文</param> /// <param name="strDESKey">密钥</param> /// <param name="strDESIV">向量</param> /// <returns>密文</returns> public string DESEncrypt(string strPlain, string strDESKey, string strDESIV) { //把密钥转换成字节数组 byte[] bytesDESKey = ASCIIEncoding.ASCII.GetBytes(strDESKey); //把向量转换成字节数组 byte[] bytesDESIV = ASCIIEncoding.ASCII.GetBytes(strDESIV); //声明1个新的DES对象 DESCryptoServiceProvider desEncrypt = new DESCryptoServiceProvider(); //开辟一块内存流 MemoryStream msEncrypt = new MemoryStream(); //把内存流对象包装成加密流对象 CryptoStream csEncrypt = new CryptoStream(msEncrypt, desEncrypt.CreateEncryptor(bytesDESKey, bytesDESIV), CryptoStreamMode.Write); //把加密流对象包装成写入流对象 StreamWriter swEncrypt = new StreamWriter(csEncrypt); //写入流对象写入明文 swEncrypt.WriteLine(strPlain); //写入流关闭 swEncrypt.Close(); //加密流关闭 csEncrypt.Close(); //把内存流转换成字节数组,内存流如今已是密文了 byte[] bytesCipher = msEncrypt.ToArray(); //内存流关闭 msEncrypt.Close(); //把密文字节数组转换为字符串,并返回 return UnicodeEncoding.Unicode.GetString(bytesCipher); } /// <summary> /// DES解密方法 /// </summary> /// <param name="strCipher">密文</param> /// <param name="strDESKey">密钥</param> /// <param name="strDESIV">向量</param> /// <returns>明文</returns> public string DESDecrypt(string strCipher, string strDESKey, string strDESIV) { //把密钥转换成字节数组 byte[] bytesDESKey = ASCIIEncoding.ASCII.GetBytes(strDESKey); //把向量转换成字节数组 byte[] bytesDESIV = ASCIIEncoding.ASCII.GetBytes(strDESIV); //把密文转换成字节数组 byte[] bytesCipher = UnicodeEncoding.Unicode.GetBytes(strCipher); //声明1个新的DES对象 DESCryptoServiceProvider desDecrypt = new DESCryptoServiceProvider(); //开辟一块内存流,并存放密文字节数组 MemoryStream msDecrypt = new MemoryStream(bytesCipher); //把内存流对象包装成解密流对象 CryptoStream csDecrypt = new CryptoStream(msDecrypt, desDecrypt.CreateDecryptor(bytesDESKey, bytesDESIV), CryptoStreamMode.Read); //把解密流对象包装成读出流对象 StreamReader srDecrypt = new StreamReader(csDecrypt); //明文=读出流的读出内容 string strPlainText = srDecrypt.ReadLine(); //读出流关闭 srDecrypt.Close(); //解密流关闭 csDecrypt.Close(); //内存流关闭 msDecrypt.Close(); //返回明文 return strPlainText; }
using System; using System.Security.Cryptography; using System.IO; using System.Text; namespace Microsoft.Samples.Security.PublicKey { class App { // Main entry point static void Main(string[] args) { // Instantiate 3 People for example. See the Person class below Person alice = new Person("Alice"); Person bob = new Person("Bob"); Person steve = new Person("Steve"); // Messages that will exchanged. See CipherMessage class below CipherMessage aliceMessage; CipherMessage bobMessage; CipherMessage steveMessage; // Example of encrypting/decrypting your own message Console.WriteLine("Encrypting/Decrypting Your Own Message"); Console.WriteLine("-----------------------------------------"); // Alice encrypts a message using her own public key aliceMessage = alice.EncryptMessage("Alice wrote this message"); // then using her private key can decrypt the message alice.DecryptMessage(aliceMessage); // Example of Exchanging Keys and Messages Console.WriteLine(); Console.WriteLine("Exchanging Keys and Messages"); Console.WriteLine("-----------------------------------------"); // Alice Sends a copy of her public key to Bob and Steve bob.GetPublicKey(alice); steve.GetPublicKey(alice); // Bob and Steve both encrypt messages to send to Alice bobMessage = bob.EncryptMessage("Hi Alice! - Bob."); steveMessage = steve.EncryptMessage("How are you? - Steve"); // Alice can decrypt and read both messages alice.DecryptMessage(bobMessage); alice.DecryptMessage(steveMessage); Console.WriteLine(); Console.WriteLine("Private Key required to read the messages"); Console.WriteLine("-----------------------------------------"); // Steve cannot read the message that Bob encrypted steve.DecryptMessage(bobMessage); // Not even Bob can use the Message he encrypted for Alice. // The RSA private key is required to decrypt the RS2 key used // in the decryption. bob.DecryptMessage(bobMessage); } // method Main } // class App class CipherMessage { public byte[] cipherBytes; // RC2 encrypted message text public byte[] rc2Key; // RSA encrypted rc2 key public byte[] rc2IV; // RC2 initialization vector } class Person { private RSACryptoServiceProvider rsa; private RC2CryptoServiceProvider rc2; private string name; // Maximum key size for the RC2 algorithm const int keySize = 128; // Person constructor public Person(string p_Name) { rsa = new RSACryptoServiceProvider(); rc2 = new RC2CryptoServiceProvider(); rc2.KeySize = keySize; name = p_Name; } // Used to send the rsa public key parameters public RSAParameters SendPublicKey() { RSAParameters result = new RSAParameters(); try { result = rsa.ExportParameters(false); } catch (CryptographicException e) { Console.WriteLine(e.Message); } return result; } // Used to import the rsa public key parameters public void GetPublicKey(Person receiver) { try { rsa.ImportParameters(receiver.SendPublicKey()); } catch (CryptographicException e) { Console.WriteLine(e.Message); } } public CipherMessage EncryptMessage(string text) { // Convert string to a byte array CipherMessage message = new CipherMessage(); byte[] plainBytes = Encoding.Unicode.GetBytes(text.ToCharArray()); // A new key and iv are generated for every message rc2.GenerateKey(); rc2.GenerateIV(); // The rc2 initialization doesnt need to be encrypted, but will // be used in conjunction with the key to decrypt the message. message.rc2IV = rc2.IV; try { // Encrypt the RC2 key using RSA encryption message.rc2Key = rsa.Encrypt(rc2.Key, false); } catch (CryptographicException e) { // The High Encryption Pack is required to run this sample // because we are using a 128-bit key. See the readme for // additional information. Console.WriteLine("Encryption Failed. Ensure that the" + " High Encryption Pack is installed."); Console.WriteLine("Error Message: " + e.Message); Environment.Exit(0); } // Encrypt the Text Message using RC2 (Symmetric algorithm) ICryptoTransform sse = rc2.CreateEncryptor(); MemoryStream ms = new MemoryStream(); CryptoStream cs = new CryptoStream(ms, sse, CryptoStreamMode.Write); try { cs.Write(plainBytes, 0, plainBytes.Length); cs.FlushFinalBlock(); message.cipherBytes = ms.ToArray(); } catch (Exception e) { Console.WriteLine(e.Message); } finally { ms.Close(); cs.Close(); } return message; } // method EncryptMessage public void DecryptMessage(CipherMessage message) { // Get the RC2 Key and Initialization Vector rc2.IV = message.rc2IV; try { // Try decrypting the rc2 key rc2.Key = rsa.Decrypt(message.rc2Key, false); } catch (CryptographicException e) { Console.WriteLine("Decryption Failed: " + e.Message); return; } ICryptoTransform ssd = rc2.CreateDecryptor(); // Put the encrypted message in a memorystream MemoryStream ms = new MemoryStream(message.cipherBytes); // the CryptoStream will read cipher text from the MemoryStream CryptoStream cs = new CryptoStream(ms, ssd, CryptoStreamMode.Read); byte[] initialText = new Byte[message.cipherBytes.Length]; try { // Decrypt the message and store in byte array cs.Read(initialText, 0, initialText.Length); } catch (Exception e) { Console.WriteLine(e.Message); } finally { ms.Close(); cs.Close(); } // Display the message received Console.WriteLine(name + " received the following message:"); Console.WriteLine(" " + Encoding.Unicode.GetString(initialText)); } // method DecryptMessage } // class Person } // namespace PublicKey