Доброго времени суток, уважаемые.
Может кто подскажет как такой код переписать под C#
Чтоб он мог дешифровать данные зашифрованные аналогичной функцией на Java
private SecretKey generateSecretKey(String s)
{
SecretKey secretkey = null;
ByteArrayInputStream bytearrayinputstream = new ByteArrayInputStream(s.getBytes());
ByteArrayOutputStream bytearrayoutputstream = new ByteArrayOutputStream();
Base64.decode(bytearrayinputstream, bytearrayoutputstream);
SecretKeyFactory secretkeyfactory = SecretKeyFactory.getInstance("DES");
DESKeySpec deskeyspec = new DESKeySpec(bytearrayoutputstream.toByteArray(), 0);
secretkey = secretkeyfactory.generateSecret(deskeyspec);
return secretkey;
}
public boolean decrypt(InputStream inputstream, OutputStream outputstream)
{
boolean flag = false;
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding", "SunJCE");
cipher.init(2, key);
CipherInputStream cipherinputstream = new CipherInputStream(inputstream, cipher);
byte abyte0[] = new byte[8192];
for(int i = 0; (i = cipherinputstream.read(abyte0)) != -1;)
outputstream.write(abyte0, 0, i);
cipherinputstream.close();
flag = true;
return flag;
}
Здравствуйте, JShade, Вы писали:
JS>Доброго времени суток, уважаемые.
JS>Может кто подскажет как такой код переписать под C#
JS>Чтоб он мог дешифровать данные зашифрованные аналогичной функцией на Java
что то типа того:
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;
class DESSample
{
static void Main()
{
try
{
// Create a new DES object to generate a key
// and initialization vector (IV). Specify one
// of the recognized simple names for this
// algorithm.
DES DESalg = DES.Create("DES");
// Create a string to encrypt.
string sData = "Here is some data to encrypt.";
string FileName = "CText.txt";
// Encrypt text to a file using the file name, key, and IV.
EncryptTextToFile(sData, FileName, DESalg.Key, DESalg.IV);
// Decrypt the text from a file using the file name, key, and IV.
string Final = DecryptTextFromFile(FileName, DESalg.Key, DESalg.IV);
// Display the decrypted string to the console.
Console.WriteLine(Final);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
public static void EncryptTextToFile(String Data, String FileName, byte[] Key, byte[] IV)
{
try
{
// Create or open the specified file.
FileStream fStream = File.Open(FileName,FileMode.OpenOrCreate);
// Create a new DES object.
DES DESalg = DES.Create();
// Create a CryptoStream using the FileStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(fStream,
DESalg.CreateEncryptor(Key,IV),
CryptoStreamMode.Write);
// Create a StreamWriter using the CryptoStream.
StreamWriter sWriter = new StreamWriter(cStream);
// Write the data to the stream
// to encrypt it.
sWriter.WriteLine(Data);
// Close the streams and
// close the file.
sWriter.Close();
cStream.Close();
fStream.Close();
}
catch(CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
}
catch(UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
}
}
public static string DecryptTextFromFile(String FileName, byte[] Key, byte[] IV)
{
try
{
// Create or open the specified file.
FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);
// Create a new DES object.
DES DESalg = DES.Create();
// Create a CryptoStream using the FileStream
// and the passed key and initialization vector (IV).
CryptoStream cStream = new CryptoStream(fStream,
DESalg.CreateDecryptor(Key,IV),
CryptoStreamMode.Read);
// Create a StreamReader using the CryptoStream.
StreamReader sReader = new StreamReader(cStream);
// Read the data from the stream
// to decrypt it.
string val = sReader.ReadLine();
// Close the streams and
// close the file.
sReader.Close();
cStream.Close();
fStream.Close();
// Return the string.
return val;
}
catch(CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
return null;
}
catch(UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
return null;
}
}
}
Владея информацией, владеешь миром. Уинстон Черчилль
Здравствуйте, DioNNis, Вы писали:
DNN>Здравствуйте, JShade, Вы писали:
JS>>Доброго времени суток, уважаемые.
JS>>Может кто подскажет как такой код переписать под C#
JS>>Чтоб он мог дешифровать данные зашифрованные аналогичной функцией на Java
DNN>что то типа того:
DNN>DNN>
Спасибо. Это понятно =)
Я немного неверно истолковал вопрос.
как переписать я практически понял...
вопрос в следующем:
1. Как в C# указать параметры криптоалгоритма такие же как в приведеном примере ( DES/ECB/PKCS5Padding ).
Или может оно по умолчанию так и будет?
2. как указать текстовый ключ для шифрации ? (то что в примере делается в ф-ии generateSecretKey )
Здравствуйте, JShade, Вы писали:
JS>вопрос в следующем:
JS>1. Как в C# указать параметры криптоалгоритма такие же как в приведеном примере ( DES/ECB/PKCS5Padding ).
JS>Или может оно по умолчанию так и будет?
У TripleDESCryptoServiceProvider есть свойства Mode (ECB — есть) и Padding (а вот PKCS5 — вроде нету)
JS>2. как указать текстовый ключ для шифрации ? (то что в примере делается в ф-ии generateSecretKey )
В .net все симмеиричные криптопровайдеры принимают ключ и IV.
Строку можно конвертнуть в массив байт
byte[] buffer;
buffer = Convert.FromBase64String(s);
А дальше смотри, что там с этим массивом делает DESKeySpec в Java, и как из него вытащить ключ и вектор.