2015-11-24 29 views
-1

我只能加密,但我不知道如何解密。有人请帮忙。我必须声明一个布尔变量吗? 或者还有其他更好的方法吗?如何为我的解密编写一个没有特殊字符的代码

   string UserInput = ""; 
       int shift; 
       Shift OBSHIFT = new Shift(); 
       Console.Write("\nType a string to encrypt:"); 
       UserInput = Console.ReadLine(); 
       Console.Write("How many chars would you like to shift?: "); 
       shift = int.Parse(Console.ReadLine()); 
       Console.WriteLine("\nApplying Caesar cipher ... "); 
       Console.Write("Your encrypted string is: "); 
       Console.WriteLine(OBSHIFT.Cshift(UserInput, shift)); 
       Console.Read(); 
     } 
    } 
class Shift 
{ 
    public string Cshift(string str, int shift) 
    { 
     string UserOutput = ""; 
     char[] A = null; 
     A = str.ToCharArray(); 
     int temp; 
     for (int i = 0; i < str.Length; i++) 
     { 
      char c = A[i]; 
      if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) 
      { 
       temp = (int)(A[i] + shift); 
       if ((c >= 'A' && c <= 'Z' && temp > 'Z') || (c >= 'a' && c <= 'z' && temp > 'z')) 
        temp = temp - 26; 
       else 
        temp = (int)(A[i] + (shift)); 
      } 
      else 
       temp = c; 
      UserOutput += (char)temp; 
     } 
     return UserOutput; 
    } 
} 

}

}

回答

0

谈到凯撒密码,你可以简单地否定shift并获得原始字符串。

即,cshift(cshift(string, x), -x) == string

使用您Shift类:

int sh = 17; 
string original = "abcdefgh"; 

string encrypted = shift.Cshift(original, sh); 
string decrypted = shift.Cshift(shifted, -sh); 

Console.WriteLine(decrypted == original); // true 

为了方便,你可以创建一个方法Decrypt,这将做到这一点:

class Shift 
{ 
    public string Encrypt(string originalString, int shift) 
    { 
     string userOutput = ""; 
     char[] a = originalString.ToCharArray(); 
     for (int i = 0; i < originalString.Length; i++) 
     { 
      char c = a[i]; 
      int temp; 
      if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z')) 
      { 
       temp = (int)(a[i] + shift); 
       if ((c >= 'A' && c <= 'Z' && temp > 'Z') || (c >= 'a' && c <= 'z' && temp > 'z')) 
        temp = temp - 26; 
       else 
        temp = (int)(a[i] + (shift)); 
      } 
      else 
       temp = c; 
      userOutput += (char)temp; 
     } 
     return userOutput; 
    } 

    public string Decrypt(string cipherString, int shift) 
    { 
     return Encrypt(cipherString, -shift); 
    } 
} 

请注意,我也做了一些小的代码的改进,比如:

  • 联合声明和转让A
  • 移动temp到内部范围
  • 给了专有名称的局部变量(小写)
+0

Yeldar嗨,我不明白你的代码,我在哪里可以把INT SH = 17 ; string original =“abcdefgh”; string encrypted = shift.Cshift(original,sh); string decrypted = shift.Cshift(shifted,-sh); Console.WriteLine(decrypted == original); –