RSA encryption/decryption using Java


username

I am doing a simple program to encrypt/decrypt using the RSA algorithm in Java. I create a password object like this:

//Create a Cipher object
Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");

I encrypt by calling the encrypt function:

String cipher=encrypt(textByte, pair, rsaCipher);
System.out.println("The Encryption using RSA Algorithm : "+cipher);

and decrypt as:

//Decryption
String plain=decrypt(Base64.decodeBase64(cipher),pair, rsaCipher);
System.out.println("The Decryption using RSA Algorithm : "+plain);

When I display the output, the decrypted output returns a long space before the original text:enter image description here

However, when I edit the code that creates the Cipher object to: //Create Cipher object Cipher rsaCipher = Cipher.getInstance("RSA");

i.e. the operation mode and padding parameters are removed, the problem is solved and the output becomes:enter image description here

Where is the problem. In the first case (when spaces appear), do I specify NoPadding? Why do spaces appear in the decrypted message? Even with padding, I hope this doesn't happen.

EDIT: Here is the encryption and decryption method:

public static String encrypt(byte[] textBytes, KeyPair pair, Cipher rsaCipher) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException
{
    //get the public key
    PublicKey pk=pair.getPublic(); 


    //Initialize the cipher for encryption. Use the public key.
    rsaCipher.init(Cipher.ENCRYPT_MODE, pk);

    //Perform the encryption using doFinal
    byte[] encByte = rsaCipher.doFinal(textBytes);

    // converts to base64 for easier display.
    byte[] base64Cipher = Base64.encodeBase64(encByte);

    return new String(base64Cipher);
}//end encrypt

public static String decrypt(byte[] cipherBytes, KeyPair pair, Cipher rsaCipher) throws IllegalBlockSizeException, BadPaddingException, InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException
{
    //get the public key
    PrivateKey pvk=pair.getPrivate(); 

    //Create a Cipher object
    //Cipher rsaCipher = Cipher.getInstance("RSA/ECB/NoPadding");

    //Initialize the cipher for encryption. Use the public key.
    rsaCipher.init(Cipher.DECRYPT_MODE, pvk);

    //Perform the encryption using doFinal
    byte[] decByte = rsaCipher.doFinal(cipherBytes);

    return new String(decByte);

}//end decrypt
Martin Podwith

Your problem is indeed with padding. The secure RSA function requires some kind of padding, actually PKCS#1 1.5 or OAEP padding. Also, the beginning and end of the encrypted plain text needs to be found.

RSA's modular exponentiation is performed using large integers. Then, the results of these operations are represented as octet strings. These octet strings are basically big-endian unsigned fixed-length representations of integers. These integers hold 00value bytes (called I2OS primitives in the RSA standard). So what you're seeing is the result of the modular exponentiation, while the 00padding is still there.

Long story short, always use a padding scheme. Today, OAEP would be preferable. Use with hybrid encryption schemes, or use higher-level container formats such as CMS or PGP.

Related


RSA decryption in Java without using RSA library

rddead I am writing a program that uses RSA to encrypt and decrypt text. The values of P, Q and E are provided by the user and it is checked whether they are prime numbers. The program finds N and D. Encryption and decryption failed. I've looked at some of the

Unable to decrypt RSA using Java

