r9793 - in helma-ng/trunk/modules: core helma

[email protected] Sat, 16 May 2009 00:18:52 +0200 (CEST)
Newsgroups gmane.comp.java.helma.cvs
Message-ID <20090515221852.037ED3D0D6@mia>
Author: hannes
Date: 2009-05-16 00:18:51 +0200 (Sat, 16 May 2009)
New Revision: 9793

Modified:
   helma-ng/trunk/modules/core/string.js
   helma-ng/trunk/modules/helma/buffer.js
Log:
Rename String.prototype.md5 to String.prototype.digest and allow it to generate other digests than MD5, implement compatible digest method on helma/buffer.Buffer.

Details at http://dev.helma.org/trac/helma/changeset/9793

Modified: helma-ng/trunk/modules/core/string.js
===================================================================
--- helma-ng/trunk/modules/core/string.js	2009-05-15 22:18:50 UTC (rev 9792)
+++ helma-ng/trunk/modules/core/string.js	2009-05-15 22:18:51 UTC (rev 9793)
@@ -391,13 +391,15 @@
 
 
 /**
- * function calculates the md5 hash of a string
- * @return String md5 hash of the string
+ * function calculates a message digest of a string. If no
+ * argument is passed, the MD5 algorithm is used.
+ * @param algorithm the name of the algorithm to use
+ * @return String message digest of the string
  */
-Object.defineProperty(String.prototype, "md5", {
-    value: function() {
+Object.defineProperty(String.prototype, "digest", {
+    value: function(algorithm) {
         var str = asJavaString(this);
-        var md = java.security.MessageDigest.getInstance('MD5');
+        var md = java.security.MessageDigest.getInstance(algorithm || 'MD5');
         var b = md.digest(str.getBytes())
         var buf = new java.lang.StringBuffer(b.length * 2);
         var j;

Modified: helma-ng/trunk/modules/helma/buffer.js
===================================================================
--- helma-ng/trunk/modules/helma/buffer.js	2009-05-15 22:18:50 UTC (rev 9792)
+++ helma-ng/trunk/modules/helma/buffer.js	2009-05-15 22:18:51 UTC (rev 9793)
@@ -1,3 +1,6 @@
+require('core/string');
+include('helma/system');
+
 export('Buffer');
 
 /**
@@ -33,6 +36,23 @@
         content.forEach(fn);
     }
 
+    this.digest = function(algorithm) {
+        var md = java.security.MessageDigest.getInstance(algorithm || 'MD5');
+        content.forEach(function(part) {
+            md.update(asJavaString(part).getBytes());
+        });
+        var b = md.digest();
+        var buf = new java.lang.StringBuffer(b.length * 2);
+        var j;
+        for (var i in b) {
+            j = (b[i] < 0) ? (256 + b[i]) : b[i];
+            if (j < 16)
+                buf.append('0');
+            buf.append(java.lang.Integer.toHexString(j));
+        }
+        return buf.toString();
+    }
+
     if (arguments.length > 0) {
         this.write.apply(this, arguments);
     }