[Go to site: main page, start]

0% found this document useful (0 votes)
41 views16 pages

RSA Encryption in Java and Python

The document describes how to encrypt a string in Java using RSA encryption and decrypt it in Python. It explains how to generate an RSA key pair using OpenSSL, encrypt a string in Java using the public key, and decrypt it in Python using the private key. Code snippets are provided for encrypting a string in Java by loading the public key, initializing a Cipher, and encrypting the bytes. Code is also provided for decrypting in Python by loading the private key, base64 decoding the encrypted string, initializing a Cipher, and decrypting the bytes.

Uploaded by

Yochay Rofe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views16 pages

RSA Encryption in Java and Python

The document describes how to encrypt a string in Java using RSA encryption and decrypt it in Python. It explains how to generate an RSA key pair using OpenSSL, encrypt a string in Java using the public key, and decrypt it in Python using the private key. Code snippets are provided for encrypting a string in Java by loading the public key, initializing a Cipher, and encrypting the bytes. Code is also provided for decrypting in Python by loading the private key, base64 decoding the encrypted string, initializing a Cipher, and decrypting the bytes.

Uploaded by

Yochay Rofe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Skip to content

The Tech Check


Tech from one dev to another

 Data Science
 Tech
 General
 Proof of Concepts (POCs)
 About Me / Products
 Must Watch Videos

Search

Trending Now

 I made a website which tells if you’re wearing a mask or not – without machine

learning

 Free apps vs. Paid apps

 Binary Search Tree Implementation in Java

 Querying Hive Tables From a Spring Boot App

 out() vs. outE() – JanusGraph and Gremlin

 Getting Started With JanusGraph

 I made a website which tells if you’re wearing a mask or not – without machine

learning

 Free apps vs. Paid apps

 Binary Search Tree Implementation in Java

 Querying Hive Tables From a Spring Boot App

 out() vs. outE() – JanusGraph and Gremlin

 Getting Started With JanusGraph


Home>>Tech>>How to encrypt a string in Java using RSA and decrypt it in Python
TECH

How to encrypt a string in Java using RSA and


decrypt it in Python
Sunny SrinidhiNovember 7, 20194996 Views0
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 [Link] 2048
The command above will create a private key file – [Link]. 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 [Link] -outform PEM -pubout -out [Link]

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

Encryption with Java


Now that we have a key pair, let’s start encrypting our message. I have selected a very
specific message to encrypt, and it makes a lot of sense:
String dataToBeEncrypted = "Some random words in no particular order.";

As you can see, I can’t really send out this very sensitive message over public internet. So
let’s encrypt it. For that though, we need to first convert this string into a byte array:
byte[] bytesToBeEncrypted = [Link]();

Next, we need to read the public key file into our Java code. We have to clean up the
public key data though. Let’s see why that is. If you open up your public key file (cat it or
open it in a text editor), you’ll see something like this:
-----BEGIN PUBLIC KEY-----

MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAut9/U5lR6UN/02YX79qv

iuKd2AQwEBiJMt15djesw6wgR/1jWJr/ZUM+XPIVkshHoPkhh2JhnqvEZt3VEYeY

xy88xRksZqqEmgCwEX4gVsAWrGCTJ7U+LyuSYpavbHGcUkA4rIh9XCkgphvXYod2

cnyU0XQJ1jRLvTD4EozTtyA1wKRxtATj/2o+swH3mnEW1y4weEoLmfcJ844tQU/l

3DIxQh+XWhzdsqo8kX+Za8RAFbH2xbK+yG6U3it5TrSwmsSSUh2ZGlcGiN76C/42

6rTWS0lj5kYEUYKqON782ui8K2hGj9ylpL6lohosH8lsTKZvRK0PCs698QKrlc/M

bwIDAQAB

-----END PUBLIC KEY-----


As you can see, there’s some text in there, and some new line characters, and some
dashes. You need to remove all that and have only the key. For that, once we have the
file’s content into a variable, we’ll replace all the unwanted text with some empty strings.
For that, we’ll use the following code snippet:
public static final String NEW_LINE_CHARACTER = "\n";

public static final String PUBLIC_KEY_START_KEY_STRING = "-----BEGIN PUBLIC


