Dart Crypto early access

The Dart project just saw its first crypto libraries land, specifically for SHA1 and SHA256. Also appearing is HMAC support. Learn how to use these very new libraries in this post.

This new functionality is very new. You'll need to pull the latest from the bleeding_edge branch, as of 2012-04-30. It's so new, it's not even wired into the dart: library scheme, nor is it in the SDK yet. I expect crypto libs to get the full SDK treatment very soon.

Here's an example of how to create a SHA256 hash and convert to a hex string:


#import('../dart/lib/crypto/crypto.dart');


// Want this in the crypto lib? Star this bug: http://code.google.com/p/dart/issues/detail?id=2839
String digestToString(List<int> digest) {
  var buf = new StringBuffer();
  for (var part in digest) {
    buf.add("${(part < 16) ? "0" : ""}${part.toRadixString(16).toLowerCase()}");
  }
  return buf.toString();
}


main() {
  var sha = new SHA256();
  print(digestToString(sha.update('hello'.charCodes()).digest()));
}

The current crypto library includes a Hash interface:


/**
 * Interface for cryptographic hash functions.
 *
 * The [update] method is used to add data to the hash. The [digest] method
 * is used to extract the message digest.
 *
 * Once the [digest] method has been called no more data can be added using the
 * [update] method. If [update] is called after the first call to [digest] a
 * HashException is thrown.
 *
 * If multiple instances of a given Hash is needed the [newInstance]
 * method can provide a new instance.
 */
interface Hash {
  /**
   * Add a list of bytes to the hash computation.
   */
  Hash update(List<int> data);


  /**
   * Finish the hash computation and extract the message digest as
   * a list of bytes.
   */
  List<int> digest();


  /**
   * Returns a new instance of this hash function.
   */
  Hash newInstance();


  /**
   * Block size of the hash in bytes.
   */
  int get blockSize();
}

View the full commit for more code and test cases.

As always, the Dart team is interested in your feedback. Please file bugs and feature requests or join the mailing list to share your experience. Thanks for trying Dart!

Popular posts from this blog

Lists and arrays in Dart

The 29 Healthiest Foods on the Planet

Converting Array to List in Scala