加密演算法學習

你好呀嗯嗯發表於2024-08-11

三種演算法,呼叫如下:

class Program
    {
        static void Main(string[] args)
        {
            //MD5  一共32位,不能解密,且不可逆
            //字串相同,結果就一定相同 mds不能解密
            //針對字串進行MD5
            Console.WriteLine(MD5Encrypt.Encrypt("1"));
            //針對檔案進行MD5檢查
            Console.WriteLine(MD5Encrypt.AbstractFile(@"D:\C#高階學習\MyEncrypt\Example\Example\Program.cs"));

            //使用場景
            //密碼登入(防止看到明文)、急速秒傳(百度雲 計算檔案MD5)、git/svn(MD5比對)

            //Des 可逆對稱加密
            string desEn = DesEncrypt.Encrypt("guoxu");
            string desDe = DesEncrypt.Decrypt(desEn);

            //可逆非對稱加密
            KeyValuePair<string, string> encryptDecrypt = RasEncrypt.GetKeyPair();
            string rsaEnl = RasEncrypt.Encrypt("net",encryptDecrypt.Key);
            string rsaDel = RasEncrypt.Decrypt(rsaEnl, encryptDecrypt.Value);
        }
    }

1.MD5

class MD5Encrypt
	{
		public static string Encrypt(string source,int length = 32)
		{
			if (string.IsNullOrEmpty(source)) return string.Empty;
			HashAlgorithm provider = CryptoConfig.CreateFromName("MD5") as HashAlgorithm;
			byte[] bytes = Encoding.UTF8.GetBytes(source);
			byte[] hashValue = provider.ComputeHash(bytes);
			StringBuilder sb = new StringBuilder();
			switch (length)
			{
				case 16:
					for(int i = 4;i< 12; i++)
					{
						sb.Append(hashValue[i].ToString("x2"));
					}
					break;
				case 32:
					for (int i = 0; i < 16; i++)
					{
						sb.Append(hashValue[i].ToString("x2"));
					}
					break;
				default:
					for (int i = 0; i < hashValue.Length; i++)
					{
						sb.Append(hashValue[i].ToString("x2"));
					}
					break;
			}
			return sb.ToString();
		}

		public static string AbstractFile(string fileName)
		{
			using (FileStream file = new FileStream(fileName, FileMode.Open))
			{
				return AbstractFile(file);
			}
		}

		private static string AbstractFile(Stream stream)
		{
			MD5 md5 = new MD5CryptoServiceProvider();
			byte[] retVal = md5.ComputeHash(stream);
			StringBuilder sb = new StringBuilder();
			for(int i = 0; i < retVal.Length; i++)
			{
				sb.Append(retVal[i].ToString("x2"));
			}
			return sb.ToString();
		}
	}

 2.Des

class DesEncrypt
	{
		private static byte[] _rgbKey = ASCIIEncoding.ASCII.GetBytes(Constant.DesKey.Substring(0, 8));
		private static byte[] _rgbIV = ASCIIEncoding.ASCII.GetBytes(Constant.DesKey.Substring(0,8));
		
		public static string Encrypt(string plainText, string key = "12345678")
		{
			using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
			{
				byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
				des.Key = Encoding.UTF8.GetBytes(key);
				des.IV = Encoding.UTF8.GetBytes(key); // 使用相同的金鑰作為 IV

				using (MemoryStream ms = new MemoryStream())
				{
					using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
					{
						cs.Write(plainBytes, 0, plainBytes.Length);
						cs.FlushFinalBlock();
						return Convert.ToBase64String(ms.ToArray());
					}
				}
			}
		}

		public static string Decrypt(string cipherText, string key = "12345678")
		{
			using (DESCryptoServiceProvider des = new DESCryptoServiceProvider())
			{
				byte[] cipherBytes = Convert.FromBase64String(cipherText);
				des.Key = Encoding.UTF8.GetBytes(key);
				des.IV = Encoding.UTF8.GetBytes(key); // 使用相同的金鑰作為 IV

				using (MemoryStream ms = new MemoryStream())
				{
					using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write))
					{
						cs.Write(cipherBytes, 0, cipherBytes.Length);
						cs.FlushFinalBlock();
						return Encoding.UTF8.GetString(ms.ToArray());
					}
				}
			}
		}
	}

  3.RAS

class RasEncrypt
    {
        public static KeyValuePair<string,string> GetKeyPair()
        {
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            string publicKey = RSA.ToXmlString(false);
            string privateKey = RSA.ToXmlString(true);
            return new KeyValuePair<string, string>(publicKey, privateKey);
        }

        public static string Encrypt(string content, string encryptKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(encryptKey);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            byte[] DataToEncrypt = ByteConverter.GetBytes(content);
            byte[] resultBytes = rsa.Encrypt(DataToEncrypt, false);
            return Convert.ToBase64String(resultBytes);
        }

        public static string Decrypt(string content, string decryptKey)
        {
            byte[] dataToDecrypt = Convert.FromBase64String(content);
            RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
            RSA.FromXmlString(decryptKey);
            byte[] resultBytes = RSA.Decrypt(dataToDecrypt, false);
            UnicodeEncoding ByteConverter = new UnicodeEncoding();
            return ByteConverter.GetString(resultBytes);
        }
    }

相關文章