Several common encryption algorithms in DotNet, and dotnet encryption algorithms

Source: Internet
Author: User
Tags dotnet

Several common encryption algorithms in DotNet, and dotnet encryption algorithms

In the. NET project, we usually use encryption. Because in Modern projects, the requirements for information security are getting higher and higher, so the encryption of more information becomes crucial. Several common encryption/decryption algorithms are provided.

1. for mutual conversion between text and Base64 encoded text and conversion between Byte [] and Base64 encoded text:

(1). convert normal text into Base64 encoded text

/// <Summary> /// convert plain text to Base64 encoded text /// </summary> /// <param name = "value"> plain text </ param> // <returns> </returns> public static string StringToBase64String (string value) {if (string. isNullOrEmpty (value) {throw new ArgumentNullException (value);} try {var binBuffer = (new UnicodeEncoding ()). getBytes (value); var base64ArraySize = (int) Math. ceiling (binBuffer. length/3d) * 4; var charBuffer = new char [base64ArraySize]; Convert. toBase64CharArray (binBuffer, 0, binBuffer. length, charBuffer, 0); var s = new string (charBuffer); return s;} catch (Exception ex) {throw new Exception (ex. message );}}

(2) convert the Base64 encoded text into common text

/// <Summary> /// convert Base64 encoded text to plain text /// </summary> /// <param name = "base64"> Base64 encoded text </param> /// <returns> </returns> public static string Base64StringToString (string base64) {if (string. isNullOrEmpty (base64) {throw new ArgumentNullException (base64);} try {var charBuffer = base64.ToCharArray (); var bytes = Convert. fromBase64CharArray (charBuffer, 0, charBuffer. length); return (new UnicodeEncoding ()). getString (bytes);} catch (Exception ex) {throw new Exception (ex. message );}}

(3). Convert Byte [] to Base64 encoded text

/// <Summary> /// convert Byte [] to Base64 encoded text /// </summary> /// <param name = "binBuffer"> Byte [] </param> // <returns> </returns> public string ToBase64 (byte [] binBuffer) {if (binBuffer = null) {throw new ArgumentNullException ("binBuffer");} try {var base64ArraySize = (int) Math. ceiling (binBuffer. length/3d) * 4; var charBuffer = new char [base64ArraySize]; Convert. toBase64CharArray (binBuffer, 0, binBuffer. length, charBuffer, 0); var s = new string (charBuffer); return s;} catch (Exception ex) {throw new Exception (ex. message );}}

(4). Convert Base64 encoded text to Byte []

/// <Summary> /// convert Base64 encoded text to Byte [] /// </summary> /// <param name = "base64"> Base64 encoded text </param> /// <returns> </returns> public byte [] Base64ToBytes (string base64) {if (string. isNullOrEmpty (base64) {throw new ArgumentNullException (base64);} try {var charBuffer = base64.ToCharArray (); var bytes = Convert. fromBase64CharArray (charBuffer, 0, charBuffer. length); return bytes;} catch (Exception ex) {throw new Exception (ex. message );}}

2. DES encryption/Decryption class.

(1). Encryption

Private static readonly string KEY = "pengze0902 "; /// <summary> /// encryption /// </summary> /// <param name = "Text"> </param> /// <returns> </ returns> public static string Encrypt (string Text) {return Encrypt (Text, KEY );} /// <summary> /// encrypt data /// </summary> /// <param name = "Text"> </param> /// <param name = "sKey"> </param> // <returns> </returns> public static string Encrypt (string Text, string sKey) {var des = new DESCryptoServiceProvider (); var inputByteArray = Encoding. default. getBytes (Text); var bKey = Encoding. ASCII. getBytes (Md5Hash (sKey ). substring (0, 8); des. key = bKey; des. 4 = bKey; var MS = new System. IO. memoryStream (); var cs = new CryptoStream (MS, des. createEncryptor (), CryptoStreamMode. write); cs. write (inputByteArray, 0, inputByteArray. length); cs. flushFinalBlock (); var ret = new StringBuilder (); foreach (byte B in ms. toArray () {ret. appendFormat ("{0: X2}", B);} return ret. toString ();}

(2). decrypt

Private static readonly string KEY = "pengze0902 "; /// <summary> /// decrypt /// </summary> /// <param name = "text"> </param> /// <returns> </ returns> public static string Decrypt (string text) {return Decrypt (text, KEY );} /// <summary> // decrypt the data /// </summary> /// <param name = "text"> </param> /// <param name = "sKey"> </param> // <returns> </returns> public static string Decrypt (string text, string sKey) {var des = new DESCryptoServiceProvider (); var len = text. length/2; byte [] inputByteArray = new byte [len]; int x; for (x = 0; x <len; x ++) {var I = Convert. toInt32 (text. substring (x * 2, 2), 16); inputByteArray [x] = (byte) I;} var bKey = Encoding. ASCII. getBytes (Md5Hash (sKey ). substring (0, 8); des. key = bKey; des. IV = bKey; System. IO. memoryStream MS = new System. IO. memoryStream (); CryptoStream cs = new CryptoStream (MS, des. createDecryptor (), CryptoStreamMode. write); cs. write (inputByteArray, 0, inputByteArray. length); cs. flushFinalBlock (); return Encoding. default. getString (ms. toArray ());}

(3). Obtain the MD5 encrypted string

//// <Summary> /// obtain the MD5 encryption string /// </summary> /// <param name = "input"> source plaintext string </param>/ // <returns> ciphertext string </returns> public static string Md5Hash (string input) {var md5 = new MD5CryptoServiceProvider (); var bs = Encoding. UTF8.GetBytes (input); bs = md5.ComputeHash (bs); var s = new StringBuilder (); foreach (var B in bs) {s. append (B. toString ("x2 "). toUpper ();} var password = s. toString (); return password ;}

3. MD5 Encryption

(1). 32 characters in upper case

/// <Summary> /// 32-bit uppercase // </summary> /// <returns> </returns> public static string Upper32 (string s) {var hashPasswordForStoringInConfigFile = System. web. security. formsAuthentication. hashPasswordForStoringInConfigFile (s, "md5"); if (hashPasswordForStoringInConfigFile! = Null) s = hashPasswordForStoringInConfigFile. ToString (); return s. ToUpper ();}

(2). 32 characters in lowercase

/// <Summary> /// 32-bit lower case /// </summary> /// <returns> </returns> public static string Lower32 (string s) {var hashPasswordForStoringInConfigFile = System. web. security. formsAuthentication. hashPasswordForStoringInConfigFile (s, "md5"); if (hashPasswordForStoringInConfigFile! = Null) s = hashPasswordForStoringInConfigFile. ToString (); return s. ToLower ();}

(3). 16 characters in upper case

/// <Summary> /// 16-digit uppercase // </summary> /// <returns> </returns> public static string Upper16 (string s) {var hashPasswordForStoringInConfigFile = System. web. security. formsAuthentication. hashPasswordForStoringInConfigFile (s, "md5"); if (hashPasswordForStoringInConfigFile! = Null) s = hashPasswordForStoringInConfigFile. ToString (); return s. ToUpper (). Substring (8, 16 );}

(4). 16 characters in lower case

/// <Summary> /// 16-bit lower case /// </summary> /// <returns> </returns> public static string Lower16 (string s) {var hashPasswordForStoringInConfigFile = System. web. security. formsAuthentication. hashPasswordForStoringInConfigFile (s, "md5"); if (hashPasswordForStoringInConfigFile! = Null) s = hashPasswordForStoringInConfigFile. ToString (); return s. ToLower (). Substring (8, 16 );}

4. Sha1 Signature Algorithm

/// <Summary> /// signature algorithm /// </summary> /// <param name = "str"> </param> /// <returns> </returns> public static string GetSha1 (string str) {if (string. isNullOrEmpty (str) {throw new ArgumentNullException (str);} try {// create SHA1 object SHA1 sha = new SHA1CryptoServiceProvider (); // convert mystr to byte [] var enc = new ASCIIEncoding (); var dataToHash = enc. getBytes (str); // var dataHashed = sha. computeHash (dataToHash); // converts the computation result to string var hash = BitConverter. toString (dataHashed ). replace ("-", ""); return hash;} catch (Exception ex) {throw new Exception (ex. message );}}

5. Sha256 Encryption Algorithm

/// <Summary> /// convert the string to a sha256 hash // </summary> /// <param name = "data"> string </param >/// <returns> sha256 hash or null </returns> public static string ToSha256 (this string data) {try {if (string. isNullOrEmpty (data) return null; var hashValue = new SHA256Managed (). computeHash (Encoding. UTF8.GetBytes (data); var hex = hashValue. aggregate ("", (current, x) => current + String. format ("{0: x2}", x); if (string. isNullOrEmpty (hex) throw new Exception ("Erro creating SHA256 hash"); return hex;} catch (Exception e) {throw new Exception (e. message, e );}}

The above are some commonly used algorithm code.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.