Статус: Участник
Группы: Участники
Зарегистрирован: 07.04.2013(UTC) Сообщений: 16  Сказал «Спасибо»: 2 раз
|
Нужно зашифровать строку в строку и расшифровать ее же. В итоге получаем исходную строку. На тестовом примере actual = "Иван Васильевич Толку" - три последние буквы пропадают. На разных длинах строк пропадает разное количество символов, причем непропорционально длине строки. Иногда появляются иероглифы. Не представляю, в чем может быть косяк. Подскажите пожалуйста, может кто-нибудь уже сталкивался с подобным класс : Код:
////////////////////////////////////////////////
//класс
public class CryptoManager
{
// Создаем объект шифрования со сгенерированным ключом и синхропосылкой.
Gost28147 gost;
public CryptoManager()
{
gost = Gost28147.Create();
}
public string DecryptString(string data)
{
return Encoding.UTF8.GetString(decryptData(Convert.FromBase64String(data)));
}
public String EncryptString(string text)
{
return Convert.ToBase64String(encryptData(Encoding.UTF8.GetBytes(text)));
}
//шифрование массива байт
public byte[] encryptData(byte[] data)
{
int length = data.Length;
try
{
// Открываем или создаем файл.
MemoryStream mStream = new MemoryStream();
// Создаем CryptoStream, используя FileStream,
// переданный ключ и синхропосылку (IV).
CryptoStream cStream = new CryptoStream(mStream,
gost.CreateEncryptor(),
CryptoStreamMode.Write);
// Пишем данные в поток, зашифровая их.
cStream.Write(data, 0, length);
// Get an array of bytes from the
// MemoryStream that holds the
// encrypted data.
byte[] ret = mStream.ToArray();
//cStream.FlushFinalBlock();
// Close the streams.
cStream.Close();
mStream.Close();
// Return the encrypted buffer.
return ret;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
}
return null;
}
//разшифрование массива байтов
public byte[] decryptData(byte[] data)
{
try
{
// Create buffer to hold the decrypted data.
byte[] result = new byte[data.Length];
// Открываем или создаем файл.
MemoryStream mStream = new MemoryStream(data);
// Создаем CryptoStream, используя FileStream,
// переданный ключ и синхропосылку (IV).
CryptoStream cStream = new CryptoStream(mStream,
gost.CreateDecryptor(),
CryptoStreamMode.Read);
// Read the decrypted data out of the crypto stream
// and place it into the temporary buffer.
cStream.Read(result, 0, data.Length);
return result;
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
}
return null;
}
}
Тест: Код:
/////////////////////////////////////////
//тест
public void EncryptStringTest()
{
CryptoManager target = new CryptoManager();
string text = "Иван Васильевич Толкунов";
string expected = "Иван Васильевич Толкунов";
string actual;
actual = target.EncryptString(text);
actual = target.DecryptString(actual);
Assert.AreEqual(expected, actual);
//Assert.Inconclusive("Verify the correctness of this test method.");
}
|
|
|
|
Статус: Участник
Группы: Участники
Зарегистрирован: 07.04.2013(UTC) Сообщений: 16  Сказал «Спасибо»: 2 раз
|
со вставкой кода на форуме какой-то глюк Вот начало класса Код:
public class CryptoManager
{
// Создаем объект шифрования со сгенерированным ключом и синхропосылкой.
Gost28147 gost;
public CryptoManager()
{
gost = Gost28147.Create();
}
public string DecryptString(string data)
{
return Encoding.UTF8.GetString(decryptData(Convert.FromBase64String(data)));
}
public String EncryptString(string text)
{
return Convert.ToBase64String(encryptData(Encoding.UTF8.GetBytes(text)));
}
//шифрование массива байт
|
|
|
|
Быстрый переход
Вы не можете создавать новые темы в этом форуме.
Вы не можете отвечать в этом форуме.
Вы не можете удалять Ваши сообщения в этом форуме.
Вы не можете редактировать Ваши сообщения в этом форуме.
Вы не можете создавать опросы в этом форуме.
Вы не можете голосовать в этом форуме.
Important Information:
The Форум КриптоПро uses cookies. By continuing to browse this site, you are agreeing to our use of cookies.
More Details
Close