Documentation

Javascript

Requirements:
jQuery 1.3.2

Options:

Name Default Description
formElements “input,select,textarea” string / jQuery selector
The jQuery seletor to select which form element should be encrypted. Leave this option to get all form elements.
submitEvent “click” string / jQuery event
Event that triggers the submit of the form. “Click” also handles the “Enter button”.
submitTrigger “:input:submit” string / jQuery selector
The element where the submitEvent should get bound to.
getKeysURL “main.php?generateKeypair=true” string
The url where the script should receive the keys.
postVariable “jCryption” string
The name of the POST/GET variable which the PHP-Script receives.
disableAllFields true boolean
Disables all form fields when you submit a form. You have to do that if you submit the form without ajaxSubmit because enabled form elements will still be sent unencrypted to the server.
addClassDisabled false boolean
Set to true if jCryption should add a class disabeld to every disabled element.
collectionSpeed 1 int / in ms
The speed of the element collection.
encryptionSpeed 1 int / in ms
The speed of each encryption step.
receivedKeys function(keys) {} function(keys)
Called when keys are received from the server.
beforeEncryption function() { return true; } function()
This function is called before the keys will be retrieved from the server (if you w”ant to javascript validate something do it here), return true to continue.
inputCollectorCallback function(i,length) {} function(i,length)
“this”, refers to the current collected input element. “i” is the current number of the element and “length” is the number of all elements.
inputCollectorFinished function(length) { return true; } function(length)
Called when all elements are collected, you can abort the encryption by returning false.
encryptionCallback function(i,length) {} function(i,length)
This function is called on every encryption step. “i” is the current number of the step and “length” is the total number of all steps.
encryptionFinished function(encryptedString,length) {return true;} function(encryptedString,length)
Called when the encryption is finished. You can still cancel the submit of the form by returning false.
ajaxSubmit false boolean
When you set this to true the form will be sent by $.ajax with following options.
ajaxDataType “html” string
jQuery $.ajax dataType.
ajaxSubmitSuccess function(data, textStatus) {} function(data, textStatus)
jQuery $.ajax success callback function.
ajaxSubmitError function(XMLHttpRequest, textStatus, errorThrown) {} function(XMLHttpRequest, textStatus, errorThrown)
jQuery $.ajax error callback function.

PHP

Requirements:
PHP 4.0.4 with libbcmath

Here is a small example how you may use the jCryption PHP class.
Basically you’ll find everything you need in this example.

<?php
session_start();
require_once("jCryption-1.0.1.php");
 
$keyLength = 256;
$jCryption = new jCryption();
 
