Introduction to RSA in Java

The RSA (Rivest–Shamir–Adleman) is an asymmetric cryptography algorithm based on a pair of keys: Public and Private. The public key could be shared by everyone, it is used for encrypting the data. The private key should be kept private as the name said. It is used for decrypting the data.

The acronym RSA comes from the surnames of Ron Rivest, Adi Shamir, and Leonard Adleman, who publicly described the algorithm in 1977.

In this article, we are going to present how to generate, save and use RSA keys in Java.

2. RSA Key Pair

Let's start with generating RSA keys, using pure Java.

Rsa private key

Note that, doFinal(. ) returns bytes array, so in order to present the result we could use Base64 responsible for converting bytes into a string.

4.2. Decrypting

Let's check if our encrypted string is correct. We will do it by decrypting it using the private.key .

String with a new Cipher instance but in this case dedicated for the private certificate:

To decrypt we also use the doFinal(. ) method.

Cipher decryptCipher = Cipher.getInstance("RSA"); decryptCipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedMessageBytes = decryptCipher.doFinal(encryptedMsg); String decryptedMessage = new String(decryptedMessageBytes, StandardCharsets.UTF_8); System.out.println(decryptedMessage); 
FrontBackend.com 

The output confirms that certificates are generated correctly.

5. Encrypt and decrypt files

Encrypting and decrypting files using our private/public RSA keys are similar to encrypting/decrypting strings but in this case, the first step will be reading bytes from a file.

byte[] fileBytes = Files.readAllBytes(Paths.get("/tmp/file.to.encrypt")); 

When we have byte array we could do steps like in the previous point:

Cipher encryptFileCipher = Cipher.getInstance("RSA"); encryptFileCipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] encryptedFile = encryptCipher.doFinal(fileBytes); Cipher decryptFileCipher = Cipher.getInstance("RSA"); decryptFileCipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] decryptedFileBytes = decryptCipher.doFinal(encryptedFile); 

6. Conclusion

In this short tutorial, we presented how to start working on RSA keys in Java. How to create them and use them for encryption and decryption of the data.

As usual, the source code is available on our GitHub.