C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

自己做数字签名加密解密这就了,对这些东西有一点点懂,可能自己整理的有些错误。 
C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider 
DESCryptoServiceProvider 是用于对称加密 RSACryptoServiceProvider是用于非对称加密 
对称加密的意思:有一个密钥 相当于加密算法,加密用它来加密,解密也需要用到它。因为加密解密都是用同一个密钥所以叫对称加密。 对称加密有一个坏处只要拥有密钥的人都可以解密。 
非对称加密:就是有2个密钥,一个是公钥,一个是私钥,私钥是自己的,不能随便给人,公钥随便给,无所谓。一般是别人用你的公钥加密,然后把密文给你,你用你的私钥解密,这样一样加密和解密不是同一个密钥,所以叫非对称。 非对称的好处是假如没有私钥别人是无法解密的,就算加密的那个人他把数据加密了他也无法解密,加密者把密文和公钥随便给那个人都无法解密。 
数字签名:数字签名的意义就是这些数据与原文数据比对是否修改过,这个解释有点麻烦,当初我也搞了好久才理解!一般是用自己的私钥对数据进行签名,然后用公钥去验证这个数据是否修改过 
-
现在该说说DESCryptoServiceProvider 和RSACryptoServiceProvider 在C#中的具体怎么用: 
-
1、用RSACryptoServiceProvider 加密解密 
//加密解密用到的公钥与私钥 
RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider(); 
string privatekey=oRSA.ToXmlString(true);//私钥 
string publickey=oRSA.ToXmlString(false);//公钥 
//这两个密钥需要保存下来 
byte[] messagebytes = Encoding.UTF8.GetBytes("luo罗"); //需要加密的数据 
-
//公钥加密 
RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider(); 
oRSA1.FromXmlString(publickey); //加密要用到公钥所以导入公钥 
byte[] AOutput = oRSA1.Encrypt(messagebytes ,false); //AOutput 加密以后的数据 
-
//私钥解密 
RSACryptoServiceProvider oRSA2 = new RSACryptoServiceProvider(); 
oRSA2.FromXmlString(privatekey);           
byte[] AInput = oRSA2.Decrypt(AOutput, false); 
string reslut=Encoding.ASCII.GetString(AInput) 
2、用RSACryptoServiceProvider签名验签 
   byte[] messagebytes = Encoding.UTF8.GetBytes("luo罗"); 
           RSACryptoServiceProvider oRSA = new RSACryptoServiceProvider(); 
           string privatekey = oRSA.ToXmlString(true); 
           string publickey = oRSA.ToXmlString(false); 
           
            //私钥签名 
            RSACryptoServiceProvider oRSA3 = new RSACryptoServiceProvider(); 
            oRSA3.FromXmlString(privatekey); 
            byte[] AOutput = oRSA3.SignData(messagebytes, "SHA1"); 
            //公钥验证 
            RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider(); 
            oRSA4.FromXmlString(publickey); 
            bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", AOutput); 
3、用证书进行签名 
    因为一般证书的私钥是不可以导出的所以所以用第2种方法导入私钥的来进行签名行不通 
byte[] messagebytes = Encoding.UTF8.GetBytes("luo罗"); 
           string Path = @"D:\Certificate\1.P12"; 
           X509Certificate2 x509 = new X509Certificate2(Path, "12345678"); 
           SHA1 sha1 = new SHA1CryptoServiceProvider(); 
           byte[] hashbytes = sha1.ComputeHash(messagebytes); //对要签名的数据进行哈希 
           RSAPKCS1SignatureFormatter signe = new RSAPKCS1SignatureFormatter(); 
           signe.SetKey(x509.PrivateKey); //设置签名用到的私钥 
           signe.SetHashAlgorithm("SHA1"); //设置签名算法 
           byte[] reslut = signe.CreateSignature(hashbytes); 
验签:与第2方法相同 
           RSACryptoServiceProvider oRSA4 = new RSACryptoServiceProvider(); 
           oRSA4.FromXmlString(x509.PublicKey.Key.ToXmlString(false)); 
           bool bVerify = oRSA4.VerifyData(messagebytes, "SHA1", reslut); 
4、用证书加密解密 
   string Path = @"D:\Certificate\1.P12"; 
            X509Certificate2 x509 = new X509Certificate2(Path, "12345678"); 
            byte[] data = System.Text.Encoding.UTF8.GetBytes("cheshi罗"); 
-
            //证书公钥加密 
            RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider(); 
     
            oRSA1.FromXmlString(x509.PublicKey.Key.ToXmlString(false)); 
-
            byte[] AOutput = oRSA1.Encrypt(data, false); 
