Examples

In short words jCryption is a javascript HTML-Form encryption plugin, which encrypts the POST/GET-Data that will be sent when you submit a form.

No long talking, take a look at some Examples.
Please look in the FAQ or Documentation section for more detailed information.

Simple demo »

This is the standard setup.
Like in older versions it’s still posible with one simple call to encrypt your form.

Just call jCryption on your form.

$("#normal").jCryption();

demo »

Feedback demo »

To give your user some kind of feedback that the encryption is still in progress you can show a loader.

var $status = $('<div id="status" style="margin-top:15px;"><img src="loading.gif" alt="Loading..." title="Loading..." style="margin-right:15px;" /><span>Encrypting</span></div>').hide();
$("#submitButton").parent().append($status);
 
$("#callbackForm").jCryption({
	beforeEncryption:function() {
		$status.show();
		return true;
	}
});

demo »

Bi-Directional communication »

With jCryption 2.0 you can communicate encrypted with the server, you are no longer bound to just encrypting forms.
This example is a litte more complicated than the other,
but if you want to use jCryption for bidirectional communication just look at the source code … you will understand it with ease.
Just a short explaination what is going on …

1) Client chooses a Password … (in the example a weak one, you should use a good random number in production e.g. mousemovement coordinates)
2) Client requests RSA Public key from Server
3) Client encrypts Password with RSA Public key
4) Server decrypts Password and stores it in the session
5) Server Encrypts the Password with AES and sends it back to the Client
6) Client decrypts it with AES with the Password
7) Both have now the same “secret” key which is used for communication

Here is a litte example how it works.

var $loader = $('<img src="loading.gif" alt="Loading..." title="Loading..." style="margin-right:15px;" />');
$(function() {
	var hashObj = new jsSHA("mySuperPassword", "ASCII");
	var password = hashObj.getHash("SHA-512", "HEX");
 
	$.jCryption.authenticate(password, "encrypt.php?generateKeypair=true", "encrypt.php?handshake=true", function(AESKey) {
		$("#text,#encrypt,#decrypt,#serverChallenge").attr("disabled",false);
		$("#status").html('<span style="font-size: 16px;">Let\'s Rock!</span>');
	}, function() {
		// Authentication failed
	});
 
	$("#encrypt").click(function() {
		var encryptedString = $.jCryption.encrypt($("#text").val(), password);
		$("#log").prepend("\n").prepend("----------");
		$("#log").prepend("\n").prepend("String: " + $("#text").val());
		$("#log").prepend("\n").prepend("Encrypted: " + encryptedString);
		$.ajax({
			url: "encrypt.php",
			dataType: "json",
			type: "POST",
			data: {
				jCryption: encryptedString
			},
			success: function(response) {
				$("#log").prepend("\n").prepend("Server decrypted: " + response.data);
			}
		});
	});
 
	$("#serverChallenge").click(function() {
		$.ajax({
			url: "encrypt.php?decrypttest=true",
			dataType: "json",
			type: "POST",
			success: function(response) {
				$("#log").prepend("\n").prepend("----------");
				$("#log").prepend("\n").prepend("Server original: " + response.unencrypted);
				$("#log").prepend("\n").prepend("Server sent: " + response.encrypted);
				var decryptedString = $.jCryption.decrypt(response.encrypted, password);
				$("#log").prepend("\n").prepend("Decrypted: " + decryptedString);
			}
		});
	});
 
	$("#decrypt").click(function() {
		var decryptedString = $.jCryption.decrypt($("#text").val(), password);
		$("#log").prepend("\n").prepend("----------");
		$("#log").prepend("\n").prepend("Decrypted: " + decryptedString);
	});
 
});

demo »

HTML 5 Session Storage »

Frederik Lassen added an excellent example of how to use the “new” HTML5 Session Storage so the script is not required to request the key everytime from the server instead the “key” is stored in the session.

demo »

If you want to see the old examples here is the link.