if(isset($_GET["generateKeypair"])) {
	$keys = $jCryption->generateKeypair($keyLength);
 
	//sets the keys in the session to have them ready when you submit the form
	//please keep this structure. You'll need the hex value of the key for javascript
	//and the int value of the key for PHP. e = public key, d = private key, n = modulo
	$_SESSION["e"] = array("int" => $keys["e"], "hex" => $jCryption->dec2string($keys["e"],16));
	$_SESSION["d"] = array("int" => $keys["d"], "hex" => $jCryption->dec2string($keys["d"],16));
	$_SESSION["n"] = array("int" => $keys["n"], "hex" => $jCryption->dec2string($keys["n"],16));
 
	//returns the needed keys for the javascript part in a JSON string
	//maxdigits is need for the javascript and caluclated like ($keyLength * 2 / 16 + 3)
	echo '{"e":"'.$_SESSION["e"]["hex"].'","n":"'.$_SESSION["n"]["hex"].'","maxdigits":"'.intval($keyLength*2/16+3)).'"}';
} else {
	//print the orginial POST
	echo "POST:";
	print_r($_POST);
	echo "<br/>";
 
	//here the decrypt function is called. The first parameter is the encrypted POST.
	//Second parameter is the private key d in it's int form and third the modulo n.
	//This function will return your orginal decrypted POST.
	$var = $jCryption->decrypt($_POST['jCryption'], $_SESSION["d"]["int"], $_SESSION["n"]["int"]);
	//parses the decrypted string and returns it in an array.
	//now it's important to unset the keys from the session
	unset($_SESSION["e"]);
	unset($_SESSION["d"]);
	unset($_SESSION["n"]);
	parse_str($var,$result);
	echo "decrypted POST";
	print_r($result);
}
?>
Comments (22) Trackbacks (0)
  1. have you any example for asp.net mvc?

  2. I’m having problems. I know it encrypts, but it never moves off of the current page, like it doesn’t submit. This code is in a page that is in a subfolder, thus, the getKeysURL option. I have put the action of the form relative to the current directory. I have no idea why this is not working, because it works every other time I use this.

    var field = null;
    function setField(formField)
    {
    if( field == null )
    field = formField;
    }
    // this submits the form via the encryption javascript
    $(document).ready(function()
    {
    $(”#cPass”).jCryption({
    getKeysURL:”../getKey.php”,
    beforeEncryption:function()
    {
    // Various input checking tests that I know work
    // If bad, return false, else return true;
    }
    }
    )
    $(”input”).removeAttr(”disabled”);
    });

    • I figured it out! My submit button () had the name “submit” (name=”submit”), and that caused it to not submit. When I changed the name or deleted it, it worked fine as before. YEAH!!!!!

  3. Do you know why some times process of generating keypairs takes so many time and never ends up. (Some times it work great). And place next in apache error.log:

    bc math warning: non-zero scale in modulus
    bc math warning: non-zero scale in base
    bc math warning: non-zero scale in exponent

    Apache 2.2.4 / PHP 5.2.11

  4. Hey man, in your sample code above on line 19, the echo at the bottom of the if-block, you’ve got 2 parenthesis closing that, you actually only need one. :)

  5. Has anyone tried this with Perl? Anyone knows what the ‘n’ (modulo) param is that you return with the public key? Also, what’s the point of returning “maxdigits” (instead of $keyLength, say)?

    • n = modulo yes …
      The maxdigits variable was used by Dave Shapiro and there was no reason to change the mechanism oder variables so I kept it.
      maxdigits = keyLength*2/16+3

      • Sorry, I’m new to this RSA stuff, so it took me a while to figure out the terminology and what the params meant. I really like this library, but I couldn’t get it working with perl’s Crypt::OpenSSL::RSA or Crypt::RSA, so I ended up using a different javascript library, which worked. I suspect the problem was with padding. What kind of padding does Dave Shapiro’s library use? If you have any other thoughts that might point me to a solution, let me know. Thanks.

        Incidentally, this is the javascript RSA library I ended up using, which does the PKCS1 padding that’s compatible with the perl modules I was trying to use.

        http://www-cs-students.stanford.edu/~tjw/jsbn/

  6. Uh, I was in desperate need of this and infact planning to build one myself. Thanks to you that you saved me a lot of time.
    Cheers…
    Keep up the good work.

  7. what about decrypt in javascript?
    This would be usefull for example for comunicating via ajax and getting the response encrypted. In JS you could decrypt and process the response.

    • I have the same requirement. Just to clarify, jCryption is currently just one-way traffic encryption, correct?

    • I am currently looking for the best method to provide a bidirectional communication. I think the best way would be changing a symmetric key via RSA and encrypt/decrypt the rest with the symmetric algorithm like AES for example. If someone has a better idea, please let me know.

      • I too am interested in bidirectional encrypted messaging portal. Existing services of “encrypted” email store text messages and attachments on a portal, but do not support HTML forms or organized responses that can be easily incorporated into a database. Current services like Tumbleweed from Axway email a form that includes security tokens to access a message via https. PGP requires installing a client and creating personal keys, too much work for many casual business clients. jQuery/jcryption could install a simple encryption/decryption client in a browser window. Ultimately, content could be stored on a web server that would be unreadable to hackers that don’t have a private key that would be emailed to the client. Any recipient of the email could access the content, but that doesn’t seem to stop these encrypted email services from touting HIPAA compliance.

  8. CORRECTION:
    My code did not display write:
    _____________________________________
    $(document).ready(function() {
    $(”#loginLiteForm”).jCryption({getVariable:”encryption”, getKeysURL:”gen_keys.php”});
    var count = 0;
    for (i=0; i -1) {
    count++;
    }
    }
    if (count > 0) {
    for (i=1; i<=count; i++) {
    $("#encrypt"+i+"").jCryption({getVariable:"encryption", getKeysURL:"gen_keys.php"});
    }
    }
    });

  9. How do encrypt GET data?

    Here is my jQuery setup script. Can you modify this so it will encrypt GET data?
    ***********************
    $(document).ready(function() {
    $(”#loginLiteForm”).jCryption({postVariable:”encryption”, getKeysURL:”gen_keys.php”});
    var count = 0;
    for (i=0; i -1) {
    count++;
    }
    }
    if (count > 0) {
    for (i=1; i<=count; i++) {
    $("#encrypt"+i+"").jCryption({postVariable:"encryption", getKeysURL:"gen_keys.php"});
    }
    }
    });

  10. Will there be an asp.net version??

    • The first priority for me is making jCryption faster and more secure, other versions will follow when everything else is done.
      Although i can’t say if there will be a asp.net version because my asp skills are very limited.

  11. Are you planning to provide Java Version ??

    • Yes there are plans on releasing alternatives to PHP.
      A user posted here that he is developing a java version, as soon as he is finished and I tested it, it will be included in a future release of jCryption.

      • I have been working on Cryptography from last few years, Though there are numerous algorithms are provided with Java, I would request you to re-evaluate before and provide a very flexible API similar to the one you provided for PHP. Also, I would like to participate in development of Java version.

Leave a comment


No trackbacks yet.