2013-03-29 143 views
0

我到處看了很多教程,他們都說它應該可以工作,但它沒有。Base64編碼和解碼不起作用

我想輸入「編碼RandomText」,然後它應該編碼「RandomText」爲Base64,如果我輸入「解碼[theEncodedText]」它應該從Base64編碼解碼,並給我「RandomText「。我做了我能做的所有事情,但仍然無效。

檢查我的全碼:

static public void Write(string text, int ms) 
    { 
     foreach (char c in text) 
     { 
      Thread.Sleep(ms); 
      Console.Write(c); 
     } 
    } 
    static public string Encode(string text) 
    { 
     byte[] encodedBytes = ASCIIEncoding.ASCII.GetBytes(text); 
     return Convert.ToBase64String(encodedBytes); 
    } 
    static public string Decode(string text) 
    { 
     byte[] decodedBytes = Convert.FromBase64String(text2); 
     return ASCIIEncoding.ASCII.GetString(decodedBytes); 
    } 
    static void Main(string[] args) 
    { 
     string input = ""; 
     while (input != "exit") 
     { 
      Console.ForegroundColor = ConsoleColor.White; 
      Write("Input:> ", 10); Console.ForegroundColor = ConsoleColor.Gray; 
      input = Console.ReadLine().ToLower().Trim(); 

      if (input.StartsWith("encode")) 
      { 
       try 
       { 
        string toEncode = input.Substring(7); 
        Write(Encode(toEncode) + "\n\n", 10); 
       } 
       catch 
       { 
        Write("Please enter the text to encode!\n\n", 10); 
       } 
      } 
      else if (input.StartsWith("decode")) 
      { 
       try 
       { 
        string toDecode = input.Substring(7); 
        Write(Decode(toDecode) + "\n\n", 10); 
       } 
       catch 
       { 
        Write("The entered text is either missing or is not encoded!\n\n", 10); 
       }     
      } 
      else 
      { 
       if (input != "" && input != "exit") 
       { 
        Write("Invalid command.\n\n", 10); 
       } 
       else 
       { 
       } 
      } 
      Console.ForegroundColor = ConsoleColor.White; 
     } 
    } 

回答

0

Base64是區分大小寫的。您正在降低輸入數據的情況。因此它不會工作。