Fork me on GitHub
Comments (115) Trackbacks (1)
  1. excellent work, you should consider using

    http://xregexp.com/plugins/#unicode

    to better manage international characters in javascript

  2. Hello,

    is there a way to make this library works only on client side ?

    I would like to have the possibilty to use it to store datas on untrusted servers. So only me can encrypt and decrypt the data via my browser.

  3. I do trust all of the ideas you’ve offered to your post. They are very convincing and can certainly work. Still, the posts are very quick for beginners. Could you please prolong them a little from next time? Thank you for the post.

  4. I have used Jcryption 2.0 to encrypt username,password for ExtJs 4.0.7 form.I have developed the application on win 32 bit.Here it works fine.But when I installed the setup on win 64 bit it gives problem.When I debugged the following code ,

    $.jCryption.challenge = function(challenge, key) {
    var temp=$.jCryption.decrypt(challenge, key);
    if ($.jCryption.decrypt(challenge, key) == key) {

    return true;
    }
    return false;
    };

    I found that value of variable temp=”" but actually it should be decrypted value and my authenticate method returns fail. Is some one know why it happens?

    Thanks in advance.

  5. Great examples! I came here looking for an example of encryption in JavaScript using the “client certificate”… without luck so far, should this be possible?

  6. Can not decrypt Chinese Character.

  7. I have a REST API in PHP how can i use jcryption ?

  8. Greetings,

    Appreciate very much if somebody can help me with this. The alert message didn’t pop-up and it went to prog.php.

    TIA

    *************************************************

    $(function() {
    $(“#crypt”).jCryption({
    beforeEncryption:inputvalidation;
    });
    });

    function inputvalidation() {
    if (document.form.emailaddr.value.length == 0) {
    alert(“Please fill in your email address.”);
    return false;
    }
    return true;
    }

    *************************************************

  9. I have encrypted data using var sd=$(‘#txtbox’).jCryption(); this method
    Now I want to send this to java code , my java code will decrypt this encrypted data.

    Is it possible?(No use of session no use of key)

    Thanks,

  10. can any one tell me java code for decryption without key

  11. Great work! But “man in the middle” attack still can break encryption. Proxy script on some middle server can bypass security. In case you even can’t detect if the certificate signed with wrong certificate. SSL gives “green label” in browser bar (also containing domain name from certificate).
    Am I right? Are there any ways to check AES key or determine harmful proxy?

    • Hi
      Nope … there is no way except SSL to prevent the “man in the middle” attack.
      It just isn’t technology possible without an secure channel which only SSL can supply.

      • What vantage point would one need in order to carry out an MITM attack? In other words, would you just need to be in range of an unencrypted WLAN over which the connection is taking place? Would you actually need to have access to the LAN router? Would you need to be an ISP or internet backbone? What level of privileged access is required by an attacker, if any?

        • If the attacker caught the first key exchange, which I assume isn’t encrypted, would they then be able to decrypt the encrypted communication that follows?

          • You are quite wrong.

            This uses PUBLIC-PRIVATE KEY ENCRYPTION.

            No one here seems to get that. Public-private key encryption is how you handshake, you then use AES because its faster.

            To put it this way, if I encrypt something with a PUBLIC encryption key, you CANNOT decrypt that same information with the PUBLIC key.

            You require the PRIVATE key, which is never ever shared.

            That means that no password or encryption key is ever sent in an unencrypted format, or risky format.

            So how does this work?

            Client asks server for PUBLIC key (which is useless to hackers).
            Server gives client PUBLIC key.
            Client encrypts password with PUBLIC key. Password CANNOT be decrypted using that same key.
            The server uses the PRIVATE key it has, to decrypt the client’s password.

            The client and the server then both use the client’s password as the encryption key for AES encryption.

            Basically, they use public-private key encryption to communicate an AES encryption key. This makes the whole process 100% secure.

            SSL does basically the same thing….

          • Jon is wrong, Olaf is right. Here’s how MITM would work on this:

            1) CLIENT request pubkey -> MITM -> SERVER

            2)SERVER responds with pubkey1 -> MITM responds with pubkey2 -> CLIENT

            3) CLIENT encrypts secret with pubkey2 -> MITM decrypts and saves, then re-encrypts with pubkey1 -> SERVER

            4) SERVER decrypts secret, then re-encrypts AES -> MITM decrypts AES, then re-encrypts AES -> CLIENT

            5) All future CLIENT -> MITM -> SERVER -> MITM -> CLIENT IO is encrypted with AES where the MITM has keys to communicate freely with both. MITM is required to function correctly as it behaves as a “gateway” of sorts between CLIENT and SERVER. If it breaks, the whole communication chain fails. But while it is running, it has full access to plain text data on the channel.

            I would very much like to implement some solution that eliminates the need for a dedicated IP address for every SSL-protected domain, but I believe this solution is too weak to be taken seriously with the blatant MITM hole. I don’t even care about SSL certificate prices… the problem is IP addresses. IPv6 is not ubiquitous enough to leverage the plentiful IP’s. SNI based Virtual Hosting offers a straight forward and promising future, however it too does not yet enjoy ubiquitous support in browsers.

  12. sir, pls send me the code for login uesrname and password using RSA algorithm in client side and tomcat server..

  13. i want more codes in encrypting and decrypting data with the textbox and the button.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

  14. i need codes in encrypting the data.

  15. I want to check the form validation before encrypt it!
    Any suggestion.

  16. In bi directional communication when we send request by using $.jCryption.authenticate(),initially it works fine,but after some time it executes the authentication failed function.Why this happens? can anyone tell.

    Thanks in advance.

  17. As I wasn’t able to find a Java implementation available on the web, I implemented my own version (which I called JavaCryption). It is available here: http://jcryptionforjava.wordpress.com/, including a fully working example. I hope it can be useful. Thanks.

    • Thanks Gabriel.
      Could you please include full source code though?

      • Hi, the full source code is available on sourceforge. Indeed, I tried to use latin chars (ISO-8859-1) in the beginning, but jCryption only works with UTF-8, so I had to change the encoding. Maybe you could modify the plug-in lines 1045 and 1121 (it’s where the encoding is applied). One question: UTF-8 does not support cyrillic chars?

        • “UTF-8 (UCS Transformation Format — 8-bit[1]) is a variable-width encoding that can represent every character in the Unicode character set.”
          http://en.wikipedia.org/wiki/UTF-8

          • “Дмитрий” == “Dmitriy”
            The code I downloaded from Sourceforge has only servlet as source: CryptoServlet.java

            Yes, I can decompile easily, but I want to reduce the hassle to other gumbys :) .

          • It’s because you downloaded the example, it contains only the binaries. You can download the source here: http://sourceforge.net/projects/javacryption/files/javacryption-1.0/.

          • thanks for the tip. it might be worth noting that there must be no space btweeen the passcode and the pipe.The code here is correct. But I typed it as echo passcode | gpg The command interpreter must have included the space in my passcode and the decrypt failed. After figuring that out, this works great. Thanks again.VA:F [1.9.22_1171](from 2 votes)

    • Gabriel, your code does not work quite well with Cyrillic chars: cp1251.
      I entered “жас” and “a” did not get decrypted correctly.

      Also, Base64 does not work with 16-bit chars in jCryption. Same goes for Apache commons version in java.

    • Thanks a lot Gabriel.
      I had been trying to find similar solution for java from some days.

  18. Great plugin, thanks for the work on this. I’ve got it setup in a jquery mobile/backbone/requirejs/AMD app and split up the plugin file to 2 files – the plugin, and all the support libraries. At some point I’ll likely refactor the latter as it introduces many globals…will send a push request if/when I get that done.

  19. Hi! There’s a problem using $.getJSON in IE, it caches the ajax queries (http://www.factory-h.com/blog/?p=67). If the parameters of the call to generateKeypair don’t change, IE assumes the response will be the same, and jcryption won’t work.

  20. hi o like this html 5 session storage but can u give eg…

  21. I am wondering if this could be used for the following purpose; I have had an auto complete tool made which caches data from tables in my server on the client side in order to achieve speed/performance. However it also exposes my tables in their entireity which I don’t want to do. Could this be used to store the data encrypted on the client machine and then the AC decrypts when populating? This way the user does not have my table in a readable format.

    • It depends on the structure of your table objects. Once the password is established in the session, it’s a simple matter to encrypt/decrypt – but it works on strings, not objects. You could set up a getter for your table object that called $.jCryption.decrypt(encryptedValue, sessionStorage.password). It’s fast, I think it would work well.

  22. I was able to figure it out generatekey part in php, but I can’t figure it out how to convert handshake part in java. What is the logic behind handshake?
    Do handshake is required?

Leave a comment

You must be logged in to post a comment.