金币2878
积分9960
注册时间2016-12-2
最后登录2025-1-18
|
- //加密字符串
- //失败返回0
- public static string EncryptString(string plainText, string passPhrase)
- {
- try
- {
- byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
- byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
- PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
- byte[] keyBytes = password.GetBytes(keysize / 8);
- RijndaelManaged symmetricKey = new RijndaelManaged();
- symmetricKey.Mode = CipherMode.CBC;
- ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
- MemoryStream memoryStream = new MemoryStream();
- CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
- cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
- cryptoStream.FlushFinalBlock();
- byte[] cipherTextBytes = memoryStream.ToArray();
- memoryStream.Close();
- cryptoStream.Close();
- return Convert.ToBase64String(cipherTextBytes);
- }
- catch
- {
- return "0";
- }
- }
- //解密字符串
- //失败返回0
- public static string DecryptString(string cipherText, string passPhrase)
- {
- try
- {
- byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
- byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
- PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
- byte[] keyBytes = password.GetBytes(keysize / 8);
- RijndaelManaged symmetricKey = new RijndaelManaged();
- symmetricKey.Mode = CipherMode.CBC;
- ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
- MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
- CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
- byte[] plainTextBytes = new byte[cipherTextBytes.Length];
- int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
- memoryStream.Close();
- cryptoStream.Close();
- return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
- }
- catch
- {
- return "0";
- }
- }
- private const string initVector = "96lt1937md5.....";
- private const int keysize = 256;
复制代码
|
|