【问题标题】:RSA encyrption - converting between bytes array and String [duplicate]RSA加密-字节数组和字符串之间的转换[重复]
【发布时间】:2017-09-05 14:58:09
【问题描述】:

我正在尝试实现能够执行以下操作的 RSA 加密:

  • 接受字符串值作为输入以使用公钥进行加密
  • 以字符串形式返回加密密码
  • 接受加密密码作为使用私钥解密的输入
  • 返回原值,解密

如果我直接解密由加密返回的byte 数组,我能够使加密/解密工作,但如果我将byte 数组解析为String 然后似乎不能让它工作再次回到bytes。

以下代码可以工作:

cipher.init(Cipher.ENCRYPT_MODE, pubKey);
byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);

cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(cipherBytes);
System.out.println("plain : " + new String(plainText));

以下代码不起作用

byte[] cipherBytes = cipher.doFinal(input);
System.out.println("cipher: " + new String(cipherBytes));
returnValue += new String(cipherBytes);

String cipherText = new String(cipherBytes);
byte[] reCipherBytes = cipherText.getBytes();

cipher.init(Cipher.DECRYPT_MODE, privKey);
byte[] plainText = cipher.doFinal(reCipherBytes);
System.out.println("plain : " + new String(plainText));

谁能告诉我需要做什么才能让第二个版本成功运行?

【问题讨论】:

    标签: java encryption cryptography encryption-asymmetric


    【解决方案1】:

    我认为您的问题是因为将字节数组转换为字符串时默认的 java 编码/解码字符集,反之亦然。

    我已经调试了您的代码,并且 reCipherBytes 的长度与 cipherBytes 的长度不同,这就是第二个代码块引发异常的原因。

    我建议您使用 base64 编码将 cipherBytes 转换为字符串。

        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] cipherBytes = cipher.doFinal(input);
        System.out.println("cipher: " + new String(cipherBytes));
        String returnValue = new String(cipherBytes);
    
        String cipherText = Base64.getEncoder().encodeToString(cipherBytes);
        byte[] reCipherBytes = Base64.getDecoder().decode(cipherText);
    
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] plainText = cipher.doFinal(reCipherBytes);
        System.out.println("plain : " + new String(plainText));
    

    这个代码片段应该可以工作

    【讨论】:

    • 效果很好,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    相关资源
    最近更新 更多