-
            //证书私钥解密 
            RSACryptoServiceProvider rsa2 = (RSACryptoServiceProvider)x509.PrivateKey; 
            byte[] plainbytes = rsa2.Decrypt(AOutput, false); 
            string reslut = Encoding.UTF8.GetString(plainbytes); 
5用证书对文件加密解密,因为文件可能特别大 所以需要用流和buffer的方式来,鄙视把文件全部读到byte[]里进行加密的人,假如文件5G,那全部读到byte[]里崩溃掉 
   private void Form1_Load(object sender, EventArgs e) 
        { 
            x509=new X509Certificate2(Path, "12345678"); 
            RSACryptoServiceProvider oRSA1 = new RSACryptoServiceProvider(); 
            Encrypt(); 
            Decrypt();           
        } 
        private void Decrypt() 
        { 
            string FilePath = "2.txt"; 
            string OutFile = "3.txt"; 
            System.IO.FileStream picfs = new System.IO.FileStream(FilePath, System.IO.FileMode.Open); 
            System.IO.FileStream fs = new System.IO.FileStream(OutFile, System.IO.FileMode.OpenOrCreate); 
            oRSA1 = (RSACryptoServiceProvider)x509.PrivateKey; 
            int blocksize = oRSA1.KeySize/8; 
-
            byte[] buffer, buffer1, encryblock; 
            bool Closed = true; 
            while (Closed) 
            { 
                buffer = null; 
                buffer = new byte[blocksize]; 
                int k = picfs.Read(buffer, 0, buffer.Length); 
                if (k > 0) 
                { 
                    if (blocksize == k) 
                    { 
                        encryblock = oRSA1.Decrypt(buffer, false); 
                        fs.Write(encryblock, 0, encryblock.Length); 
                    } 
                    else 
                    { 
                        buffer1 = new byte[k]; 
                        for (int i = 0; i < k; i++) 
                        { 
                            buffer1[i] = buffer[i]; 
                        } 
                        encryblock = oRSA1.Decrypt(buffer1, false); 
                        fs.Write(encryblock, 0, encryblock.Length); 
                    } 
                } 
                else 
                { 
                    picfs.Close(); 
                    fs.Close(); 
                    Closed = false; 
                } 
            } 
-
        } 
        private void Encrypt() 
        { 
            string FilePath = "1.txt"; 
            string OutFile = "2.txt"; 
            //证书公钥加密 
-
            oRSA1.FromXmlString(x509.PublicKey.Key.ToXmlString(false)); 
            System.IO.FileStream picfs = new System.IO.FileStream(FilePath, System.IO.FileMode.Open); 
            System.IO.FileStream fs = new System.IO.FileStream(OutFile, System.IO.FileMode.OpenOrCreate); 
            int blocksize = 0; 
            if (oRSA1.KeySize == 1024) 
            { 
                blocksize = 16; 
            } 
            else 
            { 
                blocksize = 8; 
            } 
            byte[] buffer, buffer1, encryblock; 
            bool Closed = true; 
            while (Closed) 
            { 
                buffer = null; 
                buffer = new byte[blocksize]; 
                int k = picfs.Read(buffer, 0, buffer.Length); 
                if (k > 0) 
                { 
                    if (blocksize == k) 
                    { 
                        encryblock = oRSA1.Encrypt(buffer, false); 
                        fs.Write(encryblock, 0, encryblock.Length); 
                    } 
                    else 
                    { 
                        buffer1 = new byte[k]; 
                        for (int i = 0; i < k; i++) 
                        { 
                            buffer1[i] = buffer[i]; 
                        } 
                        encryblock = oRSA1.Encrypt(buffer1, false); 
                        fs.Write(encryblock, 0, encryblock.Length); 
                    } 
                } 
                else 
                { 
                    picfs.Close(); 
                    fs.Close(); 
                    Closed = false; 
                } 
            } 
        } 
