Jerry's Cryptography and AJAX javascript and PHP Library
Ubiquitous Robust Encryption
Any web page can easily employ robust encryption
RC4 over RSA
really is just this easy
No SSL, no secure server needed. javascript and PHP function library does everything, even client to server URL encoding automatically
js: <body onload= initCrypto( 1024 bit)
js: encryptToServer( clientPlainText)
PHP: decryptFromClient( encryptedDataFromClient)
PHP: encryptToClient( serverPlainText)
js: decryptFromServer( encryptedDataFromServer)
Encrypt everything on the Internet from mobile device web apps to dinner recipe web pages. The technology is now free.
Encrypting only important documents merely identifies which documents are important, attracting the most powerful decryption efforts. Which is better? A society in which no one can have any secrets? Or a society in which anyone can keep everything secret?
Much faster bcmath based on true binary multiplication
- multiply two 700 digit decimal numbers (2300 bits) in less than
- 40 iterations of 700 digit integer addition function (14000 700 int adds)
greatly improved xdomain abuse detection and prevention
added 'collect' and 'populate' functions for super easy form handling
higher and much stronger encryption
easier to use php html javascript template in a single -plug and play file
Cryptography
voidinitCrypto( no_bits )
initCrypto()
This initializes the key generating handshake with the server. It takes the number of bits for the key size and returns void.
Call this function in <body onload=""
<body onload="initCrypto( 1024 )">
or let the user start crypto by selecting his desired bit strength
The Red Lock icon top right can be clicked at any time to show the current key and to reinitialize encryption.
To incorporate the Red Lock icon in your page, simply include this div at the bottom of your HTML, just before the </body>
<div id="secureComIcon"></div>
If you use the Red Lock icon, please download these three graphics files and put them on your server in the directory "/images/" so that your pages don't leach off my server. Or feel free to replace them with your own images. Search jerrysLibrary.js for them to change the code in any way.
These functions are not in the library. You may write them. If you don't write them and they don't exist, they are ignored. They are not needed for secure communications. They are provided for user information only. You can use these to inform the user of status or for any other purpose. You do not have to use nor write them at all.
Calling initCrypto() for the very first time creates a directory "temp" on your server. This directory is created in the directory in which you place jerrysLibrary.php library file. The contents of this directory will change constantly. You don't have to do anything with its contents.
To use these functions you must include this line in the HTML header
This is the only function you need to receive encrypted data from the server. The minimum needed is this.
var encryptedValue= encryptToServer( plainText);
var encryptedResponse= synchttp(( 'serverScript.php?handler=' + encryptedValue), '')
var decryptedResponse= decryptFromServer( encryptedResponse);
PHP scripts which must decrypt and encrypt must include
<?php include('/your_path/jerrysLibrary.php');
The server script decrypts the data sent above like this
if ( isset( $_GET['handler'])){
$plaintext= decryptFromClient( $_GET['handler']);
// do something with $plaintext and generate $response
echo encryptToClient( $response);
exit();
}
When passing encrypted data to the server, there is no need to URL encode it, encodeURIComponent(). The encryption library ensures that data uploaded to the server contains only URL safe characters.
It is really just that simple. There is never any need to encodeURIComponent(). All the encryption functions generate only URI safe characters on the uplink side.
To use these functions you must include this line in the HTML header
save them to your server. Remember to remove the .txt extension on the file jerrysLibrary.php
Set the path where you saved the files in line 25 of jerrysLibrary.js and set JL_setAjax in line 31 as desired. 'true' if you want to use the AJAX functions. AJAX must be set to true if cryptography is desired.
line 25: var PHPlibpath= 'http://'+window.location.hostname + '/test/jerrysLibrary.php';
line 31: var JL_setAjax= true;
Set ALLOWXDOMAIN and STOREKEYINSESSION according to your taste.
Allowing Xdomain is really convenient, but it also opens a certain vulnerability on your server. Javascript does not allow this because this could be a security issue. A hacker could send requests to your copy of jerrysLibrary.php having it access web pages to carry out his own nefarious ends. The web sights accessed would record the IP address of your server not the hacker's.
This is set true in the downloaded file.
line 20: define ( 'ALLOWXDOMAIN', 'true'); // true / false
You must include this line in the HTML header of any page using the libraries.
and include this line in all php scripts that responds to encrypted messages
<?php include ('your-server-path/jerrysLibrary.php');
AJAX
stringsynchttp( UrlInYourDomainGET, POST ) voidmultihttp( UrlInYourDomainGET, POST, callBackFunctionName )
synchttp() multihttp()
These are the two main AJAX functions.
Place GET name value pairs in the first argument and POST name value pairs in the second argument.
The third argument for multihttp() is the name of a call back function. When the server responds, the call back function will be called. In the mean time javascript can go on doing what ever else it wants. Whereas, in synchttp(), javascript is halted until the response and the response is returned as text. These are not encrypted. See Cryptography section.
synchhttp( URL, POST)
multihttp( URL, POST, 'callBackFunctionName')
function callBackFunctionName( response){
var resp= unescape( response);
// do anything with resp.
}
Try it out. Since the URL base is our own domain and the server script to which we send this request is the PHP portion of the file for this page, we can simply use '?varName=value' for our GET address. Download
testJerrysLibrary.php,
the source file of this page to see the PHP.
Notice that synchhttp() makes javascript wait until the response from the server comes back, while multihttp() can issue multiple calls and do other things. When the response does come the callback function is called and the response is passed to it escaped. You write the callback function and pass its name as the third parameter of multihttp(). Always unescape the response in the callback function.
The test AJAX server function, found in testJerrysLibrary.php, simply returns the names and values for all GET, POST, COOKIE and SESSION variables that exist. Notice the pereventCaching GET variable. It is added by the AJAX library to precent any caching that could be going on at any point along the Internet route.
The test AJAX server function also has an intentional delay to showcase the features of multihttp(). In this example a whirl image is placed inside the div until the response arrives. Of course with synchttp() this would be impossible, because javascript is tied up until the response is received.
Click either synchttp( or the multihttp( to try them out.
document.getElementById('testAJAX').innerHTML='<img src="whirl">
for ( var i=1; i<3; i++){
multihttp(( '?someGETvar='+i), '', 'callBackFunctionName' )
}
function callBackFunctionName( a){
document.getElementById( 'testAJAX').innerHTML+= unescape( a);
}
<div id="testAJAX">
</div>
stringXdomain( anyUrlGET, POST, cookiejar, agent, timeout ) voidmultiXdomain( anyUrlGET, POST, cookiejar, agent, timeout, callBackFunctionName )
Xdomain() multiXdomain()
The two Xdomain functions retrieve the contents of web pages that are not on your domain.
Javascript does not allow this because this could be a security issue. A hacker could send requests to your copy of jerrysLibrary.php having it access web pages to carry out his own nefarious ends. The web sights accessed would record the IP address of your server not the hacker. While this function can be convenient, it could also be dangerous.
There are three ways to shut down Xdomain access.
1) Open the file jerrysLibrary.php and change line number 20 to "define ( 'ALLOWXDOMAIN', 'false')"
2) Execute the javascript function Xdomain( 'noaccess', '')
3) Place a file named 'xdomain.txt' with the contents 'no' on your server in the same path as jerrysLibrary.php
Any of these three will cause both Xdomain functions to always return false and never access any web page. The only way to restore access is to delete the file 'xdomain.txt' from your server and restore line 20 to 'true'.
Both functions do exactly the same as thing except that multiXdomain does not halt javascript while waiting for the response. When the response comes it calls the call back function and passes the response as an escaped string to that function.
<input id="mxdomainurl" type="text">
URL
<input id="mxdomainpost" type="text">
send POST data if any
As one sees, even though whirling "working" image is placed in the div that will receive the text, nothing happens. The computer is frozen until the source code of the page is received.
With multiXdomain() the computer can go on to do other things until the response is received. The whirling image does show up while during the time the response takes to arrive. The response which is a the source code of a web page is passed to the callback function when it arrives which places it in the div.
That is one of the test AJAX server commands and it intentionally delays responding for 1 to 3 seconds.
<div id="MXdomain">
</div>
function displayCleanPage( a){
var pagecontents= unescape( a);
pagecontents= subtute( '<', '<', pagecontents);
pagecontents= subtute( "\n", '<br>', pagecontents);
ge('MXdomain').innerHTML= pagecontents;
}
function mxdomaincallback( a){
ge('MXdomain').innerHTML= displayCleanPage( a);
}
boolsetcookie( name, value, time, path, domain ) stringgetcookie( name )
setcookie() getcookie()
Set the value or create a cookie on the client from javascript. You don't have to be too careful with the value types. They pretty much all get turned into strings, except for in some rare occasions. Keeping them strings is good practice.
If the cookie doesn't exist, it will be created. Time is the only important value. It is relative to now and in seconds. So you don't have to add to the current timestamp. A value of 3600 will set the cookie to expire an hour from now. It is in seconds, not milliseconds. Setting time to zero, erases the cookie. Path and domain have the same meaning as cookie path and domain.
Make a new cookie name and value. Place them in their respective text fields. Set the cookie. Delete the value but not the name and click Get cookie. Take note of some actual cookie names from the section on synchttp() and put those names in the name input field then click Get Cookie.
A true cookie will retain its value on reload. Try it. Just remember that these cookies are set for only five minutes. Use the function in your own javascript to set it for a different time.
boolsetsession( name, value ) stringgetsession( name )
setsession() getsession()
Set the value of any SESSION variable on the server from javascript. If the session variable doesn't exist, it will create it. You don't have to be too careful with the value types. They pretty much get turned into strings, except for in some rare occasions. Keeping them strings is good practice.
setsession( 'nameOf_SESSION_Variable', 'value')
var yourVariable= getsession( 'nameOf_SESSION_Variable' )
Retrieve the value of any SESSION variable that the server is keeping for this session. If the session variable doesn't exist, it will return NULL string or empty string.
Make a new SESSION name and value. Place them in their respective text fields. Set the SESSION variable. Delete the value but not the name and click Get session. Take note of some actual session variable names from the section on synchttp() and put those names in the name input field then click Get session.
A true SESSION variable will retain its value on reload. Try it. Just don't close the browser or do something that would cause a new session.
Miscellany
stringsubtute( replaceThis, withThis, inString )
subtute()
If you get tired of the limitations of regular expressions, especially if you are working with special characters, this function will replace any string with any other string in any string.
ms( mouse_pointer) is a short cut for document.body.style.cursor
2 is 'hand'
1 is 'normal pointer'
Use any valid mouse pointer name in addition to 1 and 2
<span onmouseover="ms(2)" onmouseout="ms(1)">
Change the cursor on mouse over
</span>
ge( element_name ) is a short cut for document.getElementById
getxpos( element ) returns the x position of the element
getypos( element ) returns the y position of the element
<span id="testmo">
</span>
<span onmouseover="ge( 'testmo').innerHTML= getxpos( ge( 'testmo'))+ ' x pos'"
onmouseout=" ge( 'testmo').innerHTML= getypos( ge( 'testmo'))+ ' x pos'" >
Mouse over to show the x pos of this
</span>
- Comments -
Noms de plume
Enter your email,
if you want to follow this conversation. Your email is never shared.
your comment
Any web page can easily employ robust encryption
Say Good-by to Captcha
Say Goodbye to NSA spying
This article is for programmers -to encourage and help them in the ubiquitous use of robust encryption.
Encrypt all AJAX data to and from the server with this free and entirely javascript and PHP library. There are many reasons for ubiquitous encryption other than data security itself. The complete and total elimination of Captcha for one. Look at the source code for the comments section on this page to see why the comments on this page are safe from auto post robots without any sort of Captcha what-so-ever.
No installation needed. No java applet client download. No SSL. No security certificates. Not even JQuery is needed. It is a clean, short and simple library that in addition to Encryption also provides AJAX functions including get and set session and cookie. Simply download the jerrysLibrary.js and jerrysLibrary.php libraries. Save them to your server and reference them in your code.
This page demonstrates all the functions which the library provides. And the source code of this page provides direct examples of the use of each. You'll find the code examples clearly marked in the source. This library was expressly written for ease of use.
Given ever increasing security concerns,
I have decided to add RSA encryption to all client/server communications on my websites. Everything I write from now on will employ rigorous and ubiquitous encryption. Everything! not just passwords, but the contents of even every AJAX call.
Salute to Edward Snowden
This is about more than commercial and banking security. Regardless of the fact that the NSA is probably uninterested in my particular web traffic, making snooping technically infeasible makes the world a better and safer place for free thinkers and for the exchange of political ideas and ensures the free exchange of ideas without fear that someone, somewhere will decide that this or that information should not be available to the public. So, encryption is not just about keeping your data safe from hackers, but it is about making the world a better place to live.
Encrypting only important documents, merely identifies that document as worth devoting computational time. Encrypting everything forces everything to be decrypted to determine which documents are important.
The library design goal
To make encryption easy for web developers, I wrote a javascript and PHP library and offer it to everyone for their use. I encourage the proliferation of robust encryption technology to keep everyone honest. And offer this library of easy to use functions to everyone everywhere. I offer it's use free of charge. I offer it for alteration, augmentation, bug fixes, or any other changes.
This javascript and PHP library endows even tablets and smart phones with full 2048 bit RSA encryption in four very easy to use javascript functions. Plus the library provides 13 other handy functions for AJAX and to make programming easier.
The library is written and utilizes PHP and javascript only. This keeps it easy to use and implement. No user has to download software and install it. Everything can be done with javascript and PHP.
Since cryptography also requires AJAX and some other functions that make it all go easier, all the functions are explained and available here for your use. Please use them freely.
Design considerations
Upon the initial client http request, the server begins to generate vary large prime numbers in anticipation. The client passes the results of a javascript speed test to the server in its initial handshake. The server generates as strong an RSA key set as possible for the given speed test.
The server and client then use the RSA asymmetrical key set to build up a robust RC4 symmetrical key over multiple steps. Finally there is a final handshake where the server and client confirm to each other that they are indeed the same machines which first began the negotiation.
This is done by decrypting a message and comparing it with the original handshake message. Re-encrypting it and passing it back confirms that the server and client are in fact the very same which began the key negotiations a few seconds ago. This Guarantees that no hacker has hijacked the handshaking. Communication then continues for the session with the secure RC4 key at which the server and client arrived.
The message or safe word which persists throughout the communication session is contained in the javascript variable JL_cryname. The hash of this randomly generated message is the name of a file on the server which contains all the pertinent key information. Server SESSION variables are not used because they slow the server down and because using the hash of the passed message disassociates any obvious connection between session files on the server and http requests.
The challenge for the server is generating large prime numbers. A 2000 bit prime number can take as much as two minutes to generate in pure PHP. I solved this simply by having the client make multiple http requests under the same JL_cryname. This employs many instances of the same prime number generator which dumps their results into the same pool.
The client javascript is challenged by the bcmath needed to encrypt in RSA
To get things to work on the javascript client I looked for a bcmath package for javascript. I found a good one but it was still too slow. I ended up writing my own from scratch. By ignoring negative numbers, floating point and validation of the arguments, I got it to work better than twice as fast as the best package I looked at and kept is completely javascript.
Waiting for secure channel.