简体   繁体   English

生成一个随机字符串,其长度从变量继承

[英]Generate a random string with length inherited from variable

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(AZ) but the same length (in characters) of the message to be encrypted. 我正在使用密码学控制台应用程序(C#),并希望在加密过程中包括Vigenere Cipher的选项,以生成一个One-Time Pad密钥,该密钥完全是随机字母(AZ),但长度相同(以字符为单位)要加密的消息。 So the question is how do I generate a random string with the same length of previous user input (Stringbuilder s)? 因此,问题是如何生成与先前用户输入(Stringbuilder)长度相同的随机字符串? 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": 如果用户输入“ gen-otp”,则嵌套“ if”是我要生成一次性键盘的位置:

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

So the question is how do I generate a random string with the same length of previous user input(Stringbuilder s) 所以问题是我如何生成与先前用户输入(Stringbuilder s)长度相同的随机字符串

For random letter AZ 对于随机字母AZ

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM