我如何不超过Vigenere密码中数组的界限?

时间:2018-08-13 17:48:54

标签: c# encryption cryptography vigenere

第四个字符后,我的程序崩溃,返回此错误:

  

索引超出了数组的范围。在   System.String.get_Chars(Int32索引)在   Caesar_Cipher.Program.Main(String [] args)

我真的不知道如何解决它。

代码如下:

using System;  
using System.Collections.Generic;  
using System.Text;  

namespace vigenere_Cipher {  
    class Program {  
        static void Main(string[] args) {
            string text = string.Empty;
            string key = string.Empty;

            Console.Write("Enter the keyword: ");
            key = Console.ReadLine();
            for(int i = 0; i < key.Length; i++)
            {
                if(char.IsLetter(key[i]))
                {

                }
                else
                {
                    Console.WriteLine("a key must be alphabetical!");
                }
            }
            Console.Write("Enter plaintext: ");
            text = Console.ReadLine();
            int counter = 0;
            for(int j = 0; j <= text.Length; j++)
            {
                if(counter <= text.Length)
                {
                    counter ++;
                }
                if(char.IsLetter(text[j]))
                {
                if(char.IsUpper(text[j]))
                {
                    Console.Write("Encrypted string: " + Convert.ToChar(((text[j] + key[counter] -65)% 26) + 65));
                }
                if(char.IsLower(text[j]))
                {

                    Console.Write("Encrypted string: " + Convert.ToChar(((text[j] + key[counter]-97)%26) + 97)); 

                }
                Console.Write("\n");
            }


            Console.ReadKey();
        }
    }
 }
}

0 个答案:

没有答案