Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java public private key decryption issue

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


}
like image 293
jgg Avatar asked Aug 28 '26 22:08

jgg


1 Answers

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 encoding uses the first 7 bits of a byte, to make something that is printable or emailable, for example.

UPDATE:

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.

like image 126
James Black Avatar answered Aug 30 '26 10:08

James Black



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!