wanghao qin My password is encrypted using RSA in android app. On the server side, I need to decrypt it. , what I have is a .pem file, and the php code for decryption: function privatekey_decodeing($crypttext, $fileName, $fromjs = FALSE) { $key_co

Encrypt and decrypt large strings in Java using RSA

Sergio of Rus: I am trying to implement PKI. I want to encrypt large strings using RSA in Java without bouncy castle. The problem I get is that the data must not exceed 117 bytes. I try to find a solution that fails. I am new to this encryption. Please help me

Export RSA key object to XML using Java

dvl: I have successfully run RSA encryption/decryption in Java. This is how I generate the key. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg

Problems with encryption and decryption using RSA on JAVA

Baltaza: So I'm trying to encrypt a file created when the user types, and after encryption I want to decrypt the file. Both the user created file and the encrypted file are fine, but when I open the encrypted file, I think it's blank because it has some gibber

Encrypt and decrypt large files using rsa in Java

Prajwal Rai I am using the RSA algorithm to encrypt and decrypt files whose size exceeds the size of the rsa key. In the code below for encryption, I am reading the file content in chunks and converting it to ciphertext. The block size is 32 bytes. FileInputSt

Encrypt and decrypt large strings in Java using RSA

Sergio of Rus: I am trying to implement PKI. I want to encrypt large strings using RSA in Java without bouncy castle. The problem I get is that the data must not exceed 117 bytes. I try to find a solution that fails. I am new to this encryption. Please help me

Export RSA key object to XML using Java

dvl: I have successfully run RSA encryption/decryption in Java. This is how I generate the key. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg

Problems with encryption and decryption using RSA on JAVA

Baltaza: So I'm trying to encrypt a file created when the user types, and after encryption I want to decrypt the file. Both the user created file and the encrypted file are fine, but when I open the encrypted file, I think it's blank because it has some gibber

Problems with encryption and decryption using RSA on JAVA

Baltaza: So I'm trying to encrypt a file created when the user types, and after encryption I want to decrypt the file. Both the user created file and the encrypted file are fine, but when I open the encrypted file, I think it's blank because it has some gibber

RSA encryption between Java and JavaScript using OAEP

Andy King I am trying to encrypt a short string with JavaScript and decrypt it with Java. Decryption fails, I think it's because the block mode and/or padding is different between the two platforms. I've tried encrypting the same string in Java and JavaScript,

Encrypt text in Java using RSA algorithm

Guy Needham I am trying to use RSA encryption in Java. I am generating a public key and using it to encrypt text. My problem is that when I enter the same text and the same key twice, the encryption results are different. This means that I cannot use encryptio

rsa encryption and decryption of images using Java NetBeans

Sofian Mujer I'm developing an application that can encrypt and decrypt images (specific choices) using the RSA algorithm, everything works fine, but some pixels are behaving strangely, and I don't understand why! I use the same parameters to encrypt/decrypt a

Encrypt and decrypt large files using rsa in Java

Prajwal Rai I am using the RSA algorithm to encrypt and decrypt files whose size exceeds the size of the rsa key. In the code below for encryption, I am reading the file content in chunks and converting it to ciphertext. The block size is 32 bytes. FileInputSt

Encrypt and decrypt large strings in Java using RSA

Sergio of Rus: I am trying to implement PKI. I want to encrypt large strings using RSA in Java without bouncy castle. The problem I get is that the data must not exceed 117 bytes. I try to find a solution that fails. I am new to this encryption. Please help me

Export RSA key object to XML using Java

dvl: I have successfully run RSA encryption/decryption in Java. This is how I generate the key. ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(path)); KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg

Problems with encryption and decryption using RSA on JAVA

Baltaza: So I'm trying to encrypt a file that is created when the user types, and after encryption I want to decrypt the file. Both the user created file and the encrypted file are fine, but when I open the encrypted file, I think it's blank because it has som

Problems with encryption and decryption using RSA on JAVA

Baltaza: So I'm trying to encrypt a file that is created when the user types, and after encryption I want to decrypt the file. Both the user created file and the encrypted file are fine, but when I open the encrypted file, I think it's blank because it has som

rsa encryption and decryption of images using Java NetBeans

Sofian Mujer I'm developing an application that can encrypt and decrypt images (specific choices) using the RSA algorithm, everything works fine, but some pixels are behaving strangely, and I don't understand why! I use the same parameters to encrypt/decrypt a

Convert Java code to C# using RSA

username I am trying to convert this code: /** * Create a new PublicKey from encoded X.509 data */ public static PublicKey decodePublicKey(byte[] par0ArrayOfByte) { try { X509EncodedKeySpec var1 = new X509EncodedKeySpec(par0ArrayOfByte);

How to log into Java Card using RSA?

Jay It took me about a week to write the 2048 RSA Sign algorithm for my Java card. There are too many problems like sending and receiving a lot of bytes and so on. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

Encrypt text in Java using RSA algorithm

Guy Needham I am trying to use RSA encryption in Java. I am generating a public key and using it to encrypt text. My problem is that when I enter the same text and the same key twice, the encryption results are different. This means that I cannot use encryptio

I can't decode my own RSA message! (using Java)

Bubloo 7: So I want to use RSA encryption to encrypt some information for me, but when done it sometimes fails to decode. Here is my code: import java.math.BigInteger; public class rsa_practice { public static void main(String[] args) { BigIntege

Providing value to tags in RSA-OAEP encryption using Java

Will: I am trying to implement RSA-OAEP encryption using Java. I understand this requires labels, which are empty strings by default. How can I change the value of the label using the built-in class and provide the selected value? Maarten Bodewes: As I suggest

Decrypt OpenSSL PEM encoded RSA private key using Java?

Edge software I have an encrypted private key and know the passphrase. I need to decrypt it using Java library. However, I'd rather not use BouncyCastle unless there is no other option. From previous experience, there are too many changes and not enough docume

Simple RSA encryption using Java's built-in library

node js The requirements are: Prime numbers p and q should be at least 1024 bits The difference between two prime numbers should be greater than 2^512(for safety) Q: What I want to know is that I specify the sum of the bit lengthspandqalsoSecureRandomgenerate

Simple RSA encryption using Java's built-in library

node js The requirements are: Prime numbers p and q should be at least 1024 bits The difference between two prime numbers should be greater than 2^512(for safety) Q: What I want to know is that I specify the sum of the bit lengthspandqalsoSecureRandomgenerate