java - 解密后加密 (AES) 的字符串打印相同的值,但 equals() 上为 false

标签 java encryption cryptography aes

我的程序将使用收到的 session key 加密的字符串(AES)发送给客户端,以证明 key 是正确的。 客户端应该解密它,获取字符串并与原始字符串进行验证。

程序运行良好。它对字符串进行加密和解密。它打印我需要的字符串,但当我执行 String.equals(string) 时给我错误。 我能弄清楚为什么。 我的代码有加密部分:

// ----create a challenge for Client (to check if the session key is correct)--------

public void sessionKeyVer(String challenge, File out) throws Exception{

    aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec); // switching mode for encryption

    CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), aesCipher); //output stream to another file 

    os.write(challenge.getBytes("UTF-8"));// function to copy String to outputstream
    os.close();     //close the stream

}

有解密部分:

public boolean sessionKeyVer(File file) throws Exception{
    aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec); // switching mode for decryption

    CipherInputStream is = new CipherInputStream(new FileInputStream(file), aesCipher); //output stream to another file 
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    int i;
    byte[] b = new byte[1024];
    while((i=is.read(b))!=-1) {
          os.write(b, 0, i);
      }

    is.close();
    os.close();
    String file_string = new String(b,"UTF-8");
    System.out.print(file_string);
    return file_string.equals(challenge); //return false

}

谢谢。

最佳答案

第一部分是加密部分。 第二部分是解密部分。

第二部分是错误的。您正在解密仍然加密的缓冲区的最后一部分,而不是整个解密的 ByteArrayOutputStream,并在此过程中犯了尺寸错误。

String file_string = new String(b,"UTF-8");

应该是

String file_string = new String(os.toByteArray(), "UTF-8");

关于java - 解密后加密 (AES) 的字符串打印相同的值,但 equals() 上为 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21664967/

相关文章:

cocoa - 提取二进制文件 cocoa 的内容

node.js - Steam OpenID 签名验证

python - 获取 md5 校验和的完成百分比

Java 根据值连接列表,

java - 如何在Java中替换双括号内的子字符串?

java - Android 字段出现在标题后面

java - Mockito 匹配器将方法与泛型和供应商匹配

java将数字值加密为字母数字值

ruby - 从非 Google 系统调用时,CloudKMS 加密/解密如何安全工作?

cryptography - RSA加密问题[有效负载数据大小]