溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

ASP.NET中加密和解密怎么實(shí)現(xiàn)

發(fā)布時(shí)間:2022-08-01 09:27:34 來源:億速云 閱讀:94 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹“ASP.NET中加密和解密怎么實(shí)現(xiàn)”,在日常操作中,相信很多人在ASP.NET中加密和解密怎么實(shí)現(xiàn)問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”ASP.NET中加密和解密怎么實(shí)現(xiàn)”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!

散列運(yùn)算

mscorlib.dll下的System.Security.Cryptography下:

  • 抽象類HashAlgorithm

    • SHA256CryptoServiceProvider

    • SHA256Managed

    • SHA1CryptoServiceProvider密封類:調(diào)用Windows Crypto API

    • SHA1Managed普通類:用托管代碼寫的

    • MD5CryptoServiceProvider

    • 抽象類MD5

    • SHA1

    • SHA256

    • SHA384

    • SHA512

對字節(jié)數(shù)組或流散列運(yùn)算

    class Program 
    { 
        static void Main(string[] args) 
        { 
            string str = "Hello World"; 
            HashAlgorithm hashAlgorithm = HashAlgorithm.Create(HashAlgorithmType.SHA1); 
            byte[] data = Encoding.Default.GetBytes(str); 
            byte[] digest = hashAlgorithm.ComputeHash(data); 
            foreach (byte b in digest) 
            { 
                Console.Write("{0:X}",b); 
            } 
            Console.ReadKey(); 
        } 
    }
 
    public class HashAlgorithmType 
    { 
        public const string SHA1 = "SHA1"; 
        public const string SHA256 = "SHA256"; 
        public const string SHA384 = "SHA384"; 
        public const string SHA512 = "SHA512"; 
        public const string MD5 = "MD5"; 
    }

密匙散列運(yùn)算

string key = "secret key"; 
byte[] data = Encoding.Default.GetBytes(key); 
KeyedHashAlgorithm kha = new HMACSHA1(); 
byte[] digest = kha.ComputeHash(data); 
foreach (byte b in digest) 
{ 
    Console.Write("{0:x}",b); 
}

對稱加密和解密

  • SymmetricAlgorithm

    • RC2CryptoServiceProvider

    • RijindaelManaged

    • TripleDESCryptoServiceProvider

    • DESCryptoServiceProvider

    • DES

    • TripleDES

    • Rijndael

    • RC2

IV:Initialization vector初始化向量:

  • 為了解決加密字符串加密后仍然有重復(fù)部分,引入IV,加密字符串即使有重復(fù),也會被打亂。

  • IV值可以隨意指定,但長度固定,通常為64位byte類型

  • 密匙長度也是固定的,通常為128位或196位byte類型

使用Encoding類將字符串轉(zhuǎn)換為byte[]:

  • 如果使用UTF8,會變長編碼

加密解密方法:

  • 加密方法:CreateEncryptor(),返回ICryptoTransform接口類型

  • 解密方法:CreateDecryptor(),返回ICrtyptoTransform接口類型

