Java公共私钥解密问题 [英] Java public private key decryption issue

查看:228
本文介绍了Java公共私钥解密问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试如下面的代码中所述加密和解密邮件。基本上,我想用一个公钥加密消息,并将加密的消息从字节数组转换为字符串。并将此字符串解密为原始文本。这两种方法。这里加密工作正常,但解密失败(错误是数据必须从零开始)。我认为这是因为我将加密的字节数组转换为字符串。


如何解决这个问题? (我想有加密的字节数组作为字符串,并使用它进行解密)是否有任何其他方法(使用公钥和私钥)

I am trying to encrypt and decrypt a message as mentioned in the below code. Basically I want to encrypt a message with a public key and convert that encrypted message from byte array to String. And decrypt this string into original text. Here are the both methods. Here encryption works fine but decryption fails (error is "Data must start with zero"). I think this is causing because I convert encrypted byte array into String.

How do I solve this? (I want to have encrypted byte array as string and use it for decryption) Is there any other approach (with public and private keys)

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) {


}


推荐答案

如果您查看此页面( http:// www .wikijava.org / wiki / Secret_Key_Cryptography_Tutorial )你需要做base-64编码将字节转换为字符串,然后解密它,你只需解码然后解密。

If you look at this page (http://www.wikijava.org/wiki/Secret_Key_Cryptography_Tutorial) you will need to do base-64 encoding to turn the bytes into a string, then to decrypt it you would just decode it then decrypt.

Base-64编码使用一个字节的前7位,例如可以打印或可打印。

Base-64 encoding uses the first 7 bits of a byte, to make something that is printable or emailable, for example.

UPDATE:

我犯了一个错误,有64个字符,它会被编码,再次,为了更容易使用作为可打印。

I made a mistake, there are 64 characters that it would be encoded in, again, in order to make it easier to use as something printable.

这篇关于Java公共私钥解密问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