DEV Community

Cover image for How to encrypt a string in Java using RSA and decrypt it in Python

How to encrypt a string in Java using RSA and decrypt it in Python

contactsunny profile image Sunny Srinidhi ・2 min read

Recently at work, I was tasked to write a Java program which would encrypt a sensitive string using the RSA encryption algorithm. The encrypted string would then be passed on to a client over public internet. The client would then use the private key to decrypt the message. But the client is written in Python. So I have to make sure the encryption and decryption wok as expected. And as always, I wrote POCs for both. And here, I’m going to document that.

Creating the key pair

Before we can start the encryption, we need to have a key pair. A key pair will have a public key and a private key. The public key, as the name suggests, is public. You can share it with anybody who wishes to send you an encrypted text. They will encrypt the original text using this public key, and send over the encrypted text to you. You can then use the private key that only you have to decrypt the text. You’ll get the original message back this way.

So to start the process, we need to first generate the key pair. For this, we’ll use the very popular tool, openssh. You’ll need a terminal for this though. So open up your terminal and run the following command:

openssl genrsa -out privateKey.pem 2048

The command above will create a private key file – privateKey.pem. You can rename this to whatever you want, or you can change the value of the -out option in the command to create the file with any name you want.

Once you have this private key, we need to create a public key that goes with this. For this, we’ll run another command (given below), which will generate a public key. Again, you can change the value of the option -out to name the file whatever you want.

openssl rsa -in privateKey.pem -outform PEM -pubout -out public.pem

That’s it. You now have a key pair which we can use in our code.

Please continue reading this post on my personal blog.

Discussion (0)

Editor guide