.Net常见的几种加密方式

2021-11-21|

.Net加密算法主要分为:对称算法、非对称算法、哈希算法、随机算法。每种算法都有自己的使用场景,例如 保护隐私(防止查看)、保护完整性(防止更改)、数字签名、生成秘钥、秘钥交换、生成随机数等。
按照不同场景,微软建议使用的算法如下:

  • 数据隐私:Aes
  • 数据完整性:HMACSHA256、HMACSHA512
  • 数字签名:ECDsa、RSA
  • 密钥交换:ECDiffieHellman、RSA
  • 随机数生成:RandomNumberGenerator
  • 从密码生成密钥:Rfc2898DeriveBytes

一、私钥加密

私钥加密也称之为对称加密,因为使用的是相同的秘钥来加密、解密。对称加密是对流执行的,所以可以对大数据进行加密。对称加密速度比公钥加密速度快。对称算法要求创建秘钥和初始化向量(IV),秘钥必须保密、IV可以公开但应定期更改。常见的私钥加密有:DES、AES、HMACSHA256、HMACSHA384、HMACSHA512等。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 秘钥长度
            //16位密钥 = 128位
            //24位密钥 = 192位
            //32位密钥 = 256位
            Aes aes = Aes.Create();
            KeySizes[] ks = aes.LegalKeySizes;
            foreach (KeySizes k in ks)
            {
                Console.WriteLine("\tLegal min key size = " + k.MinSize);
                Console.WriteLine("\tLegal max key size = " + k.MaxSize);
                Console.WriteLine("\tLegal skipsize = " + k.SkipSize);
            }
            //This sample produces the following output:
            //        Legal min key size = 128
            //        Legal max key size = 256
            //        Legal skipsize = 64
            #endregion

            string original = "Here is some data to encrypt!";
            
            // Create a new instance of the Aes
            // class.  This generates a new key and initialization
            // vector (IV).
            //using (Aes myAes = Aes.Create())
            //{
            //   var strkey = Convert.ToBase64String(myAes.Key);
            //   var striv = Convert.ToBase64String(myAes.IV);
            //}

            var strkey = "BlkUeVL1KZ/AVTo36ziIOIg+cvztnOCUlc3HNoQBs8c=";
            var striv = "G2+hseZr74KJtu1BCdzdwQ==";

            //Aes加密
            var encrypted = AesEncrypt(original, strkey, striv);
            //Aes解密
            string roundtrip = AesDecrypt(encrypted, strkey, striv);

            Console.WriteLine("Encrypted:   {0}", encrypted);
            Console.WriteLine("Round Trip: {0}", roundtrip);
 
            Console.ReadLine();
        }
 
        /// 
        /// Aes加密
        /// 
        /// 
        /// 
        /// 
        /// 
        static string AesEncrypt(string plainText, string strkey, string striv)
        {
            var Key = Convert.FromBase64String(strkey);
            var IV = Convert.FromBase64String(striv);

            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                //密钥
                aesAlg.Key = Key;
                //初始化向量
                aesAlg.IV = IV;
                //运算模式
                aesAlg.Mode = CipherMode.CBC;
                //填充模式
                aesAlg.Padding = PaddingMode.PKCS7;
                //加密操作的块大小(以位为单位)
                aesAlg.BlockSize = 128;

                // Create an encryptor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {
                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }

            // Return the encrypted bytes from the memory stream.
            //return encrypted;

            return Convert.ToBase64String(encrypted);
        }

        /// 
        /// Aes解密
        /// 
        /// 
        /// 
        /// 
        /// 
        static string AesDecrypt(string text, string strkey, string striv)
        {
            byte[] cipherText = Convert.FromBase64String(text);
            var Key = Convert.FromBase64String(strkey);
            var IV = Convert.FromBase64String(striv);


            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an Aes object
            // with the specified key and IV.
            using (Aes aesAlg = Aes.Create())
            {
                //密钥
                aesAlg.Key = Key;
                //初始化向量
                aesAlg.IV = IV;
                //运算模式
                aesAlg.Mode = CipherMode.CBC;
                //填充模式
                aesAlg.Padding = PaddingMode.PKCS7;
                //加密操作的块大小(以位为单位)
                aesAlg.BlockSize = 128;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }

            return plaintext;
        }
 
    }
}

