0

I am trying to generate a cryptographic alphabetic key via c# no longer than the string entered previously. For example I have a method CharCount counting the characters and passes it into attribute CI. I then have a GenerateKey method in another class. I generate the key via Ciph.Generatekey(CI) the CI gives the count of the original string but the PROBLEM here is I want it to generate a random length up to the CI value, instead it is just generating the string length in CI.

Program Class:

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

Ciphering Class:

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();
        }
    }
Jake Groves
  • 327
  • 2
  • 4
  • 17
  • There are some blatant programming errors in your code. Mainly you should remember that you don't have to assign a value to a variable directly. `encrypt.GetNonZeroBytes(data);` followed by `data = new byte[maxSize];` is of course a gross error. – Maarten Bodewes Nov 15 '15 at 23:01

1 Answers1

0

You can use this answer to retrieve values between a minimum and a maximum value. You should use this to first generate the amount of characters in the key.

You can use it as well to generate random characters (by using an index in the range 0..26). Currently your key character generation is somewhat biased (because the modulus operator will make lower indexed characters more likely than higher indexed characters.

Community
  • 1
  • 1
Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263