fishhf.com

Java RSA Tutorial

Introduction

RSA is an algorithm for doing asymmetric encryption that involves a public key and a private key.
A public key is used for encryption while a private is used for decryption. Because of that, anyone that has the public key can create something secret, that only some guy that has the secret private key can view what it is.

Java already provides an API for using RSA in your own programs.
Let's get started!

Initialization

The following code will generate a random RSA key pair that is 512bits:

KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);
KeyPair kp = kpg.genKeyPair();
publicKey = kp.getPublic();
privateKey = kp.getPrivate();


Encryption

The following code will encrypt byte[] data into cipherData using the publicKey, which was generated using the code above.

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);

byte[] cipherData = cipher.doFinal(data);
return cipherData;


Decryption

Similarly, we can decrypt data using our generated privateKey, that was encrypted using the publicKey above.

Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);

byte[] cipherData = cipher.doFinal(data);
return cipherData;


Conclusion

Because this tutorial is made for experienced Java programmers, so it is kept as short as possible. Anyway, it is actually that easy to use RSA in Java! :P

Written by fish

New