二、公钥加密

公钥加密也称之为非对称加密,因为使用的是可公开的公钥加密数据、受保护的私钥解密数据。公钥算法是对少数字节执行的,执行速度比私钥算法慢,所以只适用于少量数据的加密,并且设计的目的也不是用于大数据加密。公钥算法也可以用与数字签名,使用私钥签名数据,公钥验证签名。
常见的公钥算法有:

  • RSA:可用于加密数据和数字签名。
  • DSA:只能用于数字签名,没有RSA安全。
  • ECDiffieHellman:只能用于秘钥生成。
  • ECDsa
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region netframework-4.5
            //RSA
            /*
              Create a new instance of the RSA class.
              Export the public key information and send it to a third party.
            */
            //using (RSA rsa = RSA.Create())
            //{
            //    var publicKey1 = rsa.ToXmlString(false);//公钥
            //    var privateKey1 = rsa.ToXmlString(true);//公钥、私钥
            //}

            var publicKey = "38BMPKXER5pb33bslSPaibF7rrCPDFI2Ur6NQs7+Nflb3u+sLNVeNdLkO+8jevqEJRYbX8aJveTc3oCN9YqIqZVLlP9dSpbKCiJURp7KXPiBwzm4R+3KHf4SQbDU1r9ehj+FPxIHxkmRyDI8YVmrk3qSlgbcuY7WY0JFhtx8clU=AQAB";
            var privateKey = "38BMPKXER5pb33bslSPaibF7rrCPDFI2Ur6NQs7+Nflb3u+sLNVeNdLkO+8jevqEJRYbX8aJveTc3oCN9YqIqZVLlP9dSpbKCiJURp7KXPiBwzm4R+3KHf4SQbDU1r9ehj+FPxIHxkmRyDI8YVmrk3qSlgbcuY7WY0JFhtx8clU=AQAB

9wP5W44hIosp3xRfeWBHRlWjIj17MW4TF29YFo/lC6pZH0Onw1ARggBaRRmjZhFsrMNQQ5x+t2mItW/YQ9czpw==

