簡體   English   中英

無法從&#39;System.Collections.Generic.IEnumerable轉換 <System.Collection.Generic.List<char> &gt;字符串[]

[英]Cannot convert from 'System.Collections.Generic.IEnumerable<System.Collection.Generic.List<char>> to string[]

我使用此代碼(可在此處找到鋒利的助手aes加密 )對字符串和要保存到文件的加密字符串進行加密。

#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<byte> the_bytes = new List<byte>();
        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();

您可以將char列表轉換為char數組,也可以使用以下方式將char列表轉換為字符串:

 listOfChars.Aggregate("", (str, x) => str + x);

不建議使用第二種方法,因為它具有二次復雜度(請查看此答案的評論)


更新:

在李先生的評論后,我再次檢查了一下,發現這樣做更加有效:

 listOfChars.Aggregate(new StringBuilder(""), (str, x) => str.Append(x)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM