Monday, April 30, 2012

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!

Thursday, April 26, 2012

Dart Server supports Web Sockets

[EDIT: Updated on 2013-03-05]

Dart is a structured web programming language that runs on the client and the server. Web sockets are bi-directional data channels for real-time streaming communication between modern web browsers and servers. Thanks to a recent commit, Dart Servers can host Web Socket connections now!

You'll need a copy of the Dart SDK as of 2013-03-05 for this to work.

Dart already ships with basic HttpServer functionality. The new Web Socket is built on top of HttpServer, so it slides right into an existing Dart server app.

The following code snippet is a simple example of a Web Socket echo server running in Dart.

import 'dart:io';

void main() {

  HttpServer.bind('127.0.0.1', port)
    .then((HttpServer server) {
      print('listening for connections on $port');
      
      var sc = new StreamController();
      sc.stream
        .transform(new WebSocketTransformer())
        .listen((message) => handleMessage(message));

      server.listen((HttpRequest request) {
        if (request.uri.path == '/ws') {
          sc.add(request);
        } else {
          /* ... */
        }
      });
    },
    onError: (error) => print("Error starting HTTP server: $error"));
}

Once you have this running, you can use a simple Web Socket test page to connect and receiving echo messages. For example, if you are running the above code, you can connect to ws://localhost:8000/ws

As always, the Dart team wants to hear your feedback. Please don't hesitate to join the Dart mailing list and file bugs and feature requests at dartbug.com. Thanks!

Disclaimer

I'm probably required to say that the views expressed in this blog are my own, and do not necessarily reflect those of my employer.