5+O0BloSYXJPxK8VMQi4gwpC7b+rqfjKlesD8TSlsmq91fvIKuOuVC7Dntbi3EVikQnuMm4gJtB5mu5x8KLZow==RoMn527HHqlDJp8WMfu93OINU3ThedbGNGZgavBgndfe4QHbHfH5TXb0Tc1ny3cl4ptOij5eHdVOZRysS5Fe+Q==xD25Tl7Pi1QYGZUp0/NTYuI+PcGlXxTDLRhUn740M8eNnBeWEGXaVDe3KSclmc/GWIQU5uy3nOF06B6+oizPDQ==Ukdbn+ggSHfzJq1CVL4XP5pB5CFpX+vkLJ7WoVFo1RpUKMEPtehSpKGL62fZ7fHsZzExcHhqvm5kSyXKNqGBUQ==20WXMKP+u3Dw8giYhvuQ8fllzOcn+JoktGgbBUrW40wQlWRpZbJf1f1rP7T2H1Gb6MBGaVCmsdqz/LUc6XEuxLTAKT4sfkUlBcGS6L5GIEzNMfDwetOLQn8YCM/qsaFdNtwhl4J0CTJQkbeTLQ0rO/iWKF87F37WcUb/Jnk7h40=
"; #region 数据加密 /* Wait for the third party to encrypt some data and send it back. */ //1.公钥加密 var str = "我是非对称加密/公钥加密。"; var strEncrypt = ""; using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(publicKey); //OAEP:最优非对称加密填充 //OAEP是RSA填充的一种模式,在PKCS#1v2.0(PKCS#1标准现在已经升级到2.2版本)中提出,用于取代原先的PKCS#1v1.5版本中的填充机制 strEncrypt = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(str), true)); } //2.私钥解密 strEncrypt = "zTDCMDIHdsAAq5kfJToaUVOqDPyucz9qAaFM0GaHCghlojpMnNk/X3NGy0WGgH62qg868yYbGPFskYtC80hY+vdewXZnCHCT+Fm9ynqcb34wLwi9SpvRT0Fd+cm9xX28sQiHb16UyKE3PS1flguvRXffPA9cAoo9phECOBlCpUo="; using (var rsa = new RSACryptoServiceProvider()) { rsa.FromXmlString(privateKey); var strDecrypt = Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(strEncrypt), true)); } #endregion #endregion //1.RSA加密/解密数据 /* Create a new instance of the RSA class. Export the public key information and send it to a third party. */ //using (RSA rsa = RSA.Create()) //{ // var publicKey = Convert.ToBase64String(rsa.ExportRSAPublicKey()); // var privateKey = Convert.ToBase64String(rsa.ExportRSAPrivateKey()); //} var publicKey = "MIIBCgKCAQEA0h/4AXjUCBc5Jokw6xpQ0ubJIkWuOLTZ9R1YpBjYWWMsBDWSWaKdfEcuYA9LaJWqyHx1CSkUapn2WVfCdFz/qkpeXD64loxSSQPqp0cEDGTMELZTWYs73FtK8wObryGDVlSwTdihGJZ+ryMi1RuAcjKq8zIiZwpZRU8p8Im2LJ+xW5Zs+wFyRNNuGmc7XeRpLdWZurv0MefA/h+8eGiReYwGBwmEYxeZHvoO6FuqbmIwOHlG/v2b9Oxvy4WSzbOCOxm8cut85cUuzXMp1OyqQ7MNbcD6eCJzMwzstOhz6s36y7//7vigGbJOeJ7oAKc4mUcz54TUaTnrKgGLXCQoJQIDAQAB"; var privateKey = "MIIEowIBAAKCAQEA0h/4AXjUCBc5Jokw6xpQ0ubJIkWuOLTZ9R1YpBjYWWMsBDWSWaKdfEcuYA9LaJWqyHx1CSkUapn2WVfCdFz/qkpeXD64loxSSQPqp0cEDGTMELZTWYs73FtK8wObryGDVlSwTdihGJZ+ryMi1RuAcjKq8zIiZwpZRU8p8Im2LJ+xW5Zs+wFyRNNuGmc7XeRpLdWZurv0MefA/h+8eGiReYwGBwmEYxeZHvoO6FuqbmIwOHlG/v2b9Oxvy4WSzbOCOxm8cut85cUuzXMp1OyqQ7MNbcD6eCJzMwzstOhz6s36y7//7vigGbJOeJ7oAKc4mUcz54TUaTnrKgGLXCQoJQIDAQABAoIBAQCH4qCx4v/L06jj4Oi/wZ7vJMyB22oVxe8F8tp2FJMlC1tVxYdFbEJIMogtGvb7RX7SdJoDOIu5fKOxl21rbxDvgXSQVwdsZIZ6LYw8bVKS6USGskIosEAf+vH3QigWE6gp1k7FqQhVLE302NYX1tc0AsxGxe81j523ksBei9BB/j8eefkYBjD5NfD3yVMeGpEnfZ032QxNEuHuS+ZNQy6tMnss72vO9rCdlpkU4EAufGW9Gi/w3wUeJj0BpOpts2Q+AbeC5GKCDlEb9z9K2sMSbCc33tcYe+BnTk7QeiHRQSnK1DLg+CvLlmVZesIl1H2lgo6+uWCch1gZao6E1yapAoGBANeV4OhynZBVJRvA2RvtFVGQpW9TOpK8j2j5bNNBospeqPr0QDdovFfoLukNXRvG7XDhKR0B+ivD9mC+hHopZv2klcxIzo2spg9NoSUs0uy1FCAcC33G9UrE8C5+tstaHeSk8ahaNUab8+bN32coAAxVVwa8UFtROYnm+FHWJ/qvAoGBAPmECEW84nsxwZ0Cc8gZ84s8shzEwQIhLzo7iKMp4rw+Bblyw1pAkN75EQGFKm122i/WsQIE8dAOSzIlSWkI0pnRNAQLpXkYqwiUqEKRsNIlusl8679PAOnVWUpOQLifvxWVduFdiUw0OFdDJOj9VoOPTs1fuw4PaZYJk6UFK+9rAoGAZ8qAvWhw80wK0ZHG9OrvmJVLEI3BZWPip2duPUccWNG6CRgO0p5aDvh5nToR2Y2sQuwkHxMUnn154JnYrffA3dyfQfrLdunoCPYW3w71fYCwb8UQwz1GWvj1qWzYFI8OVUYUEjlb7OKoSjZTmBZp74Ymn9eJ2G0ChqHsa3nvRYECgYBMBe5/UQ2we3iCXjzouv95bQTXvxsPiwzYsUrwa9KpiDw2RMFAvmtlhH2p+Oj0cUIJUWCdPORwf+ppXPMBDa8dLqCqmuHQA7QY6TJbFgjJ/rTqryUlJO0iUd7ixPTzS7js2p1eDSHIFiEUdWDJnGa/rupTqNdVcVy6WjCiFvFMAQKBgHTk3mnmYA2xrc0tfF2NgqwVfWWz/WDdtHL6HYVmqxqp4rmp+an4odI2RbavMFD7ia4PZy0FZI0E9sJnrEw3akgbanoylsJ9WCowSN0UWqsI0wEZN3x05tMiKdwMY15cp0yy8LUGkWSC+BUjYCKqYsYY9TSplKIlPkXnn/2+yf8M"; /* Wait for the third party to encrypt some data and send it back. */ //1.公钥加密 var str = "我是非对称加密/公钥加密。"; var strEncrypt = ""; using (var rsa = RSA.Create()) { rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out int bytesRead); strEncrypt = Convert.ToBase64String(rsa.Encrypt(Encoding.UTF8.GetBytes(str), RSAEncryptionPadding.Pkcs1)); } //2.私钥解密 strEncrypt = "O1njlv9Om7VvrcGmMXXOG6+Pdk7NkRJqeeBnFpSCwhQs5NNvUmnRH3JOI0t+qEu3cfn+CAIiVE9Xp/RfKYO7dGtKonXzsSjZX1R4n1gyGMmG6tdqVnHFPFXFhUvQzEAqj5YJOGZPyiiRn6VFPl7WQcxkn5UyP+H4TMXEBqVlGSvQLe4KjwiY8zfyfNIZn+fp3W69QglJ1Wd9fLxp/9gGvPKezKu2uszEAByV/FvYFIOZr2zuGm9Tpal20q0xEKiRkVdZNs+vOTe+s6Riccj8UkdXYkVDBAkaP8fKhZ5u5qU1YORCGbOIhbUlYXIINLVsFCh+5TGWEEdDD/Sf7wqEkA=="; using (var rsa = RSA.Create()) { rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out int bytesRead); var strDecrypt = Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(strEncrypt), RSAEncryptionPadding.Pkcs1)); } Console.ReadLine(); } } }

