December 6, 2017

Asymmetric Encryption with RSA and OAEP (Optimal Asymmetric Encryption Padding)

The preferred padding with RSA cipher algorithm is OAEP (Optimal Asymmetric Encryption Padding).

Java Example:

First generate public and private RSA keys with some length, here we use 2048 bits.

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
keyGen.initialize(2048, new SecureRandom());
KeyPair pair = keyGen.generateKeyPair();
PrivateKey privateKey = pair.getPrivate();
PublicKey publicKey = pair.getPublic();

Then we we encrypt our plaintext

byte[] plaintext = "Secret goes here".getBytes(StandardCharsets.UTF_8);

// While using asymmetric ciphers, use ECB as the mode of operation, 
// which essentially is a hack behind-the-scenes, meaning ignore this value.
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] ciphertext = cipher.doFinal(plaintext);

Then we can print our ciphertext with Base64 encoding

String encoded = new String(Base64.getEncoder().encode(ciphertext), StandardCharsets.UTF_8);
System.out.println("Encrypted : " + encoded);

And finally decrypt it

// While using asymmetric ciphers, use ECB as the mode of operation, 
// which essentially is a hack behind-the-scenes, meaning ignore this value.
Cipher cipher = Cipher.getInstance("RSA/ECB/OAEPWithSHA-512AndMGF1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] plaintext = cipher.doFinal(ciphertext); 

System.out.println("Decrypted : " + new String(plaintext, StandardCharsets.UTF_8));

No comments: