【问题标题】:C# Generate cryptographic key no longer than string sizeC# 生成不超过字符串大小的加密密钥
【发布时间】:2015-11-15 13:36:43
【问题描述】:

我正在尝试通过 c# 生成一个不超过之前输入的字符串的加密字母密钥。 例如,我有一个 CharCount 方法计算字符并将其传递给属性 CI。然后我在另一个类中有一个 GenerateKey 方法。我通过 Ciph.Generatekey(CI) 生成密钥,CI 给出了原始字符串的计数,但这里的问题是我希望它生成一个直到 CI 值的随机长度,而不是它只是在 CI 中生成字符串长度。

程序类:

 private static int CI;
    static void Main(string[] args)
    { 
        string Filecontents;
        FileHandling FH = new FileHandling();
        Ciphering Ciph = new Ciphering();
        Filecontents = FH.StreamFile();
        string CC = CharCount(Filecontents);
        bool test = int.TryParse(CC, out CI);
        Console.WriteLine(Ciph.GenerateKey(CI));
    }
public static string CharCount(string info)
        {
            StringBuilder result = new StringBuilder();
            int count = 0;
            string st = info;
            foreach (char c in st)
            {
                if (char.IsLetter(c))
                {
                    count++;
                }
            }
            result.Append(count);
            return result.ToString();
        }

加密类:

class Ciphering
    {
        public string GenerateKey(int maxSize)
        {
            char[] chars = new char[62];
            chars =
            "abcdefghijklmnopqrstuvwxyz".ToCharArray();
            byte[] data = new byte[1];
            using (RNGCryptoServiceProvider encrypt = new RNGCryptoServiceProvider())
            {
                encrypt.GetNonZeroBytes(data);
                data = new byte[maxSize];
                encrypt.GetNonZeroBytes(data);
            }
            StringBuilder result = new StringBuilder(maxSize);
            foreach (byte c in data)
            {
                result.Append(chars[c % (chars.Length)]);
            }
            return result.ToString();
        }
    }

【问题讨论】:

  • 您的代码中有一些明显的编程错误。主要是您应该记住,您不必直接为变量赋值。 encrypt.GetNonZeroBytes(data); 后跟 data = new byte[maxSize]; 当然是严重错误。

标签: c# cryptography


【解决方案1】:

您可以使用this answer 检索最小值和最大值之间的值。您应该首先使用它来生成键中的字符数。

您也可以使用它来生成随机字符(通过使用 0..26 范围内的索引)。目前,您的关键字符生成有些偏颇(因为模运算符会使索引较低的字符比索引较高的字符更有可能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多