三、数字签名

数字签名使用的是公钥算法实现的,使用私钥签名数据、公钥验证数据,保护数据完整性。常见的数字签名算法有RSA、RSA2、ECDsa、DSA。

  • RSA:全称SHA1WithRSA,对RSA密钥的长度不限制,推荐使用2048位以上。
  • RSA2:全称SHA256WithRSA,强制要求RSA密钥的长度至少为2048,比RSA更加安全。
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            #region netframework-4.5
            //1.私钥生成签名
            //The hash value to sign.
            str = "我是RSA数字签名。";
            byte[] hashValue = CalcSHA256(str);

            byte[] signedHashValue;
            string signedStr;

            //Generate a public/private key pair.
            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(privateKey);

                //Create an RSAPKCS1SignatureFormatter object and pass it the
                //RSA instance to transfer the private key.
                RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);

                //Set the hash algorithm to SHA256.
                rsaFormatter.SetHashAlgorithm("SHA256");

                //Create a signature for hashValue and assign it to
                //signedHashValue.
                signedHashValue = rsaFormatter.CreateSignature(hashValue);
                signedStr = Convert.ToBase64String(signedHashValue);
            }

            //2.公钥验证签名
            str = "我是RSA数字签名。";
            signedStr = "rhzchQiUc4/hPz1Qcx6kSz8vmDkNNX/nLIzU0NkUJe/Mq7MrQBzHC5+NguPLy86UHkQKp3z1TxnIOSYS9rKAtn2B6rbDepd2jpwTed93qsC+ZrFh2gDXbKHHZFcmcqEwj2vjOpqibynC5Y5phu4dBExSCf4KsgInMrJM17maFJg=";

            hashValue = CalcSHA256(str);
            signedHashValue = Convert.FromBase64String(signedStr);

            using (var rsa = new RSACryptoServiceProvider())
            {
                rsa.FromXmlString(publicKey);
                RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                rsaDeformatter.SetHashAlgorithm("SHA256");
                if (rsaDeformatter.VerifySignature(hashValue, signedHashValue))
                {
                    Console.WriteLine("The signature is valid.");
                }
                else
                {
                    Console.WriteLine("The signature is not valid.");
                }
            }
            #endregion 


            #region RSA2数字签名
            //1.私钥生成签名
            //The hash value to sign.
            var str = "我是RSA数字签名。";
            byte[] hashValue = CalcSHA256(str);

            byte[] signedHashValue;
            string signedStr;

            //Generate a public/private key pair.
            using (var rsa = RSA.Create())
            {
                rsa.ImportRSAPrivateKey(Convert.FromBase64String(privateKey), out int bytesRead);

                //Create an RSAPKCS1SignatureFormatter object and pass it the
                //RSA instance to transfer the private key.
                RSAPKCS1SignatureFormatter rsaFormatter = new RSAPKCS1SignatureFormatter(rsa);

                //Set the hash algorithm to SHA256.
                rsaFormatter.SetHashAlgorithm("SHA256");

                //Create a signature for hashValue and assign it to
                //signedHashValue.
                signedHashValue = rsaFormatter.CreateSignature(hashValue);
                signedStr = Convert.ToBase64String(signedHashValue);
            }

            //2.公钥验证签名
            str = "我是RSA数字签名。";
            signedStr = "Gt8GYpwhSE2kUyYeCsaQQyWpViMW/Gl89gJ+riXZDte0etIX00MoFzn6nzIe7fm/xESytc/VAKn2LtT+5bNarHI1vT3VdjsrPJwFNb7mJiHxMA9hyz3gRikHu1v153DejlJ1cVDgV7y8NL79OpB6qZOuPmU/sP8Om3tqCLqTUDUkNR0+kxuDI7Jpysi30zmmsIT8VpcYoV+PYoCoDLE2UJgX7oPMS8FRNajS+3GIrVstn5nh+XiavUA32sC1iZN1gfwVGQRMVuNSFkVy5xwFBiDkU90ho+HLhaSW3Zh2uQpWphHYwMZLgSItahF43WIF4w0W1Y6+P0i3zfeYGNxKGg==";

            hashValue = CalcSHA256(str);
            signedHashValue = Convert.FromBase64String(signedStr);

            using (var rsa = RSA.Create())
            {
                rsa.ImportRSAPublicKey(Convert.FromBase64String(publicKey), out int bytesRead);
                RSAPKCS1SignatureDeformatter rsaDeformatter = new RSAPKCS1SignatureDeformatter(rsa);
                rsaDeformatter.SetHashAlgorithm("SHA256");
                if (rsaDeformatter.VerifySignature(hashValue, signedHashValue))
                {
                    Console.WriteLine("The signature is valid.");
                }
                else
                {
                    Console.WriteLine("The signature is not valid.");
                }
            }
            #endregion

            Console.ReadLine();
        }

        private static byte[] CalcSHA1(string str)
        {
            using (SHA1 sha = System.Security.Cryptography.SHA1.Create())
            {
                var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(str));
                return bytes;
            }
        }

        private static byte[] CalcSHA256(string str)
        {
            using (SHA256 sha = System.Security.Cryptography.SHA256.Create())
            {
                var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(str));
                return bytes;
            }
        }

    }
}