6用证书对文件进行签名验签,因为文件可能特别大 所以需要用流和buffer的方式来 
private void Form1_Load(object sender, EventArgs e)
        {
            x509 = new X509Certificate2(Path, "12345678");
             SignFile("1.txt", "11.txt");

             VerifyFile("1.txt", "11.txt");
        }
        private bool VerifyFile(string FileName, string SignedFileName)
        {

            bool reslut = true;

            System.IO.StreamReader objread = new System.IO.StreamReader(FileName);
            System.IO.StreamReader objreadSigned = new System.IO.StreamReader(SignedFileName);

            RSACryptoServiceProvider VeryRsa = new RSACryptoServiceProvider();
            VeryRsa.FromXmlString(x509.PublicKey.Key.ToXmlString(false));

            int Inblocksize = 0;
            int Signedblocksize = 0;
            if (VeryRsa.KeySize == 1024)
            {
                Inblocksize = 16;
            }
            else
            {
                Inblocksize = 8;
            }
            Signedblocksize = VeryRsa.KeySize / 8;

            bool Closed = true;
            byte[] Buffer; //原文缓存区
            byte[] InBuffer;//原文缓存区
            byte[] Buffer1;//签名文件缓存区
            while (Closed)
            {
                Buffer = null;
                Buffer = new byte[Inblocksize];
                int k = objread.BaseStream.Read(Buffer, 0, Buffer.Length);
                if (k > 0)
                {
                    if (Inblocksize == k) //读出来的长度和缓存区一样大
                    {
                        Buffer1 = new byte[Signedblocksize];
                        objreadSigned.BaseStream.Read(Buffer1, 0, Buffer1.Length);
                        reslut = VeryRsa.VerifyData(Buffer,"SHA1",Buffer1);
                        if (!reslut)
                        {
                            Closed = false;
                        }
                    }
                    else
                    { //意思是Buffer没满,只有k个字节,k字节后面全是空所以不需要验签
                        InBuffer = new byte[k];
                        for (int i = 0; i < k; i++)
                        {
                            InBuffer[i] = Buffer[i];
                        }
                        Buffer1 = new byte[Signedblocksize];
                        objreadSigned.BaseStream.Read(Buffer1, 0, Buffer1.Length);
                        reslut = VeryRsa.VerifyData(InBuffer, "SHA1", Buffer1);
                        if (!reslut)
                        {
                            Closed = false;
                        }
                    }
                }
                else
                {
                    //这里的意思是原文已经读完毕了,并且已经和签名文件对应验签成功,那么
                    //签名文件也必须读完毕了。
                    if (objreadSigned.BaseStream.Position!= objreadSigned.BaseStream.Length)
                    {
                        reslut = false;
                    }
                    objreadSigned.Close();
                    objread.Close();
                    Closed = false;
                }
            }
            return reslut;


        }
        private void SignFile(string InFileName,string OutFileName)
        {
            RSACryptoServiceProvider SignRsa = (RSACryptoServiceProvider)x509.PrivateKey;

            System.IO.StreamReader objread = new System.IO.StreamReader(InFileName);
            System.IO.StreamWriter objwrite = new System.IO.StreamWriter(OutFileName, false);

            int blocksize = 0;
            if (SignRsa.KeySize == 1024)
            {
                blocksize = 16;
            }
            else
            {
                blocksize = 8;
            }

            bool Closed = true;
            byte[] Buffer = new byte[blocksize];
            byte[] buffer1, SignBytes;
            while (Closed)
            {
                int k = objread.BaseStream.Read(Buffer, 0, Buffer.Length);
                if (k > 0)
                {
                    if (k == blocksize)
                    {
                        SignBytes = SignRsa.SignData(Buffer, "SHA1");
                        objwrite.BaseStream.Write(SignBytes, 0, SignBytes.Length);
                    }
                    else
                    {
                        buffer1 = new byte[k];
                        for (int i = 0; i < k; i++)
                        {
                            buffer1[i] = Buffer[i];
                        }
                        SignBytes = SignRsa.SignData(buffer1, "SHA1");
                        objwrite.BaseStream.Write(SignBytes, 0, SignBytes.Length);
                    }
                }
                else
                {
                    Closed = false;
                    objread.Close();
                    objwrite.Close();
                }
            }


        }
-
7、用DESCryptoServiceProvider 进行对称加密 
byte[] messagebytes = Encoding.UTF8.GetBytes("LUO罗"); 
            //需要用的对称密钥 
            DESCryptoServiceProvider Des = new DESCryptoServiceProvider(); 
            byte[] key = Des.Key; 
            //加密 
            DESCryptoServiceProvider tdesProvider = new DESCryptoServiceProvider(); 
            tdesProvider.Key = key; 
            tdesProvider.Mode = CipherMode.ECB; 
            byte[] encrypted = tdesProvider.CreateEncryptor().TransformFinalBlock(messagebytes, 0, messagebytes.Length); 
            //解密 
            DESCryptoServiceProvider tdesProvider2 = new DESCryptoServiceProvider(); 
            tdesProvider.Key = key1; 
            tdesProvider.Mode = CipherMode.ECB; 
            byte[] outputdata = tdesProvider.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length); 
            string reslut = Encoding.UTF8.GetString(outputdata);
7用DESCryptoServiceProvider 加解密 流
CryptoStream csDecrypt = new CryptoStream(Stream, Des.CreateEncryptor(), CryptoStreamMode.Write);
          CryptoStream csDecrypt = new CryptoStream(Stream, Des.CreateDecryptor(), CryptoStreamMode.Write);