【问题标题】:Generate a random string with length inherited from variable生成长度从变量继承的随机字符串
【发布时间】:2016-10-09 19:31:49
【问题描述】:

我正在开发一个加密控制台应用程序 (C#),并希望在加密过程中包含一个 Vigenere Cipher 选项,以生成一个完全随机字母 (A-Z) 但长度相同(在字符)要加密的消息。所以问题是如何生成与先前用户输入(Stringbuilder s)长度相同的随机字符串?如果这是一个明显的解决方案,我提前道歉。以下是我用于初始化和显示加密过程结果的代码。如果用户输入“gen-otp”,嵌套的“if”是我想要生成 One-Time Pad 密钥的地方:

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

【问题讨论】:

  • 我想我需要在嵌套的 if 中声明另一个变量来保存随机生成的密钥,而不是尝试将现有变量“key”变成随机生成的密钥?

标签: c# encryption cryptography


【解决方案1】:

所以问题是如何生成与之前用户输入长度相同的随机字符串(Stringbuilder s)

对于随机字母A-Z

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

【讨论】:

  • 但是对于加密,您应该使用 Crypto 随机生成器。
  • @Sylvester_Sneer 万一你还没读过meta.stackexchange.com/questions/5234/…
  • 我必须查一下。但是,由于这是一个学习练习,至少应该提到它。
猜你喜欢
  • 2018-01-25
  • 2016-12-21
  • 2015-09-13
  • 1970-01-01
  • 2021-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
相关资源
最近更新 更多