C # Encapsulates a class of cryptographic algorithms (MD5, SHA, HMAC, DES, RSA)

Source: Internet
Author: User
Tags hmac md5 encryption sha1 sha1 encryption sha256 algorithm asymmetric encryption


Using System;
Using System.IO;
Using System.Security.Cryptography;
Using System.Text;

Namespace Wen.Helpers
{
    /// <summary>
    /// Security Assistant
    /// </summary>
    Public sealed class SecurityHelper
    {
        Private static readonly byte [] IvBytes = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF };

        #region Universal Encryption Algorithm

        /// <summary>
        /// hash encryption algorithm
        /// </summary>
        /// <param name="hashAlgorithm"> The base class from which all cryptographic hash algorithm implementations must be derived </param>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Private static string HashEncrypt( HashAlgorithm hashAlgorithm, string input, Encoding encoding)
        {
            Var data = hashAlgorithm.ComputeHash(encoding.GetBytes(input));

            Return BitConverter .ToString(data).Replace( "-", "" );
        }

        /// <summary>
        /// Verify the hash value
        /// </summary>
        /// <param name="hashAlgorithm"> The base class from which all cryptographic hash algorithm implementations must be derived </param>
        /// <param name="unhashedText"> unencrypted string </param>
        /// <param name="hashedText"> Encrypted hash </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Private static bool VerifyHashValue( HashAlgorithm hashAlgorithm, string unhashedText, string hashedText,
            Encoding encoding)
        {
            Return string .Equals(HashEncrypt(hashAlgorithm, unhashedText, encoding), hashedText,
                StringComparison .OrdinalIgnoreCase);
        }

        #endregion Universal Encryption Algorithm

        #region hash encryption algorithm

        #region MD5 Algorithm

        /// <summary>
        /// MD5 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string MD5Encrypt( string input, Encoding encoding)
        {
            Return HashEncrypt(MD5 .Create(), input, encoding);
        }

        /// <summary>
        /// Verify the MD5 value
        /// </summary>
        /// <param name="input"> unencrypted string </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static bool VerifyMD5Value( string input, Encoding encoding)
        {
            Return VerifyHashValue(MD5 .Create(), input, MD5Encrypt(input, encoding), encoding);
        }

        #endregion MD5 Algorithm

        #region SHA1 Algorithm

        /// <summary>
        /// SHA1 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string SHA1Encrypt( string input, Encoding encoding)
        {
            Return HashEncrypt(SHA1 .Create(), input, encoding);
        }

        /// <summary>
        /// Verify the SHA1 value
        /// </summary>
        /// <param name="input"> unencrypted string </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static bool VerifySHA1Value( string input, Encoding encoding)
        {
            Return VerifyHashValue(SHA1 .Create(), input, SHA1Encrypt(input, encoding), encoding);
        }

        #endregion SHA1 Algorithm

        #region SHA256 Algorithm

        /// <summary>
        /// SHA256 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string SHA256Encrypt( string input, Encoding encoding)
        {
            Return HashEncrypt(SHA256 .Create(), input, encoding);
        }

        /// <summary>
        /// Verify the SHA256 value
        /// </summary>
        /// <param name="input"> unencrypted string </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static bool VerifySHA256Value( string input, Encoding encoding)
        {
            Return VerifyHashValue(SHA256 .Create(), input, SHA256Encrypt(input, encoding), encoding);
        }

        #endregion SHA256 Algorithm

        #region SHA384 Algorithm

        /// <summary>
        /// SHA384 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string SHA384Encrypt( string input, Encoding encoding)
        {
            Return HashEncrypt(SHA384 .Create(), input, encoding);
        }

        /// <summary>
        /// Verify the SHA384 value
        /// </summary>
        /// <param name="input"> unencrypted string </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static bool VerifySHA384Value( string input, Encoding encoding)
        {
            Return VerifyHashValue(SHA256 .Create(), input, SHA384Encrypt(input, encoding), encoding);
        }

        #endregion SHA384 Algorithm

        #region SHA512 Algorithm

        /// <summary>
        /// SHA512 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="encodin
