1

我正在开发一个小型 Java 应用程序,向一些学生展示使用 RSA 算法实现的公钥加密的概念。值得一提的是,我没有使用 Java 的库,因为这会抽象出大部分关键概念。

我用于加密的算法只是将字符串分解为字符数组,加密每个字符,然后将每个加密字符显示在自己的行上(为了便于阅读)。我了解这对于实际目的来说并不安全;填充算法是后面课程的主题。

我遇到的问题是,当加密输出不是从 GUI 中的输入框中获取时,加密/解密工作正常。例如,此代码将起作用:

String sample = “Hello World”;
BigInteger[] encrypted = RsaExample.encrypt(sample);
For (BigInteger b : encrypted) {
    System.out.print(b.toString() + “\n”);
String decrypted = RsaExample.decrypt(encrypted); //Returns “Hello World”

但是,当我使用 GUI 完成相同的任务时,结果被破坏了:

//When “Encrypt” button is pressed
String sample = InputBox.getText();
BigInteger[] encrypted = RsaExample.encrypt(sample);
String output;
For (BigInteger b : encrypted) {
    output += (b.toString() + “\n”);
OutputBox.setText(output);


//When “Decrypt” button is pressed
String encrypted = OutputBox.getText();
BigInteger[] encrypted_arr = encrypted.split(“\n”);
String decrypted = RsaExample.decrypt(encrypted_arr);
OutputBox.setText(decrypted);

我已经确认(通过将输出复制/粘贴到文档)输出正在使用换行符进行格式化。我怀疑问题出在 GUI 添加某种间距或以某种方式破坏了确切的输出。

编辑:这是每个 ActionPerformed 方法的确切代码:

 private void buttonEncryptActionPerformed(java.awt.event.ActionEvent evt) {                                              
    String input = fieldInput.getText();
    BigInteger[] encrypted = encrypt.encrypt(input);
    String output = "";
    for (int i = 0; i < encrypted.length; i++) {
        //String concatenation seems to fail here
        output += encrypted[i].toString() + "\n";
    }
    System.out.println(output);
    fieldOutput.setText(output);
}                                             

private void buttonDecryptActionPerformed(java.awt.event.ActionEvent evt) {                                              
    String input = fieldOutput.getText();
    input = input.trim();
    fieldInput.setText(input);
    fieldOutput.setText(""); //Clear the output
    String[] chars = input.split("\n");
    System.out.print(chars.length);
    BigInteger[] encrypted = new BigInteger[chars.length];
    for (int i = 0; i < chars.length; i++) {
        //Remove Whitespace that caused NumberFormatException            
        String trimmed = chars[i].replaceAll("\\s",""); 
        encrypted[i] = new BigInteger(trimmed);
    }
    String decrypted = encrypt.decrypt(encrypted);
    fieldOutput.setText(decrypted);
}
4

0 回答 0