2015-11-15 54 views
0

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

项目类别:

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(); 
     } 
    } 
+0

你的代码中有一些明显的编程错误,主要你应该记住,你不必分配一个值直接指向一个变量,'encrypt.GetNonZeroBytes(data);'后面是'data = new byte [maxSize];'当然是一个严重的错误。 –

回答

0

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

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