g"> character encoding </param>
        /// <returns></returns>
        Public static string SHA512Encrypt( string input, Encoding encoding)
        {
            Return HashEncrypt(SHA512 .Create(), input, encoding);
        }

        /// <summary>
        /// Verify the SHA512 value
        /// </summary>
        /// <param name="input"> unencrypted string </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static bool VerifySHA512Value( string input, Encoding encoding)
        {
            Return VerifyHashValue(SHA512 .Create(), input, SHA512Encrypt(input, encoding), encoding);
        }

        #endregion SHA512 Algorithm

        #region HMAC-MD5 Encryption

        /// <summary>
        /// HMAC-MD5 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="key"> key </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string HMACSMD5Encrypt( string input, string key, Encoding encoding)
        {
            Return HashEncrypt(new HMACMD5 (encoding.GetBytes(key)), input, encoding);
        }

        #endregion HMAC-MD5 Encryption

        #region HMAC-SHA1 Encryption

        /// <summary>
        /// HMAC-SHA1 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="key"> key </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string HMACSHA1Encrypt( string input, string key, Encoding encoding)
        {
            Return HashEncrypt(new HMACSHA1 (encoding.GetBytes(key)), input, encoding);
        }

        #endregion HMAC-SHA1 Encryption

        #region HMAC-SHA256 Encryption

        /// <summary>
        /// HMAC-SHA256 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="key"> key </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string HMACSHA256Encrypt( string input, string key, Encoding encoding)
        {
            Return HashEncrypt(new HMACSHA256 (encoding.GetBytes(key)), input, encoding);
        }

        #endregion HMAC-SHA256 Encryption

        #region HMAC-SHA384 Encryption

        /// <summary>
        /// HMAC-SHA384 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="key"> key </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string HMACSHA384Encrypt( string input, string key, Encoding encoding)
        {
            Return HashEncrypt(new HMACSHA384 (encoding.GetBytes(key)), input, encoding);
        }

        #endregion HMAC-SHA384 Encryption

        #region HMAC-SHA512 Encryption

        /// <summary>
        /// HMAC-SHA512 encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="key"> key </param>
        /// <param name="encoding"> character encoding </param>
        /// <returns></returns>
        Public static string HMACSHA512Encrypt( string input, string key, Encoding encoding)
        {
            Return HashEncrypt(new HMACSHA512 (encoding.GetBytes(key)), input, encoding);
        }

        #endregion HMAC-SHA512 Encryption

        #endregion Hash Encryption Algorithm

        #region symmetric encryption algorithm

        #region Des encryption and decryption

        /// <summary>
        /// DES encryption
        /// </summary>
        /// <param name="input"> string to be encrypted </param>
        /// <param name="key"> key (8 digits) </param>
        /// <returns></returns>
        Public static string DESEncrypt( string input, string key)
        {
            Try
            {
                Var keyBytes = Encoding .UTF8.GetBytes(key);
                //var ivBytes = Encoding.UTF8.GetBytes(iv);

                Var des = DES .Create();
                des.Mode = CipherMode .ECB; // compatible with other languages Des encryption algorithm
                des.Padding = PaddingMode .Zeros; //Automatically fill 0

                Using (var ms = new MemoryStream ())
                {
                    Var data = Encoding .UTF8.GetBytes(input);

                    Using (var cs = new CryptoStream (ms, des.CreateEncryptor(keyBytes, IvBytes), CryptoStreamMode .Write)
                        )
                    {
                        cs.Write(data, 0, data.Length);
                        cs.FlushFinalBlock();
                    }

                    Return Convert .ToBase64String(ms.ToArray());
                }
            }
            Catch
            {
                Return input;
            }
        }

        /// <summary>
        /// DES decryption
        /// </summary>
        /// <param name="input"> string to be decrypted </param>
        /// <param name="key"> key (8 digits) </param>
        /// <returns></returns>
        Public static string DESDecrypt( string input, string key)
        {
            Try
            {
                Var keyBytes = Encoding .UTF8.GetBytes(key);
                //var ivBytes = Encoding.UTF8.GetBytes(iv);

                Var des = DES .Create();
                des.Mode = CipherMode .ECB; /
/Des encryption algorithm compatible with other languages
                des.Padding = PaddingMode .Zeros; //Automatically fill 0

                Using (var ms = new MemoryStream ())
                {
                    Var data = Convert .FromBase64String(input);

                    Using (var cs = new CryptoStream (ms, des.CreateDecryptor(keyBytes, IvBytes), CryptoStreamMode .Write)
                        )
                    {
                        cs.Write(data, 0, data.Length);

                        cs.FlushFinalBlock();
                    }

                    Return Encoding .UTF8.GetString(ms.ToArray());
                }
            }
            Catch
            {
                Return input;
            }
        }

        #endregion Des encryption and decryption

        #endregion symmetric encryption algorithm

        #region asymmetric encryption algorithm

        /// <summary>
        /// Generate RSA public and private keys
        /// </summary>
        /// <param name="publicKey"> public key </param>
        /// <param name="privateKey"> private key </param>
        Public static void GenerateRSAKeys( out string publicKey, out string privateKey)
        {
            Using (var rsa = new RSACryptoServiceProvider ())
            {
                publicKey = rsa.ToXmlString( false );
                privateKey = rsa.ToXmlString( true );
            }
        }

        /// <summary>
        /// RSA encryption
        /// </summary>
        /// <param name="publickey"> public key </param>
        /// <param name="content"> content to be encrypted </param>
        /// <returns> encrypted string </returns>
        Public static string RSAEncrypt( string publickey, string content)
        {
            Var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(publickey);
            Var cipherbytes = rsa.Encrypt(Encoding .UTF8.GetBytes(content), false);

            Return Convert .ToBase64String(cipherbytes);
        }

        /// <summary>
        /// RSA decryption
        /// </summary>
        /// <param name="privatekey"> private key </param>
        /// <param name="content"> content to be decrypted </param>
        /// <returns> decrypted string </returns>
        Public static string RSADecrypt( string privatekey, string content)
        {
            Var rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(privatekey);
            Var cipherbytes = rsa.Decrypt(Convert .FromBase64String(content), false);

            Return Encoding .UTF8.GetString(cipherbytes);
        }

        #endregion Asymmetric encryption algorithm
    }
}  





C # Encapsulates a class of cryptographic algorithms (MD5, SHA, HMAC, DES, RSA)


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.