Java公钥私钥解密问题

问题描述 投票:3回答:3

我正在尝试加密和解密消息,如下面的代码中所述。基本上我想用公钥加密消息并将该加密消息从字节数组转换为String。并将此字符串解密为原始文本。以下是这两种方法。这里加密工作正常,但解密失败(错误是“数据必须从零开始”)。我认为这是因为我将加密的字节数组转换为String。 我该如何解决这个问题? (我希望将加密的字节数组作为字符串并用于解密)是否有其他方法(使用公钥和私钥)

public static String getEncryptedMessage(String publicKeyFilePath,

    String plainMessage) {
    byte[] encryptedBytes;
    try {
        Cipher cipher = Cipher.getInstance("RSA");
        byte[] publicKeyContentsAsByteArray = getBytesFromFile(publicKeyFilePath);
        PublicKey publicKey = getPublicKey(publicKeyContentsAsByteArray);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        encryptedBytes = cipher.doFinal(plainMessage.getBytes());
        return new String(encryptedBytes);
    } catch (Throwable t) {

    }

}
public static String getDecryptedMessage(
        String privateKeyFilePath, String encryptedMessage)
         {
    byte[] decryptedMessage;
    try {
        Cipher cipher = Cipher.getInstance("RSA");
        byte[] privateKeyContentsAsByteArray = getBytesFromFile(privateKeyFilePath);
        PrivateKey privateKey = getPrivateKey(privateKeyContentsAsByteArray);
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        decryptedMessage = cipher.doFinal(encryptedMessage.getBytes());
        return new String(decryptedMessage);
    } catch (Throwable t) {


}
java encoding cryptography public-key-encryption
3个回答
2
投票

如果你看一下这个页面(http://www.wikijava.org/wiki/Secret_Key_Cryptography_Tutorial),你需要做base-64编码把字节变成一个字符串,然后解密它你只需解码然后解密。

例如,Base-64编码使用字节的前7位来制作可打印或可邮寄的内容。

更新:

我犯了一个错误,它还会编码64个字符,以便更容易使用它作为可打印的东西。


2
投票

为什么不将消息视为从加密到解密的字节数组?为什么要在中间将它改为String? (我知道这似乎是一个问题,但它实际上是一个答案...)


2
投票

直接在未格式化的数据上使用RSA可能会使您的应用程序容易受到自适应选择的密文攻击。有关详细信息,请参阅Handbook of Applied Cryptography的第8章,第288-289页,这是CRC Press的一本免费提供的书籍。 (非常值得buying the bound edition,如果你对密码学真的很感兴趣 - 你会对价格的质量感到惊讶。)

由于这种攻击,大多数集成RSA的协议使用RSA加密随机生成的会话密钥或使用输出来签署散列函数,这些输出应该与随机无法区分,或者使用非常仔细格式化的消息,这些消息将无法正确解释。 (有关详细信息,请参阅HAC中的注释8.63。)

© www.soinside.com 2019 - 2024. All rights reserved.