【问题标题】:Encrypting using Vigenere cipher where Plaintext is read from a file (JAVA)使用从文件中读取明文的 Vigenere 密码进行加密 (JAVA)
【发布时间】:2014-11-15 15:50:32
【问题描述】:

我正在尝试一个简单的 Vigenere 密码,其中从文件中读取纯文本并使用密钥进行加密。

键=ABC PT和密钥相加得到密文

纯文本:W E W I L L A T T A C K T O N I G H T

键:A B C A B C A B C A B C A B C A B C A

密码:W F Y I M N A U V A D M T P P I H J T

如何在纯文本长度内重复密钥,然后在读取时对其进行加密。

使用以下 sn-p 从文件中读取输入

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.

【问题讨论】:

  • 你试过什么?如果您手动解决此问题,您将如何解决?
  • 我正在尝试按如下方式处理它:在读取时将纯文本保存在数组中...将密钥保存在相同大小的数组中并执行添加...。
  • 好的,所以当您扫描明文时,您需要跟踪您在密钥中的位置,以及当您到达密钥时重新开始。这意味着维护两个索引,或者使用一个模密钥的长度。试着写“SOMETHING”,看看会发生什么,如果错了就改正直到它是对的。编程是调试一张白纸的艺术。
  • @keshlam :嘿,我找到了解决方案。看看

标签: java vigenere


【解决方案1】:
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');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多