Я пытаюсь зашифровать и расшифровать текст, используя TripleDESCryptoServiceProvider
.
Мое требование - одинаковый открытый текст, зашифрованный текст не должен быть одинаковым, для этого я создал разные вектор каждый раз.
Это код для шифрования и расшифровки текста.
public string EncryptString(string PlainText)
{
GenerateIV();
GenerateKey();
if (PlainText == null || PlainText.Length <= 0)
{
throw new ArgumentNullException("Invalid Plaintext.");
}
if (Key == null || Key.Length <= 0)
{
throw new ArgumentNullException("Key Can Not Be Null Or Empty.");
}
if (IV == null || IV.Length <= 0)
{
throw new ArgumentNullException("Vector Can Not Be Null Or Empty.");
}
byte[] encryptedText;
using (TripleDESCryptoServiceProvider tdsObj = new TripleDESCryptoServiceProvider())
{
if (!isKeyStrengthChecked)
{
bool isWeekKey = TripleDESCryptoServiceProvider.IsWeakKey(Key);
if (isWeekKey)
{
throw new Exception("Weak Key.");
}
else
{
isKeyStrengthChecked = true;
}
}
tdsObj.Key = Key;
tdsObj.IV = IV;
tdsObj.Mode = CipherMode.CBC;
tdsObj.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = tdsObj.CreateEncryptor(tdsObj.Key, tdsObj.IV);
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter srEncrypt = new StreamWriter(csEncrypt))
{
srEncrypt.Write(PlainText);
}
encryptedText = msEncrypt.ToArray();
}
}
}
return Convert.ToBase64String(encryptedText);
}
public string DecryptString(string cipherText)
{
GenerateIV();
GenerateKey();
if (cipherText == null || cipherText.Length <= 0)
{
throw new ArgumentNullException("Invalid CipherText.");
}
if (Key == null || Key.Length <= 0)
{
throw new ArgumentNullException("Key Can Not Be Null Or Empty.");
}
if (IV == null || IV.Length <= 0)
{
throw new ArgumentNullException("Vector Can Not Be Null Or Empty.");
}
byte[] cipherBytes = Convert.FromBase64String(cipherText);
string PlainText = null;
using (TripleDESCryptoServiceProvider tdsDecrypt = new TripleDESCryptoServiceProvider())
{
tdsDecrypt.Key = Key;
tdsDecrypt.IV = IV;
tdsDecrypt.Mode = CipherMode.CBC;
tdsDecrypt.Padding = PaddingMode.PKCS7;
ICryptoTransform decrytor = tdsDecrypt.CreateDecryptor(Key, IV);
using (MemoryStream msDecrypt = new MemoryStream(cipherBytes))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decrytor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
PlainText = srDecrypt.ReadToEnd();
}
}
}
}
return PlainText;
}
Мой полный код находится здесь .Net Fiddle
Но когда я расшифровываю текст, я не получаю такой же простой текст. Что не так я сделал.