      1 //
      2 // NOTE : The original code is wrapped so that the defined functions don't collide with existing ones.
      3 // See http://michaux.ca/articles/javascript-namespacing.
      4 // See http://msdn.microsoft.com/en-us/library/259s7zc1%28v=vs.85%29.aspx
      5 //
      6
      7 /** @namespace */
      8 Crypto = typeof Crypto != 'undefined' ? Crypto : {};
      9 /** @namespace */
     10 Crypto.Hex = (function(bs,bm) {
     11
     12 //
     13 // START OF ORIGINAL CODE
     14 //
     15
     16
     17 /*
     18  * conversion functions:
     19  * - num array to string
     20  * - string to hex
     21  */
     22
     23 function s2b(s)
     24 {
     25  var bn=1, r=[0], rn=0, sn=0, sb=256;
     26  var bits=s.length*8;
     27
     28  for(var n=0; n<bits; n++)
     29  {
     30   if((sb<<=1) > 255)
     31   {
     32    sb=1; var c=s.charCodeAt(sn++);
     33   }
     34   if(bn > bm)
     35   {
     36    bn=1;
     37    r[++rn]=0;
     38   }
     39   if(c & sb) r[rn]|=bn;
     40   bn<<=1;
     41  }
     42  return r;
     43 }
     44
     45 function b2s(b)
     46 {
     47  var bn=1, bc=0, r=[0], rb=1, rn=0;
     48  var bits=b.length*bs;
     49  var n, rr='';
     50
     51  for(n=0; n<bits; n++)
     52  {
     53   if(b[bc] & bn) r[rn]|=rb;
     54   if((rb<<=1) > 255)
     55   {
     56    rb=1; r[++rn]=0;
     57   }
     58   if((bn<<=1) > bm)
     59   {
     60    bn=1; bc++;
     61   }
     62  }
     63
     64  while(rn >= 0 && r[rn]==0) rn--;
     65  for(n=0; n<=rn; n++) rr+=String.fromCharCode(r[n]);
     66  return rr;
     67 }
     68
     69 function s2hex(s)
     70 {
     71   var result = '';
     72   for(var i=0; i<s.length; i++)
     73   {
     74     var c = s.charCodeAt(i);
     75     result += ((c<16) ? "0" : "") + c.toString(16);
     76   }
     77   return result;
     78 }
     79
     80 function hex2s(hex)
     81 {
     82   var r='';
     83   if(hex.indexOf("0x") == 0 || hex.indexOf("0X") == 0) hex = hex.substr(2);
     84
     85   if(hex.length%2) hex+='0';
     86
     87   for(var i = 0; i<hex.length; i += 2)
     88     r += String.fromCharCode(parseInt(hex.slice(i, i+2), 16));
     89   return r;
     90 }
     91
     92 //
     93 // END OF ORIGINAL CODE
     94 //
     95
     96 return {
     97     s2b: s2b,
     98     b2s: b2s,
     99     s2hex: s2hex,
    100     hex2s: hex2s
    101 };
    102
    103 })(bs, bm);