KEY-----";

public static final String PUBLIC_KEY_END_KEY_STRING = "-----END PUBLIC KEY-----";

public static final String EMPTY_STRING = "";

File keyFile = new File(publicKeyPath);

byte[] publicKey = [Link]([Link]());

String keyString = new String(publicKey);

keyString = [Link](NEW_LINE_CHARACTER, EMPTY_STRING)

.replaceAll(PUBLIC_KEY_START_KEY_STRING, EMPTY_STRING)

.replaceAll(PUBLIC_KEY_END_KEY_STRING, EMPTY_STRING);

publicKey = [Link]();

If you check the value of the publicKey variable now, you should see something like this:
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAut9/U5lR6UN/
02YX79qviuKd2AQwEBiJMt15djesw6wgR/1jWJr/
ZUM+XPIVkshHoPkhh2JhnqvEZt3VEYeYxy88xRksZqqEmgCwEX4gVsAWrGCTJ7U+LyuSYpavbHGcUkA4rI
h9XCkgphvXYod2cnyU0XQJ1jRLvTD4EozTtyA1wKRxtATj/2o+swH3mnEW1y4weEoLmfcJ844tQU/
l3DIxQh+XWhzdsqo8kX+Za8RAFbH2xbK+yG6U3it5TrSwmsSSUh2ZGlcGiN76C/
426rTWS0lj5kYEUYKqON782ui8K2hGj9ylpL6lohosH8lsTKZvRK0PCs698QKrlc/MbwIDAQAB

Right, the public key is set. Next, we need to do some magic with the Java security
package and generate an instance of the Cipher class. For this, we first need to create an
instance of the RSA key using the KeyFactory class. Then, initialise a Cipher with that
instance of the Key class. This is the code for that:
Key generatePublic = [Link](KEY_FACTORY_INSTANCE_TYPE).

generatePublic(new
X509EncodedKeySpec([Link]().decode(publicKey)));

Cipher cipherInstance = [Link](CIPHER_INSTANCE_TYPE);

[Link](1, generatePublic);

We now have everything we need to encrypt our super secret message. We now only
have to call one method on the cipherInstance to encrypt our message:
[Link](bytesToBeEncrypted);