四、哈希算法

哈希算法将任意长度的二进制数据映射到较小的固定长度的二进制值,数据发生改变后,数据对应的哈希值也将改变。常见的哈希算法有MD5、SHA1、SHA256、SHA384、SHA512。由于MD5和SHA1发现了漏洞不安全,不推荐使用。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string original = "Here is some data to encrypt!";
             
            //1.MD5加密
            using (var md5 = MD5.Create())
            {
                var bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(original));

                var sb = new StringBuilder();
                foreach (var item in bytes)
                {
                    sb.Append(item.ToString("X2"));
                }

                Console.WriteLine($"MD5:{sb.ToString()}");
            }


            //2.SHA1加密
            using (SHA1 mySHA1 = SHA1.Create())
            {
                var bytes = mySHA1.ComputeHash(Encoding.UTF8.GetBytes(original));

                var sb = new StringBuilder();
                foreach (var item in bytes)
                {
                    sb.Append(item.ToString("X2"));
                }

                Console.WriteLine($"SHA256:{sb.ToString()}");
            }

            //3.SHA256加密
            using (SHA256 mySHA256 = SHA256.Create())
            {
                var bytes = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(original));

                var sb = new StringBuilder();
                foreach (var item in bytes)
                {
                    sb.Append(item.ToString("X2"));
                }

                Console.WriteLine($"SHA256:{sb.ToString()}");
            }


            //4.SHA512加密
            using (SHA512 mySHA256 = SHA512.Create())
            {
                var bytes = mySHA256.ComputeHash(Encoding.UTF8.GetBytes(original));

                var sb = new StringBuilder();
                foreach (var item in bytes)
                {
                    sb.Append(item.ToString("X2"));
                }

                Console.WriteLine($"SHA512:{sb.ToString()}");
            }
 
            Console.ReadLine();
        }
 
    }
}

