Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Java

JavaScript RSA Encryption and Java Decryption

3.00/5 (2 votes)
19 May 2011CPOL1 min read 41.9K  
JavaScript RSA Encryption and Java Decryption

Many of us have been working with JavaScript since a long time but whenever I ask people how to send encrypted data, the only answer is to use SSL . But this article shows how to send encrypted data even when we don’t have SSL enabled. This can come in to handy in many scenarios.

I used jCryption and JavaScript Library to encrypt in JavaScript and BouncyCastle Library on Javabackend to decrypt.

Here is the flow in the example:

  1. First generate RSA keys on server end (Store in session)
  2. Send public key to client (JavaScript)
  3. Store keys in JavaScript variable
  4. In all subsequent requests, use this key to encrypt data and send to server
  5. Use keys stored in session to decrypt data and send response to server

Keys generation utility class in Java:

Java
package com.linkwithweb.encryption;

import java.io.IOException;
import java.security.KeyPair;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EncryptionServlet
 */
public class EncryptionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Default constructor.
	 */
	public EncryptionServlet() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		if (request.getParameter("generateKeypair") != null) {

			JCryptionUtil jCryptionUtil = new JCryptionUtil();

			KeyPair keys = null;
			if (request.getSession().getAttribute("keys") == null) {
				keys = jCryptionUtil.generateKeypair(512);
				request.getSession().setAttribute("keys", keys);
			}

			StringBuffer output = new StringBuffer();

			String e = JCryptionUtil.getPublicKeyExponent(keys);
			String n = JCryptionUtil.getPublicKeyModulus(keys);
			String md = String.valueOf(JCryptionUtil.getMaxDigits(512));

			output.append("{\"e\":\"");
			output.append(e);
			output.append("\",\"n\":\"");
			output.append(n);
			output.append("\",\"maxdigits\":\"");
			output.append(md);
			output.append("\"}");

			output.toString();
			response.getOutputStream().print(
					output.toString().replaceAll("\r", "").replaceAll("\n", "")
							.trim());
		} else {
			response.getOutputStream().print(String.valueOf(false));
		}
	}
}

All client code is there in index.jsp and framework.js.

JavaScript function that gets keys from server and stores in JavaScript variable:

Java
/**
 * Get Security keys from server so that we can encrypt request in future
 */
function getKeys() {
	$.jCryption.getKeys("EncryptionServlet?generateKeypair=true", function(
			receivedKeys) {
		keys = receivedKeys;
	});
}

On login button clicked here is how you encrypt and send request to server:

Java
/**
 * Called on Login Button clicked
 */
function onLoginButtonClicked() {
	var user = $("#login_user").val();
	var password = $("#login_password").val();
	$.jCryption.encrypt(user, keys, function(encrypted) {
		encryptedUser = encrypted;
		$.jCryption.encrypt(password, keys, function(encryptedPasswd) {
			encryptedPassword = encryptedPasswd;
			/**
			 * As both userName and password are encrypted now Submit login
			 */
			submitLoginRequest();
		});
	});
}

/**
 * Submit Login request
 */
function submitLoginRequest() {
	sendAjaxRequest("LoginServlet", {
		username : encryptedUser,
		password : encryptedPassword
	}, function(data) {
		if (data.length > 0) {
			$("#login_status").empty();
			$("#login_status").append(data);
		}
	});
}

And below is svn URL to download the sample source code https://linkwithweb.googlecode.com/svn/trunk/Utilities/jCryptionTutorial

The next version of the tutorial will be from flex to Java. Enjoy reading and playing with Encryption code.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)