• 关于加密


     

    4、哈希加密密码

    using System.Web.Security;

    password = FormsAuthentication.HashPasswordForStoringInConfigFile(password + dr["注册IP"], "SHA1");

    5、关于加密:

    对流可以执行对称加密,因此对称加密对于加密大量的数据很有用。对少量字节执行不对称加密,因此不对称加密只对少量的数据有用

    ASP.NET中实现加密非常容易。.NET SDK中提供了FormsAuthentication类,其中的HashPasswordForStoringInConfigFile方法可直接使用MD5和SHA1算法。

    例: MD5.Text = FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text,"MD5");

      //SHA1 use FormsAuthentication.HashPasswordForStoringInConfigFile(TextBox1.Text,"SHA1");

    加密用于达到以下目的:

    保密性:防止用户的标识或数据被读取。

    数据完整性:防止数据被更改。

    身份验证:确保数据发自特定的一方

    私钥加密

    私钥加密又称为对称加密,因为同一密钥既用于加密又用于解密。私钥加密算法非常快(与公钥算法相比),特别适用于对较大的数据流执行加密转换。它使用一个密钥和一个初始化向量 (IV) 对数据执行加密转换

    NET Framework 提供以下实现私钥加密算法的类:

    DESCryptoServiceProvider

    RC2CryptoServiceProvider

    RijndaelManaged

    TripleDESCryptoServiceProvider

    DESCryptoServiceProvider 类

    示例使用具有指定 Key 和初始化向量 (IV) 的 DESCryptoServiceProvider,加密 inName 指定的文件,并将加密结果输出到 outName 指定的文件。

    private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)

     {   

         //Create the file streams to handle the input and output files.

         FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);

         FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);

         fout.SetLength(0);      

         //Create variables to help with read and write.

         byte[] bin = new byte[100]; //This is intermediate storage for the encryption.

         long rdlen = 0;              //This is the total number of bytes written.

         long totlen = fin.Length;    //This is the total length of the input file.

         int len;                     //This is the number of bytes to be written at a time.

         DES des = new DESCryptoServiceProvider();         

         CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);               

         Console.WriteLine("Encrypting...");

         //Read from the input file, then encrypt and write to the output file.

         while(rdlen < totlen)

         {

             len = fin.Read(bin, 0, 100);

             encStream.Write(bin, 0, len);

             rdlen = rdlen + len;

             Console.WriteLine("{0} bytes processed", rdlen);

         }

         encStream.Close(); 

         fout.Close();

         fin.Close();                  

     }

    [Visual Basic, C#] 可以相同的方法进行解密;使用 CreateDecryptor 而不是 CreateEncryptor。必须使用加密该文件所用的同一 Key 和 IV 进行解密。

    RC2CryptoServiceProvider 类

    using System;

    using System.IO;

    using System.Text;

    using System.Security.Cryptography;

    namespace RC2CryptoServiceProvider_Examples

    {

        class MyMainClass

        {

            public static void Main()

            {

                string original = "This is a much longer string of data than a public/private key algorithm will accept.";

                string roundtrip;

                ASCIIEncoding textConverter = new ASCIIEncoding();

                RC2CryptoServiceProvider rc2CSP = new RC2CryptoServiceProvider();

                byte[] fromEncrypt;

                byte[] encrypted;

                byte[] toEncrypt;

                byte[] key;

                byte[] IV;

                Console.WriteLine("Effective key size is {0} bits.", rc2CSP.EffectiveKeySize);           

                //Create a new key and initialization vector.

                rc2CSP.GenerateKey();

                rc2CSP.GenerateIV();

                //Get the key and IV.

                key = rc2CSP.Key;

                IV = rc2CSP.IV;

                //Get an encryptor.

                ICryptoTransform encryptor = rc2CSP.CreateEncryptor(key, IV);           

                //Encrypt the data.

                MemoryStream msEncrypt = new MemoryStream();

                CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

                //Convert the data to a byte array.

                toEncrypt = textConverter.GetBytes(original);

                //Write all data to the crypto stream and flush it.

                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);

                csEncrypt.FlushFinalBlock();

                //Get encrypted array of bytes.

                encrypted = msEncrypt.ToArray();

                //This is where the message would be transmitted to a recipient

                // who already knows your secret key. Optionally, you can

                // also encrypt your secret key using a public key algorithm

                // and pass it to the mesage recipient along with the RC2

                // encrypted message.           

                //Get a decryptor that uses the same key and IV as the encryptor.

                ICryptoTransform decryptor = rc2CSP.CreateDecryptor(key, IV);

                //Now decrypt the previously encrypted message using the decryptor

                // obtained in the above step.

                MemoryStream msDecrypt = new MemoryStream(encrypted);

                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

                fromEncrypt = new byte[encrypted.Length];

                //Read the data out of the crypto stream.

                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

                //Convert the byte array back into a string.

                roundtrip = textConverter.GetString(fromEncrypt);

                //Display the original data and the decrypted data.

                Console.WriteLine("Original:   {0}", original);

                Console.WriteLine("Round Trip: {0}", roundtrip);

            }

        }

    }

    RijndaelManaged 类

    using System;

    using System.IO;

    using System.Text;

    using System.Security.Cryptography;

    namespace RijndaelManaged_Examples

    {

        class MyMainClass

        {

            public static void Main()

            {

                string original = "This is a much longer string of data than a public/private key algorithm will accept.";

                string roundtrip;

                ASCIIEncoding textConverter = new ASCIIEncoding();

                RijndaelManaged myRijndael = new RijndaelManaged();

                byte[] fromEncrypt;

                byte[] encrypted;

                byte[] toEncrypt;

                byte[] key;

                byte[] IV;

                //Create a new key and initialization vector.

                myRijndael.GenerateKey();

                myRijndael.GenerateIV();

                //Get the key and IV.

                key = myRijndael.Key;

                IV = myRijndael.IV;

                //Get an encryptor.

                ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);           

                //Encrypt the data.

                MemoryStream msEncrypt = new MemoryStream();

                CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

                //Convert the data to a byte array.

                toEncrypt = textConverter.GetBytes(original);

                //Write all data to the crypto stream and flush it.

                csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);

                csEncrypt.FlushFinalBlock();

                //Get encrypted array of bytes.

                encrypted = msEncrypt.ToArray();

                //This is where the message would be transmitted to a recipient

                // who already knows your secret key. Optionally, you can

                // also encrypt your secret key using a public key algorithm

                // and pass it to the mesage recipient along with the RijnDael

                // encrypted message.           

                //Get a decryptor that uses the same key and IV as the encryptor.

                ICryptoTransform decryptor = myRijndael.CreateDecryptor(key, IV);

                //Now decrypt the previously encrypted message using the decryptor

                // obtained in the above step.

                MemoryStream msDecrypt = new MemoryStream(encrypted);

                CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);

                fromEncrypt = new byte[encrypted.Length];

                //Read the data out of the crypto stream.

                csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);

                //Convert the byte array back into a string.

                roundtrip = textConverter.GetString(fromEncrypt);

                //Display the original data and the decrypted data.

                Console.WriteLine("Original:   {0}", original);

                Console.WriteLine("Round Trip: {0}", roundtrip);

            }

        }

    }

    TripleDESCryptoServiceProvider 类

    示例使用具有指定 Key 和初始化向量 (IV) 的 TripleDESCryptoServiceProvider,加密 inName 指定的文件,并将加密结果输出到 outName 指定的文件

    private static void EncryptData(String inName, String outName, byte[] tdesKey, byte[] tdesIV)

    {   

        //Create the file streams to handle the input and output files.

        FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);

        FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);

        fout.SetLength(0);     

        //Create variables to help with read and write.

        byte[] bin = new byte[100]; //This is intermediate storage for the encryption.

        long rdlen = 0;              //This is the total number of bytes written.

        long totlen = fin.Length;    //This is the total length of the input file.

        int len;                     //This is the number of bytes to be written at a time.

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();         

        CryptoStream encStream = new CryptoStream(fout, tdes.CreateEncryptor(tdesKey, tdesIV), CryptoStreamMode.Write);              

        Console.WriteLine("Encrypting...");

        //Read from the input file, then encrypt and write to the output file.

        while(rdlen < totlen)

        {

            len = fin.Read(bin, 0, 100);

            encStream.Write(bin, 0, len);

            rdlen = rdlen + len;

            Console.WriteLine("{0} bytes processed", rdlen);

        }

        encStream.Close();                    

    }

    [Visual Basic, C#] 可以用同样的方式处理解密;使用 CreateDecryptor 而不是 CreateEncryptor。必须使用加密该文件所用的同一 Key 和 IV 进行解密。

    公钥加密

    公钥加密使用一个必须对未经授权的用户保密的私钥和一个可以对任何人公开的公钥。公钥和私钥都在数学上相关联;用公钥加密的数据只能用私钥解密,而用私钥签名的数据只能用公钥验证。公钥可以被任何人使用;该密钥用于加密要发送到私钥持有者的数据。两个密钥对于通信会话都是唯一的。公钥加密算法也称为不对称算法,公钥加密通常用于加密一个私钥算法将要使用的密钥和 IV。传输密钥和 IV 后,会话的其余部分将使用私钥加密。公钥算法可用于创建数字签名以验证数据发送方的标识

    .NET Framework 提供以下实现公钥加密算法的类:

    DSACryptoServiceProvider

    RSACryptoServiceProvider

    DSACryptoServiceProvider 类(数字签名算法 (DSA))

    数字签名验证另一个实体的标识并保护数据的完整性。例如,若要使用公钥系统对消息进行数字签名,发送方先向该消息应用哈希函数以创建消息摘要。然后,发送方使用发送方的私钥加密消息摘要以创建发送方的个人签名,因为此私钥唯一标识该发送方。在收到消息和签名后,接收方使用发送方的公钥解密该签名,以恢复消息摘要,并使用发送方所用的同一哈希算法对该消息进行哈希运算。如果接收方计算的消息摘要与从发送方接收的消息摘要完全匹配,则接收方可以确定该消息来自发送方。请注意,因为发送方的公钥是公共知识,所以任何人都可以验证签名。

    using System;

    using System.Security.Cryptography;

    class DSACSPSample

    {

        static void Main()

        {

            try

            {

                //Create a new instance of DSACryptoServiceProvider to generate

                //a new key pair.

                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //The hash value to sign.

                byte[] HashValue = {59,4,248,102,77,97,142,201,210,12,224,93,25,41,100,197,213,134,130,135};               

                //The value to hold the signed value.

                byte[] SignedHashValue = DSASignHash(HashValue, DSA.ExportParameters(true), "SHA1");

                //Verify the hash and display the results.

                if(DSAVerifyHash(HashValue, SignedHashValue, DSA.ExportParameters(false), "SHA1"))

                {

                    Console.WriteLine("The hash value was verified.");

                }

                else

                {

                    Console.WriteLine("The hash value was not verified.");

                }

            }

            catch(ArgumentNullException e)

            {

                Console.WriteLine(e.Message);

            }

        }

        public static byte[] DSASignHash(byte[] HashToSign, DSAParameters DSAKeyInfo, string HashAlg)

        {

            try

            {

                //Create a new instance of DSACryptoServiceProvider.

                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //Import the key information.  

                DSA.ImportParameters(DSAKeyInfo);

                //Create an DSASignatureFormatter object and pass it the

                //DSACryptoServiceProvider to transfer the private key.

                DSASignatureFormatter DSAFormatter = new DSASignatureFormatter(DSA);

                //Set the hash algorithm to the passed value.

                DSAFormatter.SetHashAlgorithm(HashAlg);

                //Create a signature for HashValue and return it.

                return DSAFormatter.CreateSignature(HashToSign);

            }

            catch(CryptographicException e)

            {

                Console.WriteLine(e.Message);

                return null;

            }

        }

        public static bool DSAVerifyHash(byte[] HashValue, byte[] SignedHashValue, DSAParameters DSAKeyInfo, string HashAlg)

        {

            try

            {

                //Create a new instance of DSACryptoServiceProvider.

                DSACryptoServiceProvider DSA = new DSACryptoServiceProvider();

                //Import the key information.

                DSA.ImportParameters(DSAKeyInfo);

                //Create an DSASignatureDeformatter object and pass it the

                //DSACryptoServiceProvider to transfer the private key.

                DSASignatureDeformatter DSADeformatter = new DSASignatureDeformatter(DSA);               

                //Set the hash algorithm to the passed value.

                DSADeformatter.SetHashAlgorithm(HashAlg);

                //Verify signature and return the result.

                return DSADeformatter.VerifySignature(HashValue, SignedHashValue);

            }

            catch(CryptographicException e)

            {

                Console.WriteLine(e.Message);

                return false;

            }

        }

    }

    RSACryptoServiceProvider 类

    using System;

    using System.Security.Cryptography;

    using System.Text;

    class RSACSPSample

    {

        static void Main()

        {

            try

            {

                //Create a UnicodeEncoder to convert between byte array and string.

                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                //Create byte arrays to hold original, encrypted, and decrypted data.

                byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");

                byte[] encryptedData;

                byte[] decryptedData;           

                //Create a new instance of RSACryptoServiceProvider to generate

                //public and private key data.

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Pass the data to ENCRYPT, the public key information

                //(using RSACryptoServiceProvider.ExportParameters(false),

                //and a boolean flag specifying no OAEP padding.

                encryptedData = RSAEncrypt(dataToEncrypt,RSA.ExportParameters(false), false);

                //Pass the data to DECRYPT, the private key information

                //(using RSACryptoServiceProvider.ExportParameters(true),

                //and a boolean flag specifying no OAEP padding.

                decryptedData = RSADecrypt(encryptedData,RSA.ExportParameters(true), false);

                //Display the decrypted plaintext to the console.

                Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));

            }

            catch(ArgumentNullException)

            {

                //Catch this exception in case the encryption did

                //not succeed.

                Console.WriteLine("Encryption failed.");

            }

        }

        static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)

        {

            try

            {   

                //Create a new instance of RSACryptoServiceProvider.

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Import the RSA Key information. This only needs

                //toinclude the public key information.

                RSA.ImportParameters(RSAKeyInfo);

                //Encrypt the passed byte array and specify OAEP padding. 

                //OAEP padding is only available on Microsoft Windows XP or

                //later. 

                return RSA.Encrypt(DataToEncrypt, DoOAEPPadding);

            }

            //Catch and display a CryptographicException 

            //to the console.

            catch(CryptographicException e)

            {

                Console.WriteLine(e.Message);

                return null;

            }

        }

        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo,bool DoOAEPPadding)

        {

            try

            {

                //Create a new instance of RSACryptoServiceProvider.

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

                //Import the RSA Key information. This needs

                //to include the private key information.

                RSA.ImportParameters(RSAKeyInfo);

                //Decrypt the passed byte array and specify OAEP padding. 

                //OAEP padding is only available on Microsoft Windows XP or

                //later. 

                return RSA.Decrypt(DataToDecrypt, DoOAEPPadding);

            }

            //Catch and display a CryptographicException 

            //to the console.

            catch(CryptographicException e)

            {

                Console.WriteLine(e.ToString());

                return null;

            }

        }

    }

    try

    {

        //Create a new RSACryptoServiceProvider object.

        RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();

        //Export the key information to an RSAParameters object.

        //Pass false to export the public key information or pass

        //true to export public and private key information.

        RSAParameters RSAParams = RSA.ExportParameters(false);

    }

    catch(CryptographicException e)

    {

        //Catch this exception in case the encryption did

        //not succeed.

        Console.WriteLine(e.Message);

    }

    哈希值

    哈希算法将任意长度的二进制值映射为固定长度的较小二进制值,这个小的二进制值称为哈希值, 消息身份验证代码 (MAC) 哈希函数通常与数字签名一起用于对数据进行签名,而消息检测代码 (MDC) 哈希函数则用于数据完整性。

    .NET Framework 提供以下实现数字签名算法的类:

    HMACSHA1

    MACTripleDES

    MD5CryptoServiceProvider

    SHA1Managed

    SHA256Managed

    SHA384Managed

    SHA512Managed

    HMACSHA1 类(使用 SHA1 哈希函数计算基于哈希值的消息验证代码 (HMAC))

    在发送方和接收方共享机密密钥的前提下,HMAC 可用于确定通过不安全信道发送的消息是否已被篡改。发送方计算原始数据的 HMAC,然后将原始数据和 HMAC 作为单个消息发送。接收方重新计算接收到的消息的 HMAC,检查计算所得的 HMAC 是否与传送的 HMAC 匹配。

    数据或 HMAC 的任何更改都将产生不匹配,因为更改消息和重新产生正确的 HMAC 需要知道机密密钥。因此,如果代码匹配,则消息通过了身份验证。

    HMACSHA1 接受任何大小的密钥,并产生长度为 20 字节的哈希序列。

    示例使用 SHA1 哈希算法计算 data 的 HMAC,然后将其存储在 result 中。该示例假定存在预定义的常数 DATA_SIZE 和 KEY_SIZE。

    byte[] key = new byte[KEY_SIZE];

    byte[] data = new byte[DATA_SIZE];

    HMACSHA1 hmac = new HMACSHA1(key);

    CryptoStream cs = new CryptoStream(Stream.Null, hmac, CryptoStreamMode.Write);

    cs.Write(data, 0, data.Length);

    cs.Close();

    byte[] result = hmac.Hash;

    MACTripleDES 类

    使用 TripleDES 计算输入数据 CryptoStream 的消息验证代码 (MAC)。

    在发送方和接收方共享机密密钥的前提下,MAC 可用于确定通过不安全信道发送的消息是否已被篡改。发送方计算原始数据的 MAC,然后将 MAC 和原始数据作为单个消息发送。接收方重新计算接收到的消息的 MAC,检查计算所得的 MAC 是否与传送的 MAC 匹配。

    数据或 MAC 的任何更改都将产生不匹配,因为更改消息和重新产生正确的 MAC 需要知道机密密钥。因此,如果代码匹配,则消息通过了身份验证。

    MACTripleDES 使用长度为 8、16 或 24 字节的密钥,并产生长度为 8 字节的哈希序列。

    示例使用 TripleDES 哈希算法计算 data 的 MAC,并将其存储在 result 中。此示例假定存在一个预定义的常数 DATA_SIZE。

    byte[] data = new byte[DATA_SIZE];

    byte[] key = new byte[24];

    MACTripleDES mac3des = new MACTripleDES(key);

    byte[] result = mac3des.ComputeHash(data);

    MD5CryptoServiceProvider 类

    使用加密服务提供程序 (CSP) 提供的实现计算输入数据的 MD5 哈希值。

    示例是计算并返回 data 的 MD5 哈希值的方法。

    byte[] MD5hash (byte[] data)

     {

        // This is one implementation of the abstract class MD5.

        MD5 md5 = new MD5CryptoServiceProvider();

        byte[] result = md5.ComputeHash(data);

        return result;

     }

    SHA1Managed 类

    使用托管库计算输入数据的 SHA1 哈希值。

    哈希值用作表示大量数据的固定大小的唯一值。两组数据的哈希值仅在相应数据也匹配时才应当匹配。数据的少量更改会在哈希值中产生不可预知的大量更改。

    这是 SHA1 的纯托管实现,不包装 CAPI。

    SHA1Managed 算法的哈希值大小为 160 位。

    示例计算 data 的 SHA1Managed 哈希值,并将它存储在 result 中。此示例假定存在一个预定义的常数 DATA_SIZE。

    byte[] data = new byte[DATA_SIZE];

    byte[] result;

    SHA1 shaM = new SHA1Managed();

    result = shaM.ComputeHash(data);

    SHA256Managed 类

    SHA256Managed 算法的哈希值大小为 256 位。

    byte[] data = new byte[DATA_SIZE];

    byte[] result;

    SHA256 shaM = new SHA256Managed();

    result = shaM.ComputeHash(data);

    SHA384Managed 类

    SHA384Managed 算法的哈希值大小为 384 位。

    byte[] data = new byte[DATA_SIZE];

    byte[] result;

    SHA384 shaM = new SHA384Managed();

    result = shaM.ComputeHash(data);

    SHA512Managed 类

    SHA512Managed 算法的哈希值大小为 512 位

    byte[] data = new byte[DATA_SIZE];

    byte[] result;

    SHA512 shaM = new SHA512Managed();

    result = shaM.ComputeHash(data);

     

  • 相关阅读:
    利用pyautogui自动化领取dnf的在线养竹活动的竹子
    idea2019.3版本的安装
    二叉树文本分析
    表达式树的创建
    24点游戏
    二叉树
    队列操作
    HuffmanTree
    两数之和
    面向对象Python
  • 原文地址:https://www.cnblogs.com/ahuang1118/p/172596.html
Copyright © 2020-2023  润新知