五、随机数

随机数生成是很多加密操作的必要组成部分。 例如,加密密钥需要尽可能的随机,以便使其很难再现。

using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            var str="";
            //1.RandomNumberGenerator:
            #region 
            using (var random = RandomNumberGenerator.Create())
            {
                //生成32位秘钥
                var bytes = new byte[32];

                random.GetBytes(bytes);//用加密型强随机值序列填充字节数组。
                str = Convert.ToBase64String(bytes);
                Console.WriteLine(str);
            }
            #endregion

            //2.Random:
            #region 
            var rd = new Random();

            //1.生成32位秘钥
            var rdbytes = new byte[32];
            rd.NextBytes(rdbytes);
            str = Convert.ToBase64String(rdbytes);
            Console.WriteLine(str);

            //2.随机生成1-100的整数。
            for (int i = 0; i < 10; i++)
            {
                var num = rd.Next(0, 101);//生成介于指定下限(含)与指定上限(不含)之间的随机整数。
                Console.WriteLine(num);
            }


            //3. 随机生成姓名
            string[] malePetNames = { "Rufus", "Bear", "Dakota", "Fido",
                          "Vanya", "Samuel", "Koani", "Volodya",
                          "Prince", "Yiska" };

            Random rnd = new Random();
            // Generate random indexes for pet names.
            int mIndex = rnd.Next(malePetNames.Length);

            // Display the result.
            Console.WriteLine("Suggested pet name of the day: ");
            Console.WriteLine("   For a male:     {0}", malePetNames[mIndex]);

            //4.指定种子
            //使用的种子相同,生成的随机数也相同。
            var seed = (int)DateTime.Now.Ticks;
            var rd1 = new Random(seed);
            var rd2 = new Random(seed);
            Console.WriteLine(rd1.Next());
            Console.WriteLine(rd2.Next());

            // The example displays output similar to the following:
            //  2004787064
            //  2004787064 
            #endregion
 
            Console.ReadLine();
        }
 
    }
}

标签: 加密 using string 公钥 RSA System var 数字签名 Convert 算法
出处: https://www.toutiao.com/a7032872658840666638/

推荐

文明发言,请先登录

文明上网理性发言,请遵守国家法律法规。

最新评论

©2003- 黑基网 黑名单存档手机版网站地图免责条款法律声明隐私保护