Sha256 Hashes in ActionScript

Here’s the translation of the SHA256 Hashes example from Go to ActionScript, formatted in Markdown for Hugo:

SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature. Here’s how to compute SHA256 hashes in ActionScript.

package
{
    import flash.utils.ByteArray;
    import com.hurlant.crypto.hash.SHA256;
    import flash.display.Sprite;
    import flash.text.TextField;

    public class SHA256Hashes extends Sprite
    {
        public function SHA256Hashes()
        {
            var s:String = "sha256 this string";

            // Create a new SHA256 instance
            var sha256:SHA256 = new SHA256();

            // Convert the string to ByteArray
            var data:ByteArray = new ByteArray();
            data.writeUTFBytes(s);

            // Compute the hash
            var result:ByteArray = sha256.hash(data);

            // Convert the result to a hex string
            var hexString:String = "";
            for (var i:int = 0; i < result.length; i++) {
                hexString += ("0" + result[i].toString(16)).substr(-2,2);
            }

            // Display the results
            var tf:TextField = new TextField();
            tf.text = s + "\n" + hexString;
            addChild(tf);
        }
    }
}

In ActionScript, we use the com.hurlant.crypto.hash package to compute SHA256 hashes. This package is part of the AS3 Crypto library, which you’ll need to include in your project.

We start by creating a new SHA256 instance. Then, we convert our input string to a ByteArray, which is the expected input format for the hash function.

The hash method of the SHA256 class computes the hash and returns it as a ByteArray. We then convert this byte array to a hexadecimal string for display.

To run this program, you’ll need to set up a Flash or AIR project and include the AS3 Crypto library. The output will be displayed in a TextField on the stage.

Note that if you need cryptographically secure hashes, you should carefully research hash strength!

In ActionScript, you can also compute other types of hashes using similar classes from the com.hurlant.crypto.hash package, such as MD5, SHA1, SHA224, etc.