That’s it. You’ll have an encrypted byte array now. Here is the complete logic for
encrypting a byte array:
private byte[] encrypt(byte[] inputByteArray) throws Throwable {

File keyFile = new File(publicKeyPath);

byte[] publicKey = [Link]([Link]());

String keyString = new String(publicKey);

keyString = [Link](NEW_LINE_CHARACTER, EMPTY_STRING)

.replaceAll(PUBLIC_KEY_START_KEY_STRING, EMPTY_STRING)

.replaceAll(PUBLIC_KEY_END_KEY_STRING, EMPTY_STRING);

publicKey = [Link]();

Key generatePublic = [Link](KEY_FACTORY_INSTANCE_TYPE).


generatePublic(new
X509EncodedKeySpec([Link]().decode(publicKey)));

Cipher cipherInstance = [Link](CIPHER_INSTANCE_TYPE);

[Link](1, generatePublic);

return [Link](inputByteArray);

But we’re not done yet. We still need to encode this encrypted byte array to base64. For
that, we’ll just the Base64 class that ships in the [Link].base64 package:
String encryptedString = [Link]().encodeToString(encryptedByteArray);

Finally, we’re done with the encryption. The encryptedString variable is what you’re


looking for. If you log the variable, you’ll see something like this:
s59uQfRCsCCQXi4mb02O1nfvFb0nvSulVP8Ve71rMHZoFYA0hXOEqVkgYvBT1ZWrfQhY2453B8eG929zqX
WCRSMSAB+MbSQaun6rChuGAg8laxw89nN7/KoksuN45VvCFYxd18tAu915zOVG/
yvYocpPW4xXcyAWDaD7j24XEwJFAU672haBaTPbEsoobfWWyQqfyUHDA+iCVSSMOl5zqx3MTj4vOG2SfCD
25cxeH60AtI01OzMNW0XfAdQgegiQ27lKusMdK+7478g+n6gXSSzARatTotk7C5xR1DAzvIJvWLNIbKphT
lykoB0u+/DXaeJQxD4/UCEbnwFoXnYVyQ==

This is your encrypted text. You can pass this text to anybody you want and it’ll not make
any sense to anybody until they decryt it. So let’s see how we can do that in Python.

Decryption with Python


Now that we have the encrypted text, let’s move over to Python where we need to
decrypt this. But before we can start the decryption, we need to import some stuff in our
Python code:
from [Link] import RSA

from [Link] import PKCS1_v1_5

from base64 import b64decode

Once we have these packages imported, we need to read the private key from the file
and create an RSA key instance. Once we read the file, we need to get rid of the extra
text here as well, similar to what we did in Java. The following piece of code takes care of
all that:
key = open("/path/to/keyPair/[Link]").read()

key = [Link]("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA


PRIVATE KEY-----", "").replace("\n", "")

key = b64decode(key)

key = [Link](key)

Make sure you change the path to your private key file in the first statement. Once we
have this, we’ll store the encrypted text we got from Java into a variable. In the real
world, you’d use HTTP or some sort of RPC to get the encrypted text to your Python
code. We’ll just copy-paste it for now:
inputString =
'RyGR3vB6v8hl3ITN5H9tm3sxNQZnZGxOWMIL0V8s7VIQZgUhGonRAVnDKe5KHH9aB8KynoLaLUn5/
baNqfC9EiynOLqS7CxNPTY28UT1kxchGQ/
YX3yaw7AUBZeNmEKUBD5JOQD3VNaKbrgosnhaVK6bNzjlGyyhZrDpBlx2tX+h057b0ecZTPHHhJUwkjAmB
MsSTwTUJqwzzCNARDpHCS4o2qt23XYJNmw5UidPJ2JURt45YUEUovPmzDSdmS/
5V9fxbcCMpdwZJa5d2tLhzpcjdmUM6tiQNu4DUqwF4ICYxZmX9Za74Niu9fTTy4+C0jY1uUd8o8Y9g0tva
mCBwQ=='

Next, we’ll create an instance of the Cipher class using the key, again similar to what we
did in Java:
cipher = PKCS1_v1_5.new(key)

Next, we need to base64 decode the input string. If you remember, we had base64
encoded the encrypted text in Java. So we have to do the same thing here, but in the
reverse order. Once we have the decoded string, we’ll use the Cipher instance we
created to decrypt the message. We’ll use one statement to both decode the string, and
then decrypt it:
plainText = [Link](b64decode(inputString), "Error decrypting the input
string!")

And that’s it. If you print the variable plainText now, you should get back your original
message:
print(plainText)

And the output will be:


b'Some random words in no particular order.'
Let me know if you face any issues here or want any help with this stuff. And as always,
you can checkout the complete project over at Github. The resources folder in the Java
project in the repository has the Python code which you can use to decrypt the message.

About the author

Sunny Srinidhi
Coding, reading, sleeping, listening, watching, potato. INDIAN.
“If you don’t have time to do it right, when will you have time to do it over?” – John
Wooden

See author's posts

Share this:

 Twitter

 Facebook


Like this:

Loading...
Related

Encrypting and Decrypting data in MongoDB with a SpringBoot project


January 8, 2020
In "Tech"
Removing stop words in Java as part of data cleaning in Artificial Intelligence
February 5, 2020
In "Data Science"

HashMap implementation in Java


January 3, 2020
In "Tech"

Related tags : decrypt string in rsa in pythonencrypt string using rsa in javagenerate rsa key
pair using opensshjava encryption rsaopensshpython encryption and decryptionpython rsa
decryptionpython rsa encryptionrsarsa decryptionrsa decryption in pythonrsa encryptionrsa
encryption in pythonrsa encryption javarsa key pairstring encryption and decryption in rsa in
java and pythonstring encryption in rsa in java
Share:

Previous Post
Fit vs. Transform in SciKit libraries for Machine Learning
Next Post
Null Hypothesis and the P-Value

Related Articles

DAT
A SCIENCETECH

Getting started with Apache Kafka Streams


DAT
A SCIENCETECH

Put data to Amazon Kinesis Firehose delivery stream using Spring Boot

DAT
A SCIENCETECH

Querying Hive Tables From a Spring Boot App


TEC
H

Overriding Spring Boot properties in Amazon Lambda

DAT
A SCIENCETECH

Getting Started with Apache Drill and MongoDB

Leave a Reply
Your email address will not be published. Required fields are marked *
Comment

Name *

Email *

Website

 Notify me of follow-up comments by email.

 Notify me of new posts by email.

Post Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

My Upcoming O’Reilly Live Online Courses

Next Course:

Getting Started With Amazon Aurora

Dates:
 September 3rd, 2021

 December 10th, 2021


I’m An AWS Community Builder!

Search
Search for:
Follow Me

 Twitter
 LinkedIn
 Medium
 GitHub

Subscribe To Blog Via Email

Enter your email address to subscribe to this blog and receive notifications of new posts
by email.

Join 20 other subscribers

Email Address

Subscribe

Recent Posts
 Querying Hive Tables From A Spring Boot App
 Out() Vs. OutE() – JanusGraph And Gremlin
 Getting Started With JanusGraph
 I Made A Website Which Tells If You’re Wearing A Mask Or Not – Without
Machine Learning
 Free Apps Vs. Paid Apps

Categories

 Data Science (44)
 General (4)
 Rants (6)
 Smartphones (1)
 Tech (72)

Archives

 June 2021
 March 2021
 February 2021
 January 2021
 December 2020
 October 2020
 August 2020
 July 2020
 June 2020
 May 2020
 April 2020
 March 2020
 February 2020
 January 2020
 December 2019
 November 2019
 October 2019
 September 2019
 June 2019
 May 2019
 April 2019
 November 2018
 August 2018
 July 2018
 August 2017
 July 2017
 June 2017
 April 2017
 March 2017
 February 2017
 January 2017
 September 2016
 August 2016
 March 2016

Tags

AI   AMAZON   APACHE   APACHE KAFKA   APACHE SPARK   ARTIFICIAL

INTELLIGENCE   AWS   BEST PRACTICES   BIG

DATA   BIGDATA   CODING   DATASCIENCE   DATA


SCIENCE   DATA STRUCTURE IMPLEMENTATION IN JAVA   DATA
STRUCTURES   FEATURE REDUCTION   FEATURE SELECTION   JAVA   JAVA

DATA STRUCTURES   JAVA DATA STRUCTURES IMPLEMENTATION   JAVA

LINKED LIST EXAMPLE   JAVA LINKED LIST

IMPLEMENTATION   JAVASCRIPT   KAFKA   LINKEDLIST   LINKED LIST IN JAVA   LINKED

LISTS   MACHINE LEARNING   MACHINE LEARNING

MODELS   ML   NATURAL LANGUAGE

PROCESSING   NLP   PHP   PROGRAMMING   PYTHON


SCIKIT   PYTHON SKLEARN   RANTS   SCIKIT   SCIKIT
LEARN   SKLEARN   SPRING   SPRING

BOOT   TECH   TECHNOLOGY   THE FASTTEXT SERIES







Page address saved

Common questions

Powered by AI

To encrypt a string in Java using RSA and decrypt it in Python, follow the steps outlined below: 1. Generate a RSA key pair using OpenSSL. First, a private key is created with the command `openssl genrsa -out privateKey.pem 2048`. Then, generate a corresponding public key with `openssl rsa -in privateKey.pem -outform PEM -pubout -out public.pem` . 2. Read and clean the public key file in Java by removing headers, footers, and newline characters, then convert the key into a usable format . 3. Convert the string data into a byte array and use Java's KeyFactory and Cipher classes to encrypt the byte array, producing the encrypted byte array which is then base64 encoded . 4. Transfer the base64 encoded string to Python. 5. In Python, import necessary classes (`RSA`, `PKCS1_v1_5`, `b64decode`) and read the private key, cleaning it similarly to the public key . 6. Base64 decode the received encrypted string and use the decrypted key with PKCS1 v1.5 padding to decrypt the data in Python .

The key differences involve language-specific libraries and methods used for encryption and decryption. In Java, the process uses classes like KeyFactory and Cipher from the Java security package to read and clean the public key, convert it using Key specifications, and encrypt the data. The encrypted data is then base64 encoded for transfer . In Python, decryption involves reading and cleaning the private key, then creating an RSA key instance using the `Crypto.PublicKey` and `Crypto.Cipher` libraries. PKCS1_v1_5 padding is applied during decryption, and the base64 encoded encrypted data is first decoded . Both processes require careful management of Key formats and transformations specific to each language's cryptographic library.

Base64 encoding is used to encode binary data into an ASCII string format, making it suitable for transfer over media that are designed to deal with textual data. In the encryption process described, once data is encrypted into a byte array, it is subsequently encoded into a base64 string to convert the data into a textual representation that can be easily transmitted across environments like networks or stored in text files . During decryption in Python, the encoded data is first converted back into the binary form by base64 decoding before it is decrypted with the private key, allowing the original message to be reconstructed .

The `Cipher` class in Java is central to handling the encryption process. It is initialized with the RSA public key and used to perform the encryption of data into an encrypted byte array using the `doFinal` method . In Python, the equivalent function is found within the `Crypto.Cipher.PKCS1_v1_5` module, which provides the `decrypt` method to process the base64 decoded input and retrieve the original plaintext. While both handle encryption-decryption, Java emphasizes explicit initialization of an RSA Key object from a public key, whereas Python achieves similar functionality by importing an RSA instance directly within its cryptographic library .

Removing headers and new lines from the RSA key strings is necessary for compatibility with cryptographic libraries in both Java and Python, which require keys to be in a specific format for processing. Headers like "-----BEGIN PUBLIC KEY-----" and newline characters are part of PEM encoding, which is human-readable but not directly usable for cryptographic operations. Cleaning these formats into a continuous base64 encoded string allows the cryptographic functions, such as `KeyFactory` in Java and `RSA.importKey` in Python, to correctly decode and instantiate the key objects necessary for encryption or decryption operations .

Using base64 encoding in data transfer provides a means to represent binary data as ASCII string format, which is advantageous as it standardizes the data exchange process across different programming environments and networks, mitigating encoding-related issues . It ensures that data integrity is maintained when sending binary encrypted data across platforms. As illustrated, base64 encoding in Java produces a consistent format that Python can decode and understand, ensuring seamless encryption-decryption operations, maintaining data confidentiality and usability regardless of specific playform or language data handling mechanisms . This promotes interoperability and reduces errors during data transfer.

Several challenges in transferring encrypted data between Java and Python include differences in handling data types and encoding schemes across languages. String encoding transformations, like converting the encrypted byte array to base64, mitigate these challenges by producing a consistent text format that can be easily read across environments . Differing key management practices require careful cleaning and transformation of key formats, such as removing headers and line breaks, to ensure compatibility. Utilizing common cryptographic standards (RSA, PKCS1 v1.5, base64) aids in maintaining consistency and avoid discrepancies in encryption-decryption operations .

Key pair management is crucial in RSA encryption as it ensures the confidentiality and integrity of the encrypted data. The public key is distributed for encrypting data, while the private key, which must be kept secret, is used for decryption . Mismanagement of the private key, such as exposure or loss, can lead to unauthorized decryption. Therefore, secure generation, storage, and use of these keys are essential to maintaining robust security. Tools like OpenSSL aid in generating key pairs, but proper handling includes ensuring private keys remain confidential and public keys are correctly distributed and used . Key management practices must include regular auditing and secure infrastructure to prevent key misuse or compromise.

RSA encryption is considered secure primarily due to the mathematical complexity involved in factoring large numbers, a key part of RSA. The security relies on the difficulty of factoring the product of two large prime numbers, which forms the foundation of the RSA algorithm . Public keys are used to encrypt data, ensuring that only the corresponding private key, which is kept secret, can decrypt it, thus maintaining confidentiality. This separation means data can be transmitted securely over public networks, as only the intended recipient with the private key can decrypt it .

OpenSSL is instrumental in generating RSA key pairs necessary to perform encryption and decryption. By using commands such as `openssl genrsa` and `openssl rsa`, one can quickly produce secure keys, saving the time and complexity involved in generating them programmatically within an application . This tool is widely trusted for cryptographic operations, providing a reliable and standardized way to ensure key generation aligns with industry standards, which is crucial for maintaining security across different environments and languages, as seen in the document where keys are used across both Java and Python .

You might also like