Skip to content

Using hash algorithms

rubo edited this page Jul 10, 2012 · 1 revision

The following example computes the SHA-512 hash value of a string and returns the hash as a 128-character, hexadecimal-formatted string. The hash string created by this code example is compatible with any SHA-512 hash function (on any platform) that creates a 128-character, hexadecimal-formatted hash string.

var text:String = "abc";
var data:ByteArray = new ByteArray();

data.writeUTFBytes(text);

var sha512:HashAlgorithm = new SHA512();
var hash:ByteArray = sha512.computeHash(data);

trace(ByteArrayUtil.toHexString(hash));

To compute the hash of large files or blocks of large data or to display hash progress status the transformBlock() and the transformFinalBlock() methods must be used.

var rng:ByteArray = RandomNumberGenerator.getBytes(2048);
var md5:HashAlgorithm = new MD5();
var blockSize:int = 16;
var offset:int = 0;
var hash:ByteArray = new ByteArray();
			
while (rng.length - offset > blockSize)
	offset += md5.transformBlock(rng, offset, blockSize, hash, offset);
			
md5.transformFinalBlock(rng, offset, rng.length - offset);
			
trace(ByteArrayUtil.toHexString(md5.hash));
Clone this wiki locally