#region "Encrypt Strings and Byte[]"
// Note that extension methods must be defined in a non-generic static class.
// Encrypt or decrypt the data in in_bytes[] and return the result.
public static byte[] CryptBytes(string password, byte[] in_bytes, bool encryptAES)
{
// Make an AES service provider.
AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();
// Find a valid key size for this provider.
int key_size_bits = 0;
for (int i = 4096; i > 1; i--)
{
if (aes_provider.ValidKeySize(i))
{
key_size_bits = i;
break;
}
}
Debug.Assert(key_size_bits > 0);
Console.WriteLine("Key size: " + key_size_bits);
// Get the block size for this provider.
int block_size_bits = aes_provider.BlockSize;
// Generate the key and initialization vector.
byte[] key = null;
byte[] iv = null;
byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 };
MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);
// Make the encryptor or decryptor.
ICryptoTransform crypto_transform;
if (encryptAES)
{
crypto_transform = aes_provider.CreateEncryptor(key, iv);
}
else
{
crypto_transform = aes_provider.CreateDecryptor(key, iv);
}
// Create the output stream.
using (MemoryStream out_stream = new MemoryStream())
{
// Attach a crypto stream to the output stream.
using (CryptoStream crypto_stream = new CryptoStream(out_stream,
crypto_transform, CryptoStreamMode.Write))
{
// Write the bytes into the CryptoStream.
crypto_stream.Write(in_bytes, 0, in_bytes.Length);
try
{
crypto_stream.FlushFinalBlock();
}
catch (CryptographicException)
{
// Ignore this exception. The password is bad.
}
catch
{
// Re-throw this exception.
throw;
}
// return the result.
return out_stream.ToArray();
}
}
}
// String extensions to encrypt and decrypt strings.
public static byte[] EncryptAES(this string the_string, string password)
{
System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding();
byte[] plain_bytes = ascii_encoder.GetBytes(the_string);
return CryptBytes(password, plain_bytes, true);
}
public static string DecryptAES(this byte[] the_bytes, string password)
{
byte[] decrypted_bytes = CryptBytes(password, the_bytes, false);
System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding();
return ascii_encoder.GetString(decrypted_bytes);
}
public static string CryptString(string password, string in_string, bool encrypt)
{
// Make a stream holding the input string.
byte[] in_bytes = Encoding.ASCII.GetBytes(in_string);
using (MemoryStream in_stream = new MemoryStream(in_bytes))
{
// Make an output stream.
using (MemoryStream out_stream = new MemoryStream())
{
// Encrypt.
CryptStream(password, in_stream, out_stream, true);
// Return the result.
out_stream.Seek(0, SeekOrigin.Begin);
using (StreamReader stream_reader = new StreamReader(out_stream))
{
return stream_reader.ReadToEnd();
}
}
}
}
// Convert a byte array into a readable string of hexadecimal values.
public static string ToHex(this byte[] the_bytes)
{
return ToHex(the_bytes, false);
}
public static string ToHex(this byte[] the_bytes, bool add_spaces)
{
string result = "";
string separator = "";
if (add_spaces) separator = " ";
for (int i = 0; i < the_bytes.Length; i++)
{
result += the_bytes[i].ToString("x2") + separator;
}
return result;
}
// Convert a string containing 2-digit hexadecimal values into a byte array.
public static byte[] ToBytes(this string the_string)
{
List the_bytes = new List();
the_string = the_string.Replace(" ", "");
for (int i = 0; i < the_string.Length; i += 2)
{
the_bytes.Add(
byte.Parse(the_string.Substring(i, 2),
System.Globalization.NumberStyles.HexNumber));
}
return the_bytes.ToArray();
}
#endregion // Encrypt Strings and Byte[]
С помощью приведенного выше кода вы получите байт списка, с помощью этой функции он будет преобразован в символ списка
// Return a string that represents the byte array
// as a series of hexadecimal values separated
// by a separator character.
public static string ToHex(this byte[] the_bytes, char separator)
{
return BitConverter.ToString(the_bytes, 0).Replace('-', separator);
}
Я получаю данные из списка строк, зашифровываю их следующим образом и хочу записать их в файл
var encryptedLines = (from line in output
select Helper.ToHex(Encryption.EncryptAES(line, symKey),' ').ToList());
но File.WriteAllLines(fileWrite, EncryptedLines); всегда выдает мне исключение из заголовка, или если я пишу результат, он, конечно, просто записывает System. Collections.Generic.List`1[System.Char], потому что он на самом деле не преобразует тип данных в строку списка.
При этом я не понимаю, почему я не могу просто написать все строки символов в файл?
Я попробовал .ToString() или var result = EncryptedLines.Select(c => c.ToString()).ToList();
Я использую этот код (найденный здесь c Sharp Helper AES Encryption) для шифрования строки и зашифрованной строки, которую я хочу сохранить в файл.
[code]#region "Encrypt Strings and Byte[]" // Note that extension methods must be defined in a non-generic static class.
// Encrypt or decrypt the data in in_bytes[] and return the result. public static byte[] CryptBytes(string password, byte[] in_bytes, bool encryptAES) { // Make an AES service provider. AesCryptoServiceProvider aes_provider = new AesCryptoServiceProvider();
// Find a valid key size for this provider. int key_size_bits = 0; for (int i = 4096; i > 1; i--) { if (aes_provider.ValidKeySize(i)) { key_size_bits = i; break; } } Debug.Assert(key_size_bits > 0); Console.WriteLine("Key size: " + key_size_bits);
// Get the block size for this provider. int block_size_bits = aes_provider.BlockSize;
// Generate the key and initialization vector. byte[] key = null; byte[] iv = null; byte[] salt = { 0x0, 0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0xF1, 0xF0, 0xEE, 0x21, 0x22, 0x45 }; MakeKeyAndIV(password, salt, key_size_bits, block_size_bits, out key, out iv);
// Make the encryptor or decryptor. ICryptoTransform crypto_transform; if (encryptAES) { crypto_transform = aes_provider.CreateEncryptor(key, iv); } else { crypto_transform = aes_provider.CreateDecryptor(key, iv); }
// Create the output stream. using (MemoryStream out_stream = new MemoryStream()) { // Attach a crypto stream to the output stream. using (CryptoStream crypto_stream = new CryptoStream(out_stream, crypto_transform, CryptoStreamMode.Write)) { // Write the bytes into the CryptoStream. crypto_stream.Write(in_bytes, 0, in_bytes.Length); try { crypto_stream.FlushFinalBlock(); } catch (CryptographicException) { // Ignore this exception. The password is bad. } catch { // Re-throw this exception. throw; }
// return the result. return out_stream.ToArray(); } } }
// String extensions to encrypt and decrypt strings. public static byte[] EncryptAES(this string the_string, string password) { System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding(); byte[] plain_bytes = ascii_encoder.GetBytes(the_string); return CryptBytes(password, plain_bytes, true); } public static string DecryptAES(this byte[] the_bytes, string password) { byte[] decrypted_bytes = CryptBytes(password, the_bytes, false); System.Text.ASCIIEncoding ascii_encoder = new System.Text.ASCIIEncoding(); return ascii_encoder.GetString(decrypted_bytes); } public static string CryptString(string password, string in_string, bool encrypt) { // Make a stream holding the input string. byte[] in_bytes = Encoding.ASCII.GetBytes(in_string); using (MemoryStream in_stream = new MemoryStream(in_bytes)) { // Make an output stream. using (MemoryStream out_stream = new MemoryStream()) { // Encrypt. CryptStream(password, in_stream, out_stream, true);
// Return the result. out_stream.Seek(0, SeekOrigin.Begin); using (StreamReader stream_reader = new StreamReader(out_stream)) { return stream_reader.ReadToEnd(); } } } }
// Convert a byte array into a readable string of hexadecimal values. public static string ToHex(this byte[] the_bytes) { return ToHex(the_bytes, false); } public static string ToHex(this byte[] the_bytes, bool add_spaces) { string result = ""; string separator = ""; if (add_spaces) separator = " "; for (int i = 0; i < the_bytes.Length; i++) { result += the_bytes[i].ToString("x2") + separator; } return result; }
// Convert a string containing 2-digit hexadecimal values into a byte array. public static byte[] ToBytes(this string the_string) { List the_bytes = new List(); the_string = the_string.Replace(" ", "");
for (int i = 0; i < the_string.Length; i += 2) { the_bytes.Add( byte.Parse(the_string.Substring(i, 2), System.Globalization.NumberStyles.HexNumber)); } return the_bytes.ToArray(); }
#endregion // Encrypt Strings and Byte[] [/code]
С помощью приведенного выше кода вы получите байт списка, с помощью этой функции он будет преобразован в символ списка
[code] // Return a string that represents the byte array // as a series of hexadecimal values separated // by a separator character. public static string ToHex(this byte[] the_bytes, char separator) { return BitConverter.ToString(the_bytes, 0).Replace('-', separator); } [/code]
Я получаю данные из списка строк, зашифровываю их следующим образом и хочу записать их в файл
[code] var encryptedLines = (from line in output select Helper.ToHex(Encryption.EncryptAES(line, symKey),' ').ToList()); [/code]
но File.WriteAllLines(fileWrite, EncryptedLines); всегда выдает мне исключение из заголовка, или если я пишу результат, он, конечно, просто записывает System. Collections.Generic.List`1[System.Char], потому что он на самом деле не преобразует тип данных в строку списка.
При этом я не понимаю, почему я не могу просто написать все строки символов в файл?
Я попробовал .ToString() или var result = EncryptedLines.Select(c => c.ToString()).ToList();
У меня есть ArrayList, который содержит 4 элемента. Каждый элемент имеет список типов . Я пытаюсь получить первый элемент из ArrayList, используя код ниже. но он бросает ошибку
Невозможно отменить объект типа
'system.collections.generic.list 1 '...
Я хочу получить конкретный AnimationClip, используя linq для массива для Animationclip.
код:
AnimationClip[] clips = GetComponent().runtimeAnimatorController.animationClips;
Я получаю следующее сообщение об ошибке с приведенным ниже кодом. Я думал, что тип данных List такой же, как и double[], но C# требует, чтобы его экземпляр был создан с использованием первого синтаксиса, чтобы переменная работала как объект. Что я...