明文流和加密流的轉(zhuǎn)換:

    public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            #region 對稱加密和解密
 
            string key = "secret key"; 
            string str = "Hello World";
 
            //加密 
            string encryptedText = SymmetricCryptoHelper.Encrypt(str, key); 
            Console.WriteLine(encryptedText);
 
            //解密 
            string clearText = SymmetricCryptoHelper.Decrypt(encryptedText, key); 
            Console.WriteLine(clearText);
 
            Console.ReadKey();
 
            #endregion 
        } 
    }
 
    //對稱加密幫助類 
    public class SymmetricCryptoHelper 
    { 
        private ICryptoTransform encryptor;  //加密器對象 
        private ICryptoTransform decryptor; //解密器對象 
        private const int BufferSize = 1024;
 
        public SymmetricCryptoHelper(string algorithmName, byte[] key) 
        { 
            SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName); 
            provider.Key = key; 
            provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 
            encryptor = provider.CreateEncryptor(); 
            decryptor = provider.CreateDecryptor(); 
        }
 
        public SymmetricCryptoHelper(byte[] key) : this("TripleDES", key){}
 
        //加密算法 
        public string Encrypt(string clearText) 
        { 
            //創(chuàng)建明文流 
            byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText); 
            //byte[] clearBuffer = Encoding.Default.GetBytes(clearText); 
            MemoryStream clearStream = new MemoryStream(clearBuffer);
 
            //創(chuàng)建空的密文流 
            MemoryStream encryptedStream = new MemoryStream();
 
            //明文流和密文流轉(zhuǎn)換流,準(zhǔn)備寫到密文流中 
            CryptoStream cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write); 
           
            int bytesRead = 0; 
            byte[] buffer = new byte[BufferSize]; 
            do 
            { 
                //讀取明文流到buffer中 
                bytesRead = clearStream.Read(buffer, 0, BufferSize); 
                //通過CryptoStream將buffer中的明文流字節(jié)數(shù)組寫到明文流中 
                cryptoStream.Write(buffer, 0, bytesRead); 
            } while (bytesRead > 0);
 
            cryptoStream.FlushFinalBlock();
 
            //獲取加密后的字節(jié)數(shù)組 
            buffer = encryptedStream.ToArray();
 
            //將加密后的字節(jié)數(shù)組轉(zhuǎn)換成字符串 
            string encryptedText = Convert.ToBase64String(buffer); 
            return encryptedText; 
        }
 
        //解密算法 
        public string Decrypt(string encryptedText) 
        { 
            //把加密字符串轉(zhuǎn)換為加密字節(jié)數(shù)組 
            byte[] encryptedBuffer = Convert.FromBase64String(encryptedText); 
            //創(chuàng)建密文流 
            Stream encryptedStream = new MemoryStream(encryptedBuffer);
 
            //創(chuàng)建空的明文流 
            MemoryStream clearStream = new MemoryStream();
 
            //創(chuàng)建明文流和密文流的轉(zhuǎn)化流,讀取密文流 
            CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);
 
            int bytesRead = 0; 
            byte[] buffer = new byte[BufferSize];
 
            do 
            { 
                //通過CryptoStream讀取密文流到Buffer 
                bytesRead = cryptoStream.Read(buffer, 0, BufferSize); 
                //把Buffer中的密文流寫到明文流中 
                clearStream.Write(buffer, 0, bytesRead); 
            } while (bytesRead > 0);
 
            //將明文流轉(zhuǎn)換成字節(jié)數(shù)組 
            buffer = clearStream.GetBuffer();
 
            string clearText = Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length); 
            //string clearText = Encoding.Default.GetString(buffer, 0, (int)clearStream.Length); 
            return clearText; 
        }
 
        //密匙加密 
        public static string Encrypt(string clearText, string key) 
        { 
            byte[] keyData = new byte[16]; //TripleDES密匙固定長度為16個(gè)字節(jié)
 
            //把密匙字符串轉(zhuǎn)換成字節(jié)數(shù)組 
            byte[] sourceData = Encoding.Default.GetBytes(key); 
            int copyBytes = 16; 
            if (sourceData.Length < 16) 
            { 
                copyBytes = sourceData.Length; 
            }
 
            //把密匙數(shù)組復(fù)制到keyData字節(jié)數(shù)組中 
            Array.Copy(sourceData,keyData,copyBytes);
 
            SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData); 
            return helper.Encrypt(clearText); 
        }
 
        //密匙解密 
        public static string Decrypt(string encryptedText, string key) 
        { 
            byte[] keyData = new byte[16]; 
            byte[] sourceData = Encoding.Default.GetBytes(key); 
            int copyBytes = 16; 
            if (sourceData.Length < 16) 
            { 
                copyBytes = sourceData.Length; 
            } 
            Array.Copy(sourceData,keyData,copyBytes);
 
            SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData); 
            return helper.Decrypt(encryptedText); 
        } 
    }

ASP.NET中加密和解密怎么實(shí)現(xiàn)

