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