Sylvester_Sneer - 1 month ago 8

C# Question

I am working on a cryptography console application (C#) and want to include an option for the Vigenere Cipher during the encryption process to generate a One-Time Pad key that is completely random letters(A-Z) but the same length (in characters) of the message to be encrypted. So the question is how do I generate a random string with the same length of previous user input (Stringbuilder s)? I apologize in advance if this is an obvious solution. The following is my code for initializing and displaying the results of the encryption process. The nested "if" is where I want to generate the One-Time Pad key if the user enters "gen-otp":

`//Encrypt`

if ((selection == 1) && (type == 1))

{

Clear();

WriteLine("\nPlease enter the message you wish to encrypt(please exclude spaces from the message):\n");

StringBuilder s = new StringBuilder(ReadLine());

WriteLine("\nPlease enter your key word or phrase:\n");

string key = ReadLine();

VigenereEncryptDecrypt.VigenereEncrypt(ref s, key);

if (ReadLine() == "gen-otp")

{

}

Clear();

WriteLine("\nEncrypted message:\n{0}\n\nKey: {1}\n\nPlease press ENTER to continue:", s, key);

ReadLine();

Clear();

CipherSelection();

}

Answer

So the question is how do I generate a random string with the same length of previous user input(Stringbuilder s)

For random letter `A-Z`

```
Random rnd = new Random();
var otp = string.Concat(Enumerable.Range(0, s.Length)
.Select(i => (char)(rnd.Next(26) + 'A')));
```