非對稱加密

  • AsymmetricAlgorithm

    • DSACryptoServiceProvider:只能進(jìn)行認(rèn)證模式,即數(shù)字簽名

    • RSACryptoServiceProvider

    • RSA

    • DSA

對稱加密中的密匙:

密匙為由開發(fā)者設(shè)定的字符串

非對稱加密中的密匙:

  • 通常是自動生成,不同的算法有不同的密匙格式   

  • 在創(chuàng)建RSACryptoServiceProvider實(shí)例時(shí),會自動創(chuàng)建一個(gè)公/私密匙對。在實(shí)例上調(diào)用ToXmlString()方法獲得。

RSACryptoServiceProvider provider = new RSACryptoServiceProvider();
string publicPrivate = provider.ToXmlString(true);//獲得公/私匙對
//string publicOnly = provider.ToXmlString(false); //只獲得公匙
Console.Write(publicPrivate);
Console.ReadKey();

非對稱加密幫助類

    //非對稱加密幫助類 
    public class RSACryptoHelper 
    { 
        //加密 
        public static string Encrypt(string publicKeyXml, string plainText) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(publicKeyXml); //使用公匙初始化對象 
            byte[] plainData = Encoding.Default.GetBytes(plainText); 
            byte[] encryptedData = provider.Encrypt(plainData, true); 
            return Convert.ToBase64String(encryptedData); 
        }
 
        //解密 
        public static string Decrypt(string privateKeyXml, string encryptedText) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(privateKeyXml); 
            byte[] encryptedData = Convert.FromBase64String(encryptedText); 
            byte[] plainData = provider.Decrypt(encryptedData, true); 
            string plainText = Encoding.Default.GetString(plainData); 
            return plainText; 
        } 
    }

數(shù)字簽名

RSACryptoServiceProvider或DSACryptoServiceProvider
SignData()對摘要進(jìn)行簽名,并返回簽名后的摘要。
VerifyData()得出本地摘要,并解密傳遞進(jìn)來的原始摘要,對比返回bool類型結(jié)果。

數(shù)字簽名幫助類

    public class RSACryptoHelper 
    { 
        public static string SignData(string plainText, string privateKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(privateKeyXml);
 
            byte[] plainData = Encoding.Default.GetBytes(plainText); 
            //設(shè)置獲取摘要的算法 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            //獲取簽名過的摘要,是使用私匙加密過的摘要 
            byte[] signedDigest = provider.SignData(plainData, sha1); 
            return Convert.ToBase64String(signedDigest); 
        }
 
        public static bool VerifyData(string plainText, string signature, string publicKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(publicKeyXml);
 
            byte[] plainData = Encoding.Default.GetBytes(plainText); 
            byte[] signedDigest = Convert.FromBase64String(signature);
 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            bool isDataIntact = provider.VerifyData(plainData, sha1, signedDigest); 
            return isDataIntact; 
        }
 
        //使用SingnHash 
        public static string SignData2(string plainText, string privateKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(privateKeyXml); 
            byte[] plainData = Encoding.Default.GetBytes(plainText);
 
            //設(shè)置獲取摘要的算法 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            //獲得原始摘要 
            byte[] digestData = sha1.ComputeHash(plainData); 
            //對元素摘要進(jìn)行簽名 
            byte[] signedDigest = provider.SignHash(digestData, "SHA1"); 
            return Convert.ToBase64String(signedDigest); 
        }
 
        //使用VerifyHash 
        public static bool VerifyData2(string plainText, string signedDigest, string publicKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(publicKeyXml);
 
            byte[] plainData = Encoding.Default.GetBytes("SHA1"); 
            byte[] signedDigestData = Convert.FromBase64String(signedDigest);
 
            //獲得本地摘要 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            byte[] digest = sha1.ComputeHash(plainData);
 
            //解密簽名 
            bool isDataIntact = provider.VerifyHash(digest, "SHA1", signedDigestData); 
            return isDataIntact; 
        } 
    }

到此,關(guān)于“ASP.NET中加密和解密怎么實(shí)現(xiàn)”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI