Secure Hash Functions (MD4, MD5, SHA-1)

The MD4, MD5 and SHA-1 algorithms are secure hash functions. They take a string input, and produce a fixed size number - 128 bits for MD4 and MD5; 160 bits for SHA-1. This number is a hash of the input - a small change in the input results in a substantial change in the output.

The functions are thought to be secure, in the sense that it would require an enormous amount of computing power to find a string which hashes to a chosen value. In others words, there's (almost) no way to decrypt a secure hash. The uses of secure hashes include digital signatures and challenge hash authentication.

View:

Usually you'll want to get the result in hexadecimal, so it can be submitted as part of a form without worrying about URL encoding.

<script type="text/javascript">
 hash = hex_md4("input string");
 hash = hex_md5("input string");
 hash = hex_sha1("input string");
</script>

Note that the input must be a string - hex_md5(Math.random()) will not function correctly; you must do hex_md5(Math.random().toString()).

You can also get the result in base-64 encoding:

<script type="text/javascript">
 hash = b64_md4("input string");
 hash = b64_md5("input string");
 hash = b64_sha1("input string");
</script>

You can also get the result as a binary string. This representation is useful when you want to feed the result of a hash operation back into another operation. The ability to do this lets you create a variety of cryptographic protocols. For example, to do a double hash: double_hash = hex_md5(str_md5(data)); The string is encoded so each character of a string represents either one or two bytes, in ASCII and UniCode respectively. This would be troublesome to send over HTTP as form data, but JavaScript strings are completely binary safe.

In many uses of hashes you end up wanting to combine a key with some data. It isn't so bad to do this by simple concatonation, but HMAC is a carefully designed method, known to be very secure. The usage is:

<script type="text/javascript">
 hash = hex_hmac_md4("key", "data");
 hash = hex_hmac_md5("key", "data");
 hash = hex_hmac_sha1("key", "data");
</script>

There are a few configurable variables; you may have to tweak these to be compatible with the hash function on the server.

hexcaseThe case of the letters A-F in hexadecimal:
  • output 0 - lower case (default)
  • 1 - upper case
b64padThe character used to pad base-64 output to a multiple of 3 bytes
  • "" - no padding (default)
  • "=" - for strict RFC compliance
chrszWhether string input should be treated as ASCII or UniCode
  • 8 - ASCII (default)
  • 16 - UniCode

To set a variable, use a syntax like this:

<script type="text/javascript">
   chrsz = 16;
</script>
In general, it's ok to change the values of these variables between calls to the library; for example you can do ASCII and UniCode hashes on the same page. However, you can't change chrsz and then re-use data returned by a str_* function.

To see working example of these functions, visit WebTNG Hash Calculator tool page.

Convert HSV to RGB equivalent

HSV is abbreviation of Hue, Saturation, Value. It's a color model in which color itself (hue) is placed on a circle (red is 0 degrees, green is 120 degrees, blue is -120 degrees) whose radius is proportional to the saturation (purity) of the color. Value is a measure for the brightness of the color (similiar to intensity). HSV must be translated to another model for colour printing or for forming screen colours. Following function is javascript implementation to convert HSV color model into it's RGB equivalent (RGB is abbreviation of Red Green Blue, the three primary additive colors of light, which computers use to display images on your screen).

