2014-11-15 2 views
0

Я пробую простой шифр Vigenere, где обычный текст читается из файла и зашифровывается с помощью ключа.Шифрование с использованием шифрования Vigenere, где Plaintext считывается из файла (JAVA)

Key = ABC Cipher текст получается путем добавления между ПТ и ключом

Plain Text: WEWILLATTACKTONIGHT

Ключ: ABCABCABCABCABCABCA

Cipher: WFYIMNAUVADMTPPIHJT

Как может я повторите ключ для длины обычного текста, а затем зашифруйте его, когда он читается.?

вход считывается из файла, используя следующий фрагмент кода

FileInputStream fileInput = new FileInputStream("/Documents/file1.txt"); 

    int r; 
    int count = 0 ; 


    //Read each character from the file one by one till EOF 
    while ((r = fileInput.read()) != -1) 
    { 
     char c = (char) r; 
     //SOMETHING NEEDS TO BE DONE HERE 
    System.out.print(c); 
    count ++; //Keeps count of the number of characters in the plain text. 
+0

Что вы пробовали? Как бы вы решили это, если бы делали это вручную? – keshlam

+0

Я пытаюсь подойти к нему следующим образом: сохранить обычный текст в массиве по мере его чтения ... сохранить ключ в массиве одинакового размера и выполнить добавление .... –

+0

ОК, так как вы сканируете через открытый текст вам нужно отслеживать, где вы находитесь в ключе, и когда вы снова достигаете начала ключа. Это означает сохранение двух индексов или использование по модулю длины ключа. Попробуйте написать «ЧТО-ТО», посмотрите, что произойдет, и если это неправильно, исправьте это, пока оно не будет правильным. Программирование - это искусство отладки чистого листа бумаги. – keshlam

ответ

0
public static void encrypt (String a)throws IOException 
{ 

    //Array of the length of the Plain Text is created 
    char pt[] = new char[count]; 

    //File is opened again and this time passed into the plain text array 
    FileInputStream f = new FileInputStream("/Users/avtrulzz/Documents/file1.txt") ; 

    int s ; 

    int i = 0 ; 

    while((s = f.read()) != -1) 

    { 
    //Every character read is simultaneously fed into the array 
     pt[i] = (char) s ; 
      i ++ ; 
    } 

    //Find the length of the key 
    int kl = a.length() ; 
    //Find how many times the key has to be repeated 
    int keyrep = count/kl ; 

    //Where keyrep is the number of times you want to repeat the string and a is the string to repeat. 
    String repeated = new String(new char[keyrep]).replace("\0", a); 

    System.out.println("The key repeated till the length of the plain text"); 
    System.out.println(); 
    System.out.println(repeated); 

    //The string "repeated" is made into an array "keyforpt" 
    char keyforpt[] = repeated.toCharArray() ; 


    char ct[] = new char[count] ; 

    for(int ind = 0; ind < pt.length ; ind++) 

    { 
     ct[ind] = toChar((toInt(pt[ind]) + toInt(keyforpt[ind]) + 1) % 26); 
    } 

    System.out.println() ; 
    for(int temp = 0;temp < ct.length;temp++) 
     { 

      System.out.print(ct[temp]) ; 
     } 
    System.out.println() ; 
} 


private static int toInt(char chr) 
{ 
    return chr - 'a'; 
} 

private static char toChar(int value) 
{ 
    return (char)(value + 'a'); 
} 

 Смежные вопросы

  • Нет связанных вопросов^_^