2015-11-24 62 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); –