function hsv2rgb(h,s,v) {
// Adapted from http://www.easyrgb.com/math.html
// hsv values = 0 - 1, rgb values = 0 - 255
var r, g, b;
var RGB = new Array();
if(s==0){
  RGB['red']=RGB['green']=RGB['blue']=Math.round(v*255);
}else{
  // h must be < 1
  var var_h = h * 6;
  if (var_h==6) var_h = 0;
  //Or ... var_i = floor( var_h )
  var var_i = Math.floor( var_h );
  var var_1 = v*(1-s);
  var var_2 = v*(1-s*(var_h-var_i));
  var var_3 = v*(1-s*(1-(var_h-var_i)));
  if(var_i==0){ 
    var_r = v; 
    var_g = var_3; 
    var_b = var_1;
  }else if(var_i==1){ 
    var_r = var_2;
    var_g = v;
    var_b = var_1;
  }else if(var_i==2){
    var_r = var_1;
    var_g = v;
    var_b = var_3
  }else if(var_i==3){
    var_r = var_1;
    var_g = var_2;
    var_b = v;
  }else if (var_i==4){
    var_r = var_3;
    var_g = var_1;
    var_b = v;
  }else{ 
    var_r = v;
    var_g = var_1;
    var_b = var_2
  }
  //rgb results = 0 ÷ 255  
  RGB['red']=Math.round(var_r * 255);
  RGB['green']=Math.round(var_g * 255);
  RGB['blue']=Math.round(var_b * 255);
  }
return RGB;  
};
To use this function, simply assign function return to new variable and access individual values by key ('red','green',or 'blue'), i.e.:
var rgb=hsv2rgb(h,s,v);
alert('RGB value is '+rgb['red']+','+rgb['green']+','+rgb['blue']);
Working Example: Hue: Saturation: Value:

Disable Text Selection

function doNothing(){ return false; }
function disableTextSelection(id) {
if (id=='all') var element=document;
  else var element=document.getElementById(id);
if (document.all)  // MSIE
   element.onselectstart = doNothing;
 else //Mozilla
   element.onmousedown = doNothing;
}
Use this script to disable the selection of text on a page. It's conducted by canceling the selection before it starts.
  • To disable text selection for entire document, assign 'all' as parameter, i.e.: disableTextSelection('all')
  • To attach the events to a specific element call the function with element id as parameter, i.e.: disableTextSelection('text1')
Text in this box is not selectable.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci suscipit lobortis ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu feugiat nulla facilisis at vero eros et accumsan.

Get Text Selection

function selectedText() {
  if (document.getSelection) {
    var str = document.getSelection();
    if (window.RegExp) {
      var regstr = unescape("%20%20%20%20%20");
      var regexp = new RegExp(regstr, "g");
      str = str.replace(regexp, "");
    }
  } else if (document.selection && document.selection.createRange) {
    var range = document.selection.createRange();
    var str = range.text;
  } else {
    var str = "";
  }
  return str;
}
Working example: Try select some text anywhere in this page and press

Browser Bookmark

function addBookmark() {
  if(document.all) //MSIE
    window.external.AddFavorite(document.location.href,document.title);
  else if (window.sidebar)
    window.sidebar.addPanel(document.title, document.location.href,"");
  else
    alert('Close this popup and press Ctrl-D to bookmark this page');
}
This is a cross-browser function to perform Add Bookmark using javascript.
Working example: Add to Favorites

Drag & Drop for Images and Layers

A cross-browser JavaScript DHTML Library which adds Drag Drop functionality and extended DHTML capabilities to layers and to any desired image, even those integrated into the text flow. To convert images or layers into draggable DHTML items, simply pass their names/IDs to the library's main function SET_DHTML().

Optional commands allow to change and customize the behaviour of Drag&Drop items in multiple ways. For example, you can limit how far a drag&drop item can be moved, specify the cursor, or multiply drag'ndrop images. The DHTML API of this DHTML Drag&Drop JavaScript is easily understandable. It provides methods to moveTo(), resizeTo(), hide() and show() again drag and drop elements, or to copy() images right within the textflow of your page dynamically, and much more.

Each DHTML item has properties such as x, y, w, h, z, defx, defy, defw, defh, defz (co-ordinates, size, z-index, and their initial default values, respectively) plus multiple others, which you can read whenever desired. For instance, to store the current position of a drag&drop item, you might write its x and y properties into a <input type="hidden"> form element, from where you could transmit them to the server. For more details, see the DHTML API and commands reference.

Developer: Walter Zorn