凯撒密码问题

时间:2018-10-25 13:52:07

标签: c# caesar-cipher

在C#中解密凯撒密码时遇到问题。我们必须手动,加密和解密。我希望它写出所有可能性一个接一个地移动(然后很容易看到正确的解密,因为其他25可能性都是胡说八道)。问题在于它仅写入一种可能性,而不是26。我尝试了一切。你知道哪里出问题了吗?

string text = "Z programovani{}{}{}";
text = text.ToUpper();
string output = "";
int shift = 3;

foreach (char a in text)
{
    int x = (int)a;
    if (x >= 65 && x <= 90)
    {
        x += shift;
    }
    if (x == 32)
    {
        x -= shift;
    }
    if (x >90)
    {
        x = x - 26;
    }

    output += (char)x;
}
Console.WriteLine(output);

int i = 0;
do
{
    string decoded = "";

    foreach (char a in output)
    {
        int x = (int)a;
        if (x >= 65 && x <= 90)
        {
            x += 1;
        }
        if (x > 90)
        {
            x = x + 26;
        }

        decoded += (char)x;
    }
    i++;
    Console.WriteLine(decoded);
} while (i < 27);

Console.ReadKey();

2 个答案:

答案 0 :(得分:2)

让我们提取一种方法(不要将所有内容都塞进单个@Autowired public void init(AuthenticationManagerBuilder auth, DaoAuthenticationProvider provider) throws Exception { auth.authenticationProvider(provider); } @Bean public DaoAuthenticationProvider authProvider(CustomUserDetailsService userDetailsService, CustomEncoder customEncoder) { DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider(); authProvider.setUserDetailsService(userDetailsService); authProvider.setPasswordEncoder(customEncoder); return authProvider; } 分解您的解决方案,使其更简单,更易于阅读和维护):< / p>

Main

然后您可以轻松使用它:

private static string Caesar(string value, int shift) {
  if (null == value)
    return null;

  // Normalization: if we have shift out of [0..25] range, e.g. -3 or 125
  shift = ((shift % 26) + 26) % 26;

  StringBuilder sb = new StringBuilder(value.Length);

  foreach (var c in value) 
    if (c >= 'a' && c <= 'z')
      sb.Append((char)((c - 'a' + shift) % 26 + 'a')); 
    else if (c >= 'A' && c <= 'Z')
      sb.Append((char)((c - 'A' + shift) % 26 + 'A'));
    else
      sb.Append(c);

  return sb.ToString();
}

结果:

using System.Linq;

...

string text = "Z programovani{}{}{}";

// Let's use Linq; loop 
// for(int i = 0; i < 26; ++i) Console.WriteLine($"{i,2}: {Caesar(text, i)}");  
// is an alternative
string result = string.Join(Environment.NewLine, Enumerable
  .Range(0, 26)
  .Select(i => $"{i,2}: {Caesar(text, i)}"));

Console.Write(result);

答案 1 :(得分:0)

与Cypher玩游戏时,一个常见的问题是“如何处理基本字母中没有的字母?”。
字母的概念是处理[az AZ 09]范围甚至添加标点符号的一种简单方法。这里是迷你版。

static string alphabet = "abcdefghijklmnopqrstuvwxyz";

然后用简单功能将其划分为简单任务:
-ShiftChar,用密码键将字母中的char换成字母。
-密码,一个单词。
-AllCypher,计算所有密码。

char ShiftChar(char letter, int key, StringComparison comparisonType = StringComparison.CurrentCulture)
    => alphabet[EuclydianModulo(AlphabetIndex(letter, comparisonType) + key, alphabet.Length)];

int EuclydianModulo(int dividend, int divisor) //As % computes the remainder, not the modulo
    => ((dividend % divisor) + divisor) % divisor;

string Cypher(string word, int key, StringComparison comparisonType = StringComparison.CurrentCulture)
    => new string(  // To Return a string from char Array
        word.Select(x => // If letter is not in the alphabet, Don't crypt that letter. 
             alphabet.IndexOf(word, comparisonType) >= 0 ? ShiftChar(x, key, comparisonType) : x
            ).ToArray()
       );

List<string> AllCypher(string word, StringComparison comparisonType = StringComparison.CurrentCulture)
    => Enumerable.Range(0, alphabet.Length)
                  // If word is null, string.Empty.
                 .Select(key => Cypher(word??string.Empty, key, comparisonType))
                 .ToList();

internal void TestCase_SO_52991034()
{
    var inputTest = new[] { "cake", "Ufhp rd gtc bnym knaj itejs qnvztw ozlx.", null };
    var result = inputTest.Select(x => new { word = x, cypher = AllCypher(x) });


    var ignoreCase = AllCypher("ABC", StringComparison.CurrentCultureIgnoreCase);
    var caseSentitiv =  AllCypher("ABC");

    var crypt = Cypher("FooBar Crypt me!", 42, StringComparison.CurrentCultureIgnoreCase);
    var decrypt = Cypher(crypt, alphabet.Length - 42);
}

此外,解密只是一个密钥为alphabet.Length - key的加密:

string Decypher(string word, int key, StringComparison comparisonType = StringComparison.CurrentCulture)
    => Cypher(word, alphabet.Length - key, comparisonType);