Transmitting any sensitive information in a plain-text from any client such as Browser or Android client to server is vulnerable to security and hence encryption is a must. In this article, we will learn how to perform RSA encryption in Javascript and decrypt in Java. At the client-side, we will build a sample login form with HTML and Javascript with Angular JS and while submitting the login info to the server, we will RSA encrypt the password. At the server-side, we have  Spring MVC based app that will decrypt the encrypted password and perform authentication.
In real scenarios, RSA is not the perfect match for this kind of password encryption. RSA encryption is mostly used when there are 2 different endpoints are involved such as VPN client and server, SSH, etc. and performance-wise RSA encryption is slower. With every doubling of the RSA key length, decryption is 6-7 times slower. This use case is best fitted with AES encryption. We are creating this sample app only to demonstrate the interoperability of RSA encryption between Javascript and Java.
You can visit my previous article for AES encryption in Javascript and decryption in Java.
What is RSA Encryption
RSA is an asymmetric encryption technique that is mostly used when there are 2 different endpoints that are involved such as VPN client and server, SSH, etc. It uses two different keys as public and private keys. Here, you can encrypt sensitive information with a public key and a matching private key is used to decrypt the same. Â The private key is generated in PKCS#8 format and the public key is generated in X.509 format.
I assume that you already know about RSA and here we are just implementing a use case of it. You can follow my previous article to learn RSA encryption in Java.
RSA Public and Private Key
In RSA encryption, we encrypt sensitive information with a public key and a matching private key is used to decrypt the same. Let us first generate those keys programmatically in Java. You can also use this online RSA tool to generate these keys.
We can use the factory method to generate these keys using KeyPairGenerator. For the demo purpose, we are using a key size of 1024 but this is secured and hence it is suggested to use at least 2048 bits of key size but remember that with every doubling of the RSA key length, decryption is 6-7 times slower.
By default, the private key is generated in PKCS#8 format and the public key is generated in X.509 format. Here, we are doing a BASE64 encoding of the keys so that the public key can be easily shared with any client. Once, the key is generated, we will hardcode the Base64 encoded public key in JS file and use the private key at server-side.
import java.security.*; import java.util.Base64; public class RSAKeyPairGenerator { Â Â private PrivateKey privateKey; Â Â private PublicKey publicKey; Â Â public RSAKeyPairGenerator() throws NoSuchAlgorithmException { Â Â Â Â KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); Â Â Â Â keyGen.initialize(1024); Â Â Â Â KeyPair pair = keyGen.generateKeyPair(); Â Â Â Â this.privateKey = pair.getPrivate(); Â Â Â Â this.publicKey = pair.getPublic(); Â Â } Â Â public PrivateKey getPrivateKey() { Â Â Â Â return privateKey; Â Â } Â Â public PublicKey getPublicKey() { Â Â Â Â return publicKey; Â Â } Â Â public static void main(String[] args) throws NoSuchAlgorithmException { Â Â Â Â RSAKeyPairGenerator keyPairGenerator = new RSAKeyPairGenerator(); Â Â Â Â System.out.println(String.format("Public Key : %s", Base64.getEncoder().encodeToString(keyPairGenerator.getPublicKey().getEncoded()))); Â Â Â Â System.out.println(String.format("Private Key : %s", Base64.getEncoder().encodeToString(keyPairGenerator.getPrivateKey().getEncoded()))); Â Â } }
Below is the output. We have copied the same keys at client and server side.
Below is the final project structure that we will be building. Now, let us go into the implementation:
RSA Encryption in Javascript
Now, we have our public keys generated. We will use this public key in javascript for the RSA encryption. To perform RSA encryption at client-side, we will be using JSEncrypt. It is an open-source library to perform different encryption in Javascript.
Let us implement our HTML first. We have integrated Angular JS in it and included JS library for bootstrap and JSEncrypt.
index.html<!DOCTYPE HTML> <html xmlns:th="http://www.w3.org/1999/xhtml" xmlns="http://www.w3.org/1999/html"> <head> Â Â <title>Demo</title> Â Â <meta charset="utf-8" /> Â Â <meta name="viewport" content="width=device-width, initial-scale=1"/> Â Â <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/> Â Â <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> Â Â <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular.min.js"></script> Â Â <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js" async></script> Â Â <script src="https://cdnjs.cloudflare.com/ajax/libs/jsencrypt/2.3.1/jsencrypt.min.js" async></script> Â Â <script src="/loginCtrl.js"></script> </head> <body ng-app="demoApp" ng-controller="loginController"> <div class="container"> Â Â <div class="row content"> Â Â Â Â <div class="col-sm-6"> Â Â Â Â Â Â <div class="row" style="margin-top: 20px"> Â Â Â Â Â Â Â Â <div class="col-lg-12"> Â Â Â Â Â Â Â Â Â Â <form> Â Â Â Â Â Â Â Â Â Â Â Â <div class="form-group"> Â Â Â Â Â Â Â Â Â Â Â Â Â Â <label for="username">Username:</label> Â Â Â Â Â Â Â Â Â Â Â Â Â Â <input type="text" class="form-control" placeholder="Username" id="username" name="username" ng-model="userName"> Â Â Â Â Â Â Â Â Â Â Â Â </div> Â Â Â Â Â Â Â Â Â Â Â Â <div class="form-group"> Â Â Â Â Â Â Â Â Â Â Â Â Â Â <label for="pwd">Password:</label> Â Â Â Â Â Â Â Â Â Â Â Â Â Â <input type="password" class="form-control" placeholder="Enter password" id="pwd" name="pwd" ng-model="password"> Â Â Â Â Â Â Â Â Â Â Â Â </div> Â Â Â Â Â Â Â Â Â Â Â Â <button type="button" class="btn btn-primary" ng-click="decrypt()">Decrypt</button> Â Â Â Â Â Â Â Â Â Â </form> Â Â Â Â Â Â Â Â </div> Â Â Â Â Â Â </div> Â Â Â Â </div> Â Â </div> </div> </body> </html>
Below is the Angular component implementation. It has the RSA encryption implementation in Javascript using the library JSEncrypt. We are first encrypting the plain-text passwword before sending it to server.
loginCtrl.jsvar app = angular.module('demoApp', []); app.controller('loginController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {   $rootScope.authenticated = false;    $scope.headingTitle = 'Login to get started.';   let publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCz1zqQHtHvKczHh58ePiRNgOyiHEx6lZDPlvwBTaHmkNlQyyJ06SIlMU1pmGKxILjT7n06nxG7LlFVUN5MkW/jwF39/+drkHM5B0kh+hPQygFjRq81yxvLwolt+Vq7h+CTU0Z1wkFABcTeQQldZkJlTpyx0c3+jq0o47wIFjq5fwIDAQAB";   $scope.decrypt = function(){     if(!$scope.userName || !$scope.password){       alert("Missing required fields.");       return;     }     let RSAEncrypt = new JSEncrypt();     RSAEncrypt.setPublicKey(publicKey);     let encryptedPass = RSAEncrypt.encrypt($scope.password);     const user = {       "userName": $scope.userName,       "password": encryptedPass     };     $http.post('/decrypt', user).then(       function (response){            alert("Decrypted Password - " + response.data.password);       },       function(errResponse) {         alert(errResponse.status + ':' + errResponse.statusText);         return $q.reject(errResponse);       });    }; }]);
RSA Decryption in Java
We have RSAUtil.java class implemented that handles all the RSA encryption and decryption in Java. Let us first define the controller class that handles the HTTP request.
For the demo purpose, the implementation only decrypts the password and sends it back to the client.
@Controller public class WelcomeController {    private static final Logger LOGGER = LoggerFactory.getLogger(WelcomeController.class);    @Autowired   private Environment environment;    @RequestMapping(value={"/home"}, method = RequestMethod.GET)   public String loginPage(){      return "index";   }   @RequestMapping(value={"/decrypt"}, method = RequestMethod.POST)   public @ResponseBody Credentials decrypt(@RequestBody Credentials credentials) throws InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, IllegalBlockSizeException, NoSuchPaddingException {     String plainTextPass = RSAUtil.decrypt(credentials.getPassword(), environment.getProperty("rsa.private.key"));     credentials.setPassword(plainTextPass);      return credentials;   } }
Below is the decrypt method that accepts RSA encrypted string and Base64 encoded RSA private key for decryption.
public static String decrypt(String data, String base64PrivateKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Â Â Â Â return decrypt(Base64.getDecoder().decode(data.getBytes()), getPrivateKey(base64PrivateKey)); Â Â }
Below is the complete implementation of RSAUtil class. It has the method defined for RSA encryption and decryption. As we discussed above the public key generated is in X.509 format and we use public key for encryption. Hence, we need X509EncodedKeySpec class to convert it again to RSA public key.
For decryption we will be using private key and we discussed above that the private key is generated in PKCS#8 format.
public class RSAUtil { Â Â private static String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCz1zqQHtHvKczHh58ePiRNgOyiHEx6lZDPlvwBTaHmkNlQyyJ06SIlMU1pmGKxILjT7n06nxG7LlFVUN5MkW/jwF39/+drkHM5B0kh+hPQygFjRq81yxvLwolt+Vq7h+CTU0Z1wkFABcTeQQldZkJlTpyx0c3+jq0o47wIFjq5fwIDAQAB"; Â Â private static String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALPXOpAe0e8pzMeHnx4+JE2A7KIcTHqVkM+W/AFNoeaQ2VDLInTpIiUxTWmYYrEguNPufTqfEbsuUVVQ3kyRb+PAXf3/52uQczkHSSH6E9DKAWNGrzXLG8vCiW35WruH4JNTRnXCQUAFxN5BCV1mQmVOnLHRzf6OrSjjvAgWOrl/AgMBAAECgYAgA0YHdZUFL7mmIvwuE/2+Vh7JVKRAhfM7ILNHQBx7wHkOqro9eWp8mGQhUeDvitWb1C4yizJK0Znkx/pqQtFZuoatUsggocjXFl86FElQwrBp08DvfKfd0bGgy0VTFQVmCtxiqhpAmC7xmXNZXfBD41rl9CKbFfZw05QC5BoQ0QJBAO7LSku97NgFBJQ+vbmVDonuvgnQjVNb7SnwrcpJHEUAGbaVq1a50jz+s6n39TOagASaW6pcY0uwiygYu6xDnkMCQQDAzIGNKFKomTI6djcOyHfQ1ZXqyDQ3guX6nHhzZnNHFF8ZD3fPyyIRSZ3JvPK5iEzJLhB7FRtyWkGcdXgJTWoVAkBfx9zKGqkYUJLwn2XcPWRygPdq2mMFb5bmPqqGu+KB7rNhoBD0nV4tpwALifCpPSxiLEPeRmZxoqN+dsU4KHsfAkAyQt4fK3zpAQ8MGJdf3jkGEzhC/bBHLHPB8pqgEvxIcnIcOWEVpbIa6aMd3Yk1fuftpnmbbLQ8CnWCUUlau3jFAkEAk6bOZIWhTYRwIZcwBdkpyLlbatQFoTTM3i444YutXt3FrFfaWBxge+eYKId+J4dCrt/EmHhSfWKEzHibf6N5Sg=="; Â Â public static PublicKey getPublicKey(String base64PublicKey){ Â Â Â Â PublicKey publicKey = null; Â Â Â Â try{ Â Â Â Â Â Â X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64.getDecoder().decode(base64PublicKey.getBytes())); Â Â Â Â Â Â KeyFactory keyFactory = KeyFactory.getInstance("RSA"); Â Â Â Â Â Â publicKey = keyFactory.generatePublic(keySpec); Â Â Â Â Â Â return publicKey; Â Â Â Â } catch (NoSuchAlgorithmException e) { Â Â Â Â Â Â e.printStackTrace(); Â Â Â Â } catch (InvalidKeySpecException e) { Â Â Â Â Â Â e.printStackTrace(); Â Â Â Â } Â Â Â Â return publicKey; Â Â } Â Â public static PrivateKey getPrivateKey(String base64PrivateKey){ Â Â Â Â PrivateKey privateKey = null; Â Â Â Â PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.getDecoder().decode(base64PrivateKey.getBytes())); Â Â Â Â KeyFactory keyFactory = null; Â Â Â Â try { Â Â Â Â Â Â keyFactory = KeyFactory.getInstance("RSA"); Â Â Â Â } catch (NoSuchAlgorithmException e) { Â Â Â Â Â Â e.printStackTrace(); Â Â Â Â } Â Â Â Â try { Â Â Â Â Â Â privateKey = keyFactory.generatePrivate(keySpec); Â Â Â Â } catch (InvalidKeySpecException e) { Â Â Â Â Â Â e.printStackTrace(); Â Â Â Â } Â Â Â Â return privateKey; Â Â } Â Â public static byte[] encrypt(String data, String publicKey) throws BadPaddingException, IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, NoSuchAlgorithmException { Â Â Â Â Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); Â Â Â Â cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey)); Â Â Â Â return cipher.doFinal(data.getBytes()); Â Â } Â Â public static String decrypt(byte[] data, PrivateKey privateKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { Â Â Â Â Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); Â Â Â Â cipher.init(Cipher.DECRYPT_MODE, privateKey); Â Â Â Â return new String(cipher.doFinal(data)); Â Â } Â Â public static String decrypt(String data, String base64PrivateKey) throws IllegalBlockSizeException, InvalidKeyException, BadPaddingException, NoSuchAlgorithmException, NoSuchPaddingException { Â Â Â Â return decrypt(Base64.getDecoder().decode(data.getBytes()), getPrivateKey(base64PrivateKey)); Â Â } Â Â public static void main(String[] args) throws IllegalBlockSizeException, InvalidKeyException, NoSuchPaddingException, BadPaddingException { Â Â Â Â try { Â Â Â Â Â Â String encryptedString = Base64.getEncoder().encodeToString(encrypt("Dhiraj is the author", publicKey)); Â Â Â Â Â Â System.out.println(encryptedString); Â Â Â Â Â Â String decryptedString = RSAUtil.decrypt(encryptedString, privateKey); Â Â Â Â Â Â System.out.println(decryptedString); Â Â Â Â } catch (NoSuchAlgorithmException e) { Â Â Â Â Â Â System.err.println(e.getMessage()); Â Â Â Â } Â Â } }
Testing the Encryption
Let us run our spring boot app first by running RsaJavaJavascriptApplication.java as a Java main class. Now, the index.html is accessible at localhost:8080/home. Enter the username and password and click on the button to see the decrypted password in the alert box.
Conclusion
In this article, we learnt about RSA encryption and how RSA encryption can be done in Javascript and the same can be decrypted in Java.