SHA-256

Revision as of 18:01, 21 March 2020 by Thundergnat (talk | contribs) (Fix Perl 6 -> Raku in comments)

SHA-256 is the recommended stronger alternative to SHA-1. See FIPS PUB 180-4 for implementation details.

Task
SHA-256
You are encouraged to solve this task according to the task description, using any language you may know.

Either by using a dedicated library or implementing the algorithm in your language, show that the SHA-256 digest of the string "Rosetta code" is: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Ada

Library: CryptAda

<lang Ada>with Ada.Text_IO;

with CryptAda.Pragmatics; with CryptAda.Digests.Message_Digests.SHA_256; with CryptAda.Digests.Hashes; with CryptAda.Utils.Format;

procedure RC_SHA_256 is

  use CryptAda.Pragmatics;
  use CryptAda.Digests.Message_Digests;
  use CryptAda.Digests;
  function To_Byte_Array (Item : String) return Byte_Array is
     Result : Byte_Array (Item'Range);
  begin
     for I in Result'Range loop
        Result (I) := Byte (Character'Pos (Item (I)));
     end loop;
     return Result;
  end To_Byte_Array;
  Text    : constant String                := "Rosetta code";
  Bytes   : constant Byte_Array            := To_Byte_Array (Text);
  Handle  : constant Message_Digest_Handle := SHA_256.Get_Message_Digest_Handle;
  Pointer : constant Message_Digest_Ptr    := Get_Message_Digest_Ptr (Handle);
  Hash    : Hashes.Hash;

begin

  Digest_Start  (Pointer);
  Digest_Update (Pointer, Bytes);
  Digest_End    (Pointer, Hash);
  Ada.Text_IO.Put_Line
    ("""" & Text & """: " & CryptAda.Utils.Format.To_Hex_String (Hashes.Get_Bytes (Hash)));

end RC_SHA_256;</lang>

Output:
"Rosetta code": 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF

AutoHotkey

Source: SHA-256 @github by jNizM <lang AutoHotkey>str := "Rosetta code" MsgBox, % "File:`n" (file) "`n`nSHA-256:`n" FileSHA256(file)

SHA256 ============================================================================

SHA256(string, encoding = "utf-8") {

   return CalcStringHash(string, 0x800c, encoding)

}

CalcAddrHash ======================================================================

CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) {

   static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"]
   static b := h.minIndex()
   o := ""
   if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000))
   {
       if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash))
       {
           if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0))
           {
               if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0))
               {
                   VarSetCapacity(hash, hashlength, 0)
                   if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0))
                   {
                       loop, % hashlength
                       {
                           v := NumGet(hash, A_Index - 1, "UChar")
                           o .= h[(v >> 4) + b] h[(v & 0xf) + b]
                       }
                   }
               }
           }
           DllCall("advapi32\CryptDestroyHash", "Ptr", hHash)
       }
       DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0)
   }
   return o

}

CalcStringHash ====================================================================

CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) {

   chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1
   length := (StrPut(string, encoding) - 1) * chrlength
   VarSetCapacity(data, length, 0)
   StrPut(string, &data, floor(length / chrlength), encoding)
   return CalcAddrHash(&data, length, algid, hash, hashlength)

}</lang>

Output:
String:    Rosetta code
SHA-256:   764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF

AWK

Using the system function as a 'library'. <lang AWK>{

   ("echo -n " $0 " | sha256sum") | getline sha;
   gsub(/[^0-9a-zA-Z]/, "", sha);
   print sha;

} </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

BaCon

<lang qbasic>PRAGMA INCLUDE <openssl/sha.h> PRAGMA LDFLAGS -lcrypto

OPTION MEMTYPE unsigned char

DECLARE result TYPE unsigned char*

result = SHA256("Rosetta code", 12, 0)

FOR i = 0 TO SHA256_DIGEST_LENGTH-1

   PRINT PEEK(result+i) FORMAT "%02x"

NEXT

PRINT</lang>

Output:
user@host $ bacon sha256
Converting 'sha256.bac'... done, 14 lines were processed in 0.002 seconds.
Compiling 'sha256.bac'... cc  -c sha256.bac.c
cc -o sha256 sha256.bac.o -lbacon -lm  -lcrypto
Done, program 'sha256' ready.
user@host $ ./sha256 
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

BBC BASIC

Library

<lang bbcbasic> PRINT FNsha256("Rosetta code")

     END
     
     DEF FNsha256(message$)
     LOCAL buflen%, buffer%, hcont%, hprov%, hhash%, hash$, i%
     CALG_SHA_256 = &800C
     HP_HASHVAL = 2
     CRYPT_NEWKEYSET = 8
     PROV_RSA_AES = 24
     buflen% = 128
     DIM buffer% LOCAL buflen%-1
     SYS "CryptAcquireContext", ^hcont%, 0, \
     \   "Microsoft Enhanced RSA and AES Cryptographic Provider", \
     \   PROV_RSA_AES, CRYPT_NEWKEYSET
     SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_AES, 0
     SYS "CryptCreateHash", hprov%, CALG_SHA_256, 0, 0, ^hhash%
     SYS "CryptHashData", hhash%, message$, LEN(message$), 0
     SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0
     SYS "CryptDestroyHash", hhash%
     SYS "CryptReleaseContext", hprov%
     SYS "CryptReleaseContext", hcont%
     FOR i% = 0 TO buflen%-1
       hash$ += RIGHT$("0" + STR$~buffer%?i%, 2)
     NEXT
     = hash$</lang>

Output:

764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF

Native

<lang bbcbasic> REM SHA-256 calculation by Richard Russell in BBC BASIC for Windows

     REM Must run in FLOAT64 mode:
     *FLOAT64
     
     REM Test message for validation:
     message$ = "Rosetta code"
     
     REM Initialize variables:
     h0% = &6A09E667
     h1% = &BB67AE85
     h2% = &3C6EF372
     h3% = &A54FF53A
     h4% = &510E527F
     h5% = &9B05688C
     h6% = &1F83D9AB
     h7% = &5BE0CD19
     
     REM Create table of constants:
     DIM k%(63) : k%() = \
     \ &428A2F98, &71374491, &B5C0FBCF, &E9B5DBA5, &3956C25B, &59F111F1, &923F82A4, &AB1C5ED5, \
     \ &D807AA98, &12835B01, &243185BE, &550C7DC3, &72BE5D74, &80DEB1FE, &9BDC06A7, &C19BF174, \
     \ &E49B69C1, &EFBE4786, &0FC19DC6, &240CA1CC, &2DE92C6F, &4A7484AA, &5CB0A9DC, &76F988DA, \
     \ &983E5152, &A831C66D, &B00327C8, &BF597FC7, &C6E00BF3, &D5A79147, &06CA6351, &14292967, \
     \ &27B70A85, &2E1B2138, &4D2C6DFC, &53380D13, &650A7354, &766A0ABB, &81C2C92E, &92722C85, \
     \ &A2BFE8A1, &A81A664B, &C24B8B70, &C76C51A3, &D192E819, &D6990624, &F40E3585, &106AA070, \
     \ &19A4C116, &1E376C08, &2748774C, &34B0BCB5, &391C0CB3, &4ED8AA4A, &5B9CCA4F, &682E6FF3, \
     \ &748F82EE, &78A5636F, &84C87814, &8CC70208, &90BEFFFA, &A4506CEB, &BEF9A3F7, &C67178F2
     
     Length% = LEN(message$)*8
     
     REM Pre-processing:
     REM append the bit '1' to the message:
     message$ += CHR$&80
     
     REM append k bits '0', where k is the minimum number >= 0 such that
     REM the resulting message length (in bits) is congruent to 448 (mod 512)
     WHILE (LEN(message$) MOD 64) <> 56
       message$ += CHR$0
     ENDWHILE
     
     REM append length of message (before pre-processing), in bits, as
     REM 64-bit big-endian integer:
     FOR I% = 56 TO 0 STEP -8
       message$ += CHR$(Length% >>> I%)
     NEXT
     
     REM Process the message in successive 512-bit chunks:
     REM break message into 512-bit chunks, for each chunk
     REM break chunk into sixteen 32-bit big-endian words w[i], 0 <= i <= 15
     
     DIM w%(63)
     FOR chunk% = 0 TO LEN(message$) DIV 64 - 1
       
       FOR i% = 0 TO 15
         w%(i%) = !(!^message$ + 64*chunk% + 4*i%)
         SWAP ?(^w%(i%)+0),?(^w%(i%)+3)
         SWAP ?(^w%(i%)+1),?(^w%(i%)+2)
       NEXT i%
       
       REM Extend the sixteen 32-bit words into sixty-four 32-bit words:
       FOR i% = 16 TO 63
         s0% = FNrr(w%(i%-15),7) EOR FNrr(w%(i%-15),18) EOR (w%(i%-15) >>> 3)
         s1% = FNrr(w%(i%-2),17) EOR FNrr(w%(i%-2),19) EOR (w%(i%-2) >>> 10)
         w%(i%) = FN32(w%(i%-16) + s0% + w%(i%-7) + s1%)
       NEXT i%
       
       REM Initialize hash value for this chunk:
       a% = h0%
       b% = h1%
       c% = h2%
       d% = h3%
       e% = h4%
       f% = h5%
       g% = h6%
       h% = h7%
       
       REM Main loop:
       FOR i% = 0 TO 63
         s0% = FNrr(a%,2) EOR FNrr(a%,13) EOR FNrr(a%,22)
         maj% = (a% AND b%) EOR (a% AND c%) EOR (b% AND c%)
         t2% = FN32(s0% + maj%)
         s1% = FNrr(e%,6) EOR FNrr(e%,11) EOR FNrr(e%,25)
         ch% = (e% AND f%) EOR ((NOT e%) AND g%)
         t1% = FN32(h% + s1% + ch% + k%(i%) + w%(i%))
         
         h% = g%
         g% = f%
         f% = e%
         e% = FN32(d% + t1%)
         d% = c%
         c% = b%
         b% = a%
         a% = FN32(t1% + t2%)
         
       NEXT i%
       
       REM Add this chunk's hash to result so far:
       h0% = FN32(h0% + a%)
       h1% = FN32(h1% + b%)
       h2% = FN32(h2% + c%)
       h3% = FN32(h3% + d%)
       h4% = FN32(h4% + e%)
       h5% = FN32(h5% + f%)
       h6% = FN32(h6% + g%)
       h7% = FN32(h7% + h%)
       
     NEXT chunk%
     
     REM Produce the final hash value (big-endian):
     hash$ = FNhex(h0%) + " " + FNhex(h1%) + " " + FNhex(h2%) + " " + FNhex(h3%) + \
     \ " " + FNhex(h4%) + " " + FNhex(h5%) + " " + FNhex(h6%) + " " + FNhex(h7%)
     
     PRINT hash$
     END
     
     DEF FNrr(A%,I%) = (A% >>> I%) OR (A% << (32-I%))
     
     DEF FNhex(A%) = RIGHT$("0000000"+STR$~A%,8)
     
     DEF FN32(n#)
     WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE
     WHILE n# < &80000000 : n# += 2^32 : ENDWHILE
     = n#</lang>

Output:

764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF

C

Requires OpenSSL, compile flag: -lssl -lcrypto <lang c>#include <stdio.h>

  1. include <string.h>
  2. include <openssl/sha.h>

int main (void) { const char *s = "Rosetta code"; unsigned char *d = SHA256(s, strlen(s), 0);

int i; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) printf("%02x", d[i]); putchar('\n');

return 0; }</lang>

C#

<lang csharp>using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace RosettaCode.SHA256 {

   [TestClass]
   public class SHA256ManagedTest
   {
       [TestMethod]
       public void TestComputeHash()
       {
           var buffer = Encoding.UTF8.GetBytes("Rosetta code");
           var hashAlgorithm = new SHA256Managed();
           var hash = hashAlgorithm.ComputeHash(buffer);
           Assert.AreEqual(
               "76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF",
               BitConverter.ToString(hash));
       }
   }

}</lang>

C++

Uses crypto++. Compile it with -lcryptopp

<lang cpp>#include <iostream>

  1. include <cryptopp/filters.h>
  2. include <cryptopp/hex.h>
  3. include <cryptopp/sha.h>

int main(int argc, char **argv){ CryptoPP::SHA256 hash; std::string digest; std::string message = "Rosetta code";

CryptoPP::StringSource s(message, true, new CryptoPP::HashFilter(hash, new CryptoPP::HexEncoder( new CryptoPP::StringSink(digest))));

std::cout << digest << std::endl;

return 0; } </lang>

Caché ObjectScript

USER>set hash=$System.Encryption.SHAHash(256, "Rosetta code")
USER>zzdump hash
0000: 76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39
0010: 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF

Clojure

Library: pandect

<lang clojure>(use 'pandect.core) (sha256 "Rosetta code")</lang>

Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"

Common Lisp

Library: Ironclad

<lang lisp>(ql:quickload 'ironclad) (defun sha-256 (str)

 (ironclad:byte-array-to-hex-string
   (ironclad:digest-sequence :sha256 
                             (ironclad:ascii-string-to-byte-array str))))

(sha-256 "Rosetta code")</lang>

Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"

D

Standard Version

<lang d>void main() {

   import std.stdio, std.digest.sha;
   writefln("%-(%02x%)", "Rosetta code".sha256Of);

}</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Simple Implementation

<lang d>// Copyright (C) 2005, 2006 Free Software Foundation, Inc. GNU License. // Translated to D language. Only lightly tested, not for serious use.

import core.stdc.string: memcpy; import core.bitop: bswap;

struct SHA256 {

   enum uint BLOCK_SIZE = 4096;
   static assert(BLOCK_SIZE % 64 == 0, "Invalid BLOCK_SIZE.");
   uint[8] state;
   uint[2] total;
   uint bufLen;
   union {
       uint[32] buffer;
       ubyte[buffer.sizeof] bufferB;
   }
   alias TResult = ubyte[256 / 8];
   version(WORDS_BIGENDIAN) {
       static uint bswap(in uint n) pure nothrow @safe @nogc { return n; }
   }
   // Bytes used to pad the buffer to the next 64-byte boundary.
   static immutable ubyte[64] fillBuf = [0x80, 0 /* , 0, 0, ...  */];


   /** Initialize structure containing state of computation.
   Takes a pointer to a 256 bit block of data (eight 32 bit ints) and
   intializes it to the start constants of the SHA256 algorithm. This
   must be called before using hash in the call to sha256_hash. */
   void init() pure nothrow @safe @nogc {
       state = [0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU,
                0x510e527fU, 0x9b05688cU, 0x1f83d9abU, 0x5be0cd19U];
       total[] = 0;
       bufLen = 0;
   }


   /** Starting with the result of former calls of this function (or
   the initialization function) update the context for the next LEN
   bytes starting at BUFFER.
   It is not required that LEN is a multiple of 64. */
   void processBytes(in ubyte[] inBuffer) pure nothrow @nogc {
       // When we already have some bits in our internal
       // buffer concatenate both inputs first.
       const(ubyte)* inBufferPtr = inBuffer.ptr;
       auto len = inBuffer.length;
       if (bufLen != 0) {
           immutable size_t left_over = bufLen;
           immutable size_t add = (128 - left_over > len) ?
                                  len :
                                  128 - left_over;
           memcpy(&bufferB[left_over], inBufferPtr, add);
           bufLen += add;
           if (bufLen > 64) {
               processBlock(bufferB[0 .. bufLen & ~63]);
               bufLen &= 63;
               // The regions in the following copy operation cannot overlap.
               memcpy(bufferB.ptr, &bufferB[(left_over + add) & ~63], bufLen);
           }
           inBufferPtr += add;
           len -= add;
       }
       // Process available complete blocks.
       if (len >= 64) {
           processBlock(inBufferPtr[0 .. len & ~63]);
           inBufferPtr += (len & ~63);
           len &= 63;
       }
       // Move remaining bytes in internal buffer.
       if (len > 0) {
           size_t left_over = bufLen;
           memcpy(&bufferB[left_over], inBufferPtr, len);
           left_over += len;
           if (left_over >= 64) {
               processBlock(bufferB[0 .. 64]);
               left_over -= 64;
               memcpy(bufferB.ptr, &bufferB[64], left_over);
           }
           bufLen = left_over;
       }
   }


   /** Starting with the result of former calls of this function
   (or the initialization function) update the context ctx for
   the next len bytes starting at buffer.
   It is necessary that len is a multiple of 64. */
   void processBlock(in ubyte[] inBuffer)
   pure nothrow @nogc in {
       assert(inBuffer.length % 64 == 0);
   } body {
       // Round functions.
       static uint F1(in uint e, in uint f, in uint g) pure nothrow @safe @nogc {
           return g ^ (e & (f ^ g));
       }
       static uint F2(in uint a, in uint b, in uint c) pure nothrow @safe @nogc {
           return (a & b) | (c & (a | b));
       }
       immutable len = inBuffer.length;
       auto words = cast(uint*)inBuffer.ptr;
       immutable size_t nWords = len / uint.sizeof;
       const uint* endp = words + nWords;
       uint[16] x = void;
       auto a = state[0];
       auto b = state[1];
       auto c = state[2];
       auto d = state[3];
       auto e = state[4];
       auto f = state[5];
       auto g = state[6];
       auto h = state[7];
       // First increment the byte count. FIPS PUB 180-2 specifies the
       // possible length of the file up to 2^64 bits. Here we only
       // compute the number of bytes.  Do a double word increment.
       total[0] += len;
       if (total[0] < len)
           total[1]++;
       static uint rol(in uint x, in uint n) pure nothrow @safe @nogc {
           return (x << n) | (x >> (32 - n)); }
       static uint S0(in uint x) pure nothrow @safe @nogc {
           return rol(x, 25) ^ rol(x, 14) ^ (x >> 3); }
       static uint S1(in uint x) pure nothrow @safe @nogc {
           return rol(x, 15) ^ rol(x, 13) ^ (x >> 10); }
       static uint SS0(in uint x) pure nothrow @safe @nogc {
           return rol(x, 30) ^ rol(x,19) ^ rol(x, 10); }
       static uint SS1(in uint x) pure nothrow @safe @nogc {
           return rol(x, 26) ^ rol(x, 21) ^ rol(x, 7); }
       uint M(in uint I) pure nothrow @safe @nogc {
           immutable uint tm = S1(x[(I - 2) & 0x0f]) +
                               x[(I - 7) & 0x0f] +
                               S0(x[(I - 15) & 0x0f]) +
                               x[I & 0x0f];
           x[I & 0x0f] = tm;
           return tm;
       }
       static void R(in uint a, in uint b, in uint c, ref uint d,
                     in uint e, in uint f, in uint g, ref uint h,
                     in uint k, in uint m) pure nothrow @safe @nogc {
           immutable t0 = SS0(a) + F2(a, b, c);
           immutable t1 = h + SS1(e) + F1(e, f, g) + k + m;
           d += t1;
           h = t0 + t1;
       }
       // SHA256 round constants.
       static immutable uint[64] K = [
           0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U,
           0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U,
           0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U,
           0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U,
           0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU,
           0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU,
           0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U,
           0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U,
           0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U,
           0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U,
           0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U,
           0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U,
           0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U,
           0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U,
           0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U,
           0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U];
       while (words < endp) {
           foreach (ref xi; x) {
               xi = bswap(*words);
               words++;
           }
           R(a, b, c, d, e, f, g, h, K[ 0], x[ 0]);
           R(h, a, b, c, d, e, f, g, K[ 1], x[ 1]);
           R(g, h, a, b, c, d, e, f, K[ 2], x[ 2]);
           R(f, g, h, a, b, c, d, e, K[ 3], x[ 3]);
           R(e, f, g, h, a, b, c, d, K[ 4], x[ 4]);
           R(d, e, f, g, h, a, b, c, K[ 5], x[ 5]);
           R(c, d, e, f, g, h, a, b, K[ 6], x[ 6]);
           R(b, c, d, e, f, g, h, a, K[ 7], x[ 7]);
           R(a, b, c, d, e, f, g, h, K[ 8], x[ 8]);
           R(h, a, b, c, d, e, f, g, K[ 9], x[ 9]);
           R(g, h, a, b, c, d, e, f, K[10], x[10]);
           R(f, g, h, a, b, c, d, e, K[11], x[11]);
           R(e, f, g, h, a, b, c, d, K[12], x[12]);
           R(d, e, f, g, h, a, b, c, K[13], x[13]);
           R(c, d, e, f, g, h, a, b, K[14], x[14]);
           R(b, c, d, e, f, g, h, a, K[15], x[15]);
           R(a, b, c, d, e, f, g, h, K[16], M(16));
           R(h, a, b, c, d, e, f, g, K[17], M(17));
           R(g, h, a, b, c, d, e, f, K[18], M(18));
           R(f, g, h, a, b, c, d, e, K[19], M(19));
           R(e, f, g, h, a, b, c, d, K[20], M(20));
           R(d, e, f, g, h, a, b, c, K[21], M(21));
           R(c, d, e, f, g, h, a, b, K[22], M(22));
           R(b, c, d, e, f, g, h, a, K[23], M(23));
           R(a, b, c, d, e, f, g, h, K[24], M(24));
           R(h, a, b, c, d, e, f, g, K[25], M(25));
           R(g, h, a, b, c, d, e, f, K[26], M(26));
           R(f, g, h, a, b, c, d, e, K[27], M(27));
           R(e, f, g, h, a, b, c, d, K[28], M(28));
           R(d, e, f, g, h, a, b, c, K[29], M(29));
           R(c, d, e, f, g, h, a, b, K[30], M(30));
           R(b, c, d, e, f, g, h, a, K[31], M(31));
           R(a, b, c, d, e, f, g, h, K[32], M(32));
           R(h, a, b, c, d, e, f, g, K[33], M(33));
           R(g, h, a, b, c, d, e, f, K[34], M(34));
           R(f, g, h, a, b, c, d, e, K[35], M(35));
           R(e, f, g, h, a, b, c, d, K[36], M(36));
           R(d, e, f, g, h, a, b, c, K[37], M(37));
           R(c, d, e, f, g, h, a, b, K[38], M(38));
           R(b, c, d, e, f, g, h, a, K[39], M(39));
           R(a, b, c, d, e, f, g, h, K[40], M(40));
           R(h, a, b, c, d, e, f, g, K[41], M(41));
           R(g, h, a, b, c, d, e, f, K[42], M(42));
           R(f, g, h, a, b, c, d, e, K[43], M(43));
           R(e, f, g, h, a, b, c, d, K[44], M(44));
           R(d, e, f, g, h, a, b, c, K[45], M(45));
           R(c, d, e, f, g, h, a, b, K[46], M(46));
           R(b, c, d, e, f, g, h, a, K[47], M(47));
           R(a, b, c, d, e, f, g, h, K[48], M(48));
           R(h, a, b, c, d, e, f, g, K[49], M(49));
           R(g, h, a, b, c, d, e, f, K[50], M(50));
           R(f, g, h, a, b, c, d, e, K[51], M(51));
           R(e, f, g, h, a, b, c, d, K[52], M(52));
           R(d, e, f, g, h, a, b, c, K[53], M(53));
           R(c, d, e, f, g, h, a, b, K[54], M(54));
           R(b, c, d, e, f, g, h, a, K[55], M(55));
           R(a, b, c, d, e, f, g, h, K[56], M(56));
           R(h, a, b, c, d, e, f, g, K[57], M(57));
           R(g, h, a, b, c, d, e, f, K[58], M(58));
           R(f, g, h, a, b, c, d, e, K[59], M(59));
           R(e, f, g, h, a, b, c, d, K[60], M(60));
           R(d, e, f, g, h, a, b, c, K[61], M(61));
           R(c, d, e, f, g, h, a, b, K[62], M(62));
           R(b, c, d, e, f, g, h, a, K[63], M(63));
           a = state[0] += a;
           b = state[1] += b;
           c = state[2] += c;
           d = state[3] += d;
           e = state[4] += e;
           f = state[5] += f;
           g = state[6] += g;
           h = state[7] += h;
       }
   }


   /** Process the remaining bytes in the internal buffer and the
   usual prolog according to the standard and write the result to
   resBuf.
   Important: On some systems it is required that resBuf is correctly
   aligned for a 32-bit value. */
   void conclude() pure nothrow @nogc {
       // Take yet unprocessed bytes into account.
       immutable bytes = bufLen;
       immutable size_t size = (bytes < 56) ? 64 / 4 : 64 * 2 / 4;
       // Now count remaining bytes.
       total[0] += bytes;
       if (total[0] < bytes)
           total[1]++;
       // Put the 64-bit file length in *bits* at the end of
       // the buffer.
       buffer[size - 2] = bswap((total[1] << 3) | (total[0] >> 29));
       buffer[size - 1] = bswap(total[0] << 3);
       memcpy(&bufferB[bytes], fillBuf.ptr, (size - 2) * 4 - bytes);
       // Process last bytes.
       processBlock(bufferB[0 .. size * 4]);
   }


   /** Put result from this in first 32 bytes following resBuf. The
   result must be in little endian byte order.
   Important: On some systems it is required that resBuf is correctly
   aligned for a 32-bit value. */
   ref TResult read(return ref TResult resBuf) pure nothrow @nogc {
       foreach (immutable i, immutable s; state)
           (cast(uint*)resBuf.ptr)[i] = bswap(s);
       return resBuf;
   }


   /** Process the remaining bytes in the buffer and put result from
   CTX in first 32 (28) bytes following resBuf.  The result is always
   in little endian byte order, so that a byte-wise output yields to
   the wanted ASCII representation of the message digest.
   Important: On some systems it is required that resBuf be correctly
   aligned for a 32 bits value. */
   ref TResult finish(return ref TResult resBuf) pure nothrow @nogc {
       conclude;
       return read(resBuf);
   }


   /** Compute SHA512 message digest for LEN bytes beginning at
   buffer. The result is always in little endian byte order, so that
   a byte-wise output yields to the wanted ASCII representation of
   the message digest. */
   static ref TResult digest(in ubyte[] inBuffer, return ref TResult resBuf)
   pure nothrow @nogc {
       SHA256 sha = void;
       // Initialize the computation context.
       sha.init;
       // Process whole buffer but last len % 64 bytes.
       sha.processBytes(inBuffer);
       // Put result in desired memory area.
       return sha.finish(resBuf);
   }


   /// ditto
   static TResult digest(in ubyte[] inBuffer) pure nothrow @nogc {
       align(4) TResult resBuf = void;
       return digest(inBuffer, resBuf);
   }

}


version (sha_256_main) {

   void main() {
       import std.stdio, std.string;
       immutable data = "Rosetta code".representation;
       writefln("%(%02x%)", SHA256.digest(data));
   }

}</lang> Compile with -version=sha_256_main to run the main function.

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

This is a moderately efficient implementation, about 100 MB/s on a 4096 bytes input buffer on a 32 bit system, using the ldc2 compiler. On a more modern CPU (Intel Ivy Bridge) using HyperThreading, handwritten assembly by Intel is about twice faster.

DWScript

<lang delphi>PrintLn( HashSHA256.HashData('Rosetta code') );</lang>

Emacs Lisp

<lang Lisp>(secure-hash 'sha256 "Rosetta code")  ;; as string of hex digits</lang>

Erlang

More code to get the correct display format than doing the calculation.

Output:
10> Binary =  crypto:hash( sha256, "Rosetta code" ).
11> lists:append( [erlang:integer_to_list(X, 16) || <<X:8/integer>> <= Binary] ).
"764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF"

F#

<lang fsharp>open System.Security.Cryptography open System.Text

"Rosetta code" |> Encoding.ASCII.GetBytes |> (new SHA256Managed()).ComputeHash |> System.BitConverter.ToString |> printfn "%s" </lang>

Output:
76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF

Factor

Works with: Factor version 0.98

<lang factor>USING: checksums checksums.sha io math.parser ;

"Rosetta code" sha-256 checksum-bytes bytes>hex-string print</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Fortran

Intel Fortran on Windows

Using Windows API. See CryptAcquireContext, CryptCreateHash, CryptHashData and CryptGetHashParam on MSDN.

With the file rc.txt containing the string "Rosetta Code":

sha256 rc.txt
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF rc.txt (12 bytes)

<lang fortran>module sha256_mod

   use kernel32
   use advapi32
   implicit none
   integer, parameter :: SHA256LEN = 32

contains

   subroutine sha256hash(name, hash, dwStatus, filesize)
       implicit none
       character(*) :: name
       integer, parameter :: BUFLEN = 32768
       integer(HANDLE) :: hFile, hProv, hHash
       integer(DWORD) :: dwStatus, nRead
       integer(BOOL) :: status
       integer(BYTE) :: buffer(BUFLEN)
       integer(BYTE) :: hash(SHA256LEN)
       integer(UINT64) :: filesize

       dwStatus = 0
       filesize = 0
       hFile = CreateFile(trim(name) // char(0), GENERIC_READ, FILE_SHARE_READ, NULL, &
                          OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL)

       if (hFile == INVALID_HANDLE_VALUE) then
           dwStatus = GetLastError()
           print *, "CreateFile failed."
           return
       end if

       if (CryptAcquireContext(hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, &
                               CRYPT_VERIFYCONTEXT) == FALSE) then

           dwStatus = GetLastError()
           print *, "CryptAcquireContext failed.", dwStatus
           goto 3
       end if

       if (CryptCreateHash(hProv, CALG_SHA_256, 0_ULONG_PTR, 0_DWORD, hHash) == FALSE) then

           dwStatus = GetLastError()
           print *, "CryptCreateHash failed."
           go to 2
       end if

       do
           status = ReadFile(hFile, loc(buffer), BUFLEN, nRead, NULL)
           if (status == FALSE .or. nRead == 0) exit
           filesize = filesize + nRead
           if (CryptHashData(hHash, buffer, nRead, 0) == FALSE) then
               dwStatus = GetLastError()
               print *, "CryptHashData failed."
               go to 1
           end if
       end do

       if (status == FALSE) then
           dwStatus = GetLastError()
           print *, "ReadFile failed."
           go to 1
       end if

       nRead = SHA256LEN
       if (CryptGetHashParam(hHash, HP_HASHVAL, hash, nRead, 0) == FALSE) then
           dwStatus = GetLastError()
           print *, "CryptGetHashParam failed."
       end if

     1 status = CryptDestroyHash(hHash)
     2 status = CryptReleaseContext(hProv, 0)
     3 status = CloseHandle(hFile)
   end subroutine

end module

program sha256

   use sha256_mod
   implicit none
   integer :: n, m, i, j
   character(:), allocatable :: name
   integer(DWORD) :: dwStatus
   integer(BYTE) :: hash(SHA256LEN)
   integer(UINT64) :: filesize

   n = command_argument_count()
   do i = 1, n
       call get_command_argument(i, length=m)
       allocate(character(m) :: name)
       call get_command_argument(i, name)
       call sha256hash(name, hash, dwStatus, filesize)
       if (dwStatus == 0) then
           do j = 1, SHA256LEN
               write(*, "(Z2.2)", advance="NO") hash(j)
           end do
           write(*, "(' ',A,' (',G0,' bytes)')") name, filesize
       end if
       deallocate(name)
   end do

end program</lang>

Free Pascal

<lang pascal>program rosettaCodeSHA256;

uses

 SysUtils, DCPsha256;

var

 ros: String;
 sha256 : TDCP_sha256;
 digest : array[0..63] of byte;
 i: Integer;
 output: String;

begin

 ros := 'Rosetta code';
 sha256 := TDCP_sha256.Create(nil);
 sha256.init;
 sha256.UpdateStr(ros);
 sha256.Final(digest);
 output := ;
 for i := 0 to 31 do begin
   output := output + intToHex(digest[i], 2);
 end;
 writeln(lowerCase(output));

end.</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

FreeBASIC

<lang freebasic>' version 20-10-2016 ' FIPS PUB 180-4 ' compile with: fbc -s console

Function SHA_256(test_str As String) As String

 #Macro Ch (x, y, z)
   (((x) And (y)) Xor ((Not (x)) And z))
 #EndMacro
 #Macro Maj (x, y, z)
   (((x) And (y)) Xor ((x) And (z)) Xor ((y) And (z)))
 #EndMacro
 #Macro sigma0 (x)
   (((x) Shr 2 Or (x) Shl 30) Xor ((x) Shr 13 Or (x) Shl 19) Xor ((x) Shr 22 Or (x) Shl 10))
 #EndMacro
 #Macro sigma1 (x)
   (((x) Shr 6 Or (x) Shl 26) Xor ((x) Shr 11 Or (x) Shl 21) Xor ((x) Shr 25 Or (x) Shl 7))
 #EndMacro
 #Macro sigma2 (x)
   (((x) Shr 7 Or (x) Shl 25) Xor ((x) Shr 18 Or (x) Shl 14) Xor ((x) Shr 3))
 #EndMacro
 #Macro sigma3 (x)
   (((x) Shr 17 Or (x) Shl 15) Xor ((x) Shr 19 Or (x) Shl 13) Xor ((x) Shr 10))
 #EndMacro
 Dim As String message = test_str   ' strings are passed as ByRef's
 Dim As Long i, j
 Dim As UByte Ptr ww1
 Dim As UInteger<32> Ptr ww4
 Dim As ULongInt l = Len(message)
 ' set the first bit after the message to 1
 message = message + Chr(1 Shl 7)
 ' add one char to the length
 Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
 ' check if we have enough room for inserting the length
 If padding < 8 Then padding = padding + 64
 message = message + String(padding, Chr(0))   ' adjust length
 Dim As ULong l1 = Len(message)                ' new length
 l = l * 8    ' orignal length in bits
 ' create ubyte ptr to point to l ( = length in bits)
 Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
 For i = 0 To 7  'copy length of message to the last 8 bytes
   message[l1 -1 - i] = ub_ptr[i]
 Next
 'table of constants
 Dim As UInteger<32> K(0 To ...) = _
 { &H428a2f98, &H71374491, &Hb5c0fbcf, &He9b5dba5, &H3956c25b, &H59f111f1, _
   &H923f82a4, &Hab1c5ed5, &Hd807aa98, &H12835b01, &H243185be, &H550c7dc3, _
   &H72be5d74, &H80deb1fe, &H9bdc06a7, &Hc19bf174, &He49b69c1, &Hefbe4786, _
   &H0fc19dc6, &H240ca1cc, &H2de92c6f, &H4a7484aa, &H5cb0a9dc, &H76f988da, _
   &H983e5152, &Ha831c66d, &Hb00327c8, &Hbf597fc7, &Hc6e00bf3, &Hd5a79147, _
   &H06ca6351, &H14292967, &H27b70a85, &H2e1b2138, &H4d2c6dfc, &H53380d13, _
   &H650a7354, &H766a0abb, &H81c2c92e, &H92722c85, &Ha2bfe8a1, &Ha81a664b, _
   &Hc24b8b70, &Hc76c51a3, &Hd192e819, &Hd6990624, &Hf40e3585, &H106aa070, _
   &H19a4c116, &H1e376c08, &H2748774c, &H34b0bcb5, &H391c0cb3, &H4ed8aa4a, _
   &H5b9cca4f, &H682e6ff3, &H748f82ee, &H78a5636f, &H84c87814, &H8cc70208, _
   &H90befffa, &Ha4506ceb, &Hbef9a3f7, &Hc67178f2 }
 Dim As UInteger<32> h0 = &H6a09e667
 Dim As UInteger<32> h1 = &Hbb67ae85
 Dim As UInteger<32> h2 = &H3c6ef372
 Dim As UInteger<32> h3 = &Ha54ff53a
 Dim As UInteger<32> h4 = &H510e527f
 Dim As UInteger<32> h5 = &H9b05688c
 Dim As UInteger<32> h6 = &H1f83d9ab
 Dim As UInteger<32> h7 = &H5be0cd19
 Dim As UInteger<32> a, b, c, d, e, f, g, h
 Dim As UInteger<32> t1, t2, w(0 To 63)


 For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes
   ww1 = Cast(UByte Ptr, @message[j * 64])
   ww4 = Cast(UInteger<32> Ptr, @message[j * 64])
   For i = 0 To 60 Step 4  'little endian -> big endian
     Swap ww1[i   ], ww1[i +3]
     Swap ww1[i +1], ww1[i +2]
   Next
   For i = 0 To 15    ' copy the 16 32bit block into the array
     W(i) = ww4[i]
   Next
   For i = 16 To 63   ' fill the rest of the array
     w(i) = sigma3(W(i -2)) + W(i -7) + sigma2(W(i -15)) + W(i -16)
   Next
   a = h0 : b = h1 : c = h2 : d = h3 : e = h4 : f = h5 : g = h6 : h = h7
   For i = 0 To 63
     t1 = h + sigma1(e) + Ch(e, f, g) + K(i) + W(i)
     t2 = sigma0(a) + Maj(a, b, c)
     h = g : g = f : f = e
     e = d + t1
     d = c : c = b : b = a
     a = t1 + t2
   Next
   h0 += a : h1 += b : h2 += c : h3 += d
   h4 += e : h5 += f : h6 += g : h7 += h
 Next j
 Dim As String answer  = Hex(h0, 8) + Hex(h1, 8) + Hex(h2, 8) + Hex(h3, 8)
               answer += Hex(h4, 8) + Hex(h5, 8) + Hex(h6, 8) + Hex(h7, 8)
 Return LCase(answer)

End Function

' ------=< MAIN >=------

Dim As String test = "Rosetta code" Print test; " => "; SHA_256(test)


' empty keyboard buffer While Inkey <> "" : Wend Print : Print "hit any key to end program" Sleep End</lang>

Output:
Rosetta code => 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Frink

Frink has convenience methods to use any message hashing algorithm provided by your Java Virtual Machine. The result can be returned as a hexadecimal string, an integer, or an array of bytes. <lang frink>println[messageDigest["Rosetta code", "SHA-256"]]</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

FunL

A SHA-256 function can be defined using the Java support library.

<lang funl>native java.security.MessageDigest

def sha256Java( message ) = map( a -> format('%02x', a), list(MessageDigest.getInstance('SHA-256').digest(message.getBytes('UTF-8'))) ).mkString()</lang>

Here is a definition implemented as a direct translation of the pseudocode at SHA-256.

<lang funl>def sha256( message ) =

 //Initialize hash values
 h0 = 0x6a09e667
 h1 = 0xbb67ae85
 h2 = 0x3c6ef372
 h3 = 0xa54ff53a
 h4 = 0x510e527f
 h5 = 0x9b05688c
 h6 = 0x1f83d9ab
 h7 = 0x5be0cd19
 // Initialize array of round constants
 k(0..63) = [
   0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
   0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
   0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
   0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
   0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
   0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
   0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
   0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]
 // Pre-processing
 bits = BitArray( message.getBytes('UTF-8') )
 len = bits.length()
 bits.append( 1 )
 r = bits.length()%512
 bits.appendAll( 0 | _ <- 1..(if r > 448 then 512 - r + 448 else 448 - r) )
 bits.appendInt( 0 )
 bits.appendInt( len )
 words = bits.toIntVector()
 // Process the message in successive 512-bit chunks
 for chunk <- 0:words.length():16
   w(0..15) = words(chunk..chunk+15)
   // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
   for i <- 16..63
     s0 = (w(i-15) rotateright 7) xor (w(i-15) rotateright 18) xor (w(i-15) >>> 3)
     s1 = (w(i-2) rotateright 17) xor (w(i-2) rotateright 19) xor (w(i-2) >>> 10)
     w(i) = w(i-16) + s0 + w(i-7) + s1
   // Initialize working variables to current hash value
   a = h0
   b = h1
   c = h2
   d = h3
   e = h4
   f = h5
   g = h6
   h = h7
   // Compression function main loop
   for i <- 0..63
     S1 = (e rotateright 6) xor (e rotateright 11) xor (e rotateright 25)
     ch = (e and f) xor ((not e) and g)
     temp1 = h + S1 + ch + k(i) + w(i)
     S0 = (a rotateright 2) xor (a rotateright 13) xor (a rotateright 22)
     maj = (a and b) xor (a and c) xor (b and c)
     temp2 = S0 + maj
     h = g
     g = f
     f = e
     e = d + temp1
     d = c
     c = b
     b = a
     a = temp1 + temp2
   // Add the compressed chunk to the current hash value
   h0 = h0 + a
   h1 = h1 + b
   h2 = h2 + c
   h3 = h3 + d
   h4 = h4 + e
   h5 = h5 + f
   h6 = h6 + g
   h7 = h7 + h
 // Produce the final hash value (big-endian)
 map( a -> format('%08x', a.intValue()), [h0, h1, h2, h3, h4, h5, h6, h7] ).mkString()</lang>

Here is a test comparing the two and also verifying the hash values of the empty message string.

<lang funl>message = 'Rosetta code'

println( 'FunL: "' + message + '" ~> ' + sha256(message) ) println( 'Java: "' + message + '" ~> ' + sha256Java(message) )

message =

println( 'FunL: "' + message + '" ~> ' + sha256(message) ) println( 'Java: "' + message + '" ~> ' + sha256Java(message) )</lang>

Output:
FunL: "Rosetta code" ~> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Java: "Rosetta code" ~> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
FunL: "" ~> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Java: "" ~> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

Genie

<lang genie>[indent=4] /*

  SHA-256 in Genie
  valac SHA-256.gs
  ./SHA-256
  • /

init

   var msg = "Rosetta code"
   var digest = Checksum.compute_for_string(ChecksumType.SHA256, msg, -1)
   print msg
   print digest
   assert(digest == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")</lang>
Output:
prompt$ valac SHA-256.gs
prompt$ ./SHA-256
Rosetta code
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Go

<lang go>package main

import (

   "crypto/sha256"
   "fmt"
   "log"

)

func main() {

   h := sha256.New()
   if _, err := h.Write([]byte("Rosetta code")); err != nil {
       log.Fatal(err)
   }
   fmt.Printf("%x\n", h.Sum(nil))

}</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Groovy

<lang groovy>def sha256Hash = { text ->

   java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes)
           .collect { String.format("%02x", it) }.join()

}</lang> Testing <lang groovy>assert sha256Hash('Rosetta code') == '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'</lang>

Halon

<lang halon>$var = "Rosetta code"; echo sha2($var, 256);</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Haskell

<lang haskell>import Data.Char (ord) import Crypto.Hash.SHA256 (hash) import Data.ByteString (unpack, pack) import Text.Printf (printf)

main = putStrLn $ -- output to terminal

      concatMap (printf "%02x") $    -- to hex string
      unpack $                       -- to array of Word8
      hash $                         -- SHA-256 hash to ByteString
      pack $                         -- to ByteString
      map (fromIntegral.ord)         -- to array of Word8
      "Rosetta code"

</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Haxe

<lang haxe>import haxe.crypto.Sha256;

class Main {

 static function main() {	
   var sha256 = Sha256.encode("Rosetta code");
   Sys.println(sha256);
 }

}</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

J

Solution: From J8 the ide/qt addon provides bindings to Qt libraries that include support for various hashing algorithms including SHA-256. <lang j>require '~addons/ide/qt/qt.ijs' getsha256=: 'sha256'&gethash_jqtide_</lang> Example Usage: <lang j> getsha256 'Rosetta code' 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</lang>

Note that the older version Qt4 libraries currently shipped by default on many Linux distributions don't support SHA-256. On Windows and Mac, J8 includes the later Qt5 libraries that include support for SHA-256.

Starting in J8.06, the sha family of hashes have built-in support.

<lang j>sha256=: 3&(128!:6)</lang>

<lang j> sha256 'Rosetta code' 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</lang>

Java

The solution to this task would be a small modification to MD5 (replacing "MD5" with "SHA-256" as noted here).

JavaScript

<lang javascript> const crypto = require('crypto');

const msg = 'Rosetta code'; const hash = crypto.createHash('sha256').update(msg).digest('hex');

console.log(hash); </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Jsish

<lang javascript>/* SHA-256 hash in Jsish */ var str = 'Rosetta code'; puts(Util.hash(str, {type:'sha256'}));

/*

!EXPECTSTART!

764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

!EXPECTEND!

  • /</lang>
Output:
prompt$ jsish sha-256.jsi
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
prompt$ jsish -u sha-256.jsi
[PASS] sha-256.jsi

Julia

Works with: Julia version 0.6

<lang julia>msg = "Rosetta code"

using Nettle digest = hexdigest("sha256", msg)

  1. native

using SHA digest1 = join(num2hex.(sha256(msg)))

@assert digest == digest1</lang>

Kotlin

<lang scala>// version 1.0.6

import java.security.MessageDigest

fun main(args: Array<String>) {

   val text  = "Rosetta code"
   val bytes = text.toByteArray()
   val md = MessageDigest.getInstance("SHA-256")
   val digest = md.digest(bytes)
   for (byte in digest) print("%02x".format(byte))
   println() 

}</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Lasso

Lasso supports the ciphers as supplied by the operating system.

SHA-256 is not supplied by all operating systems by default.

Use the cipher_list method to view these algorithms.

<lang Lasso>// The following will return a list of all the cipher // algorithms supported by the installation of Lasso cipher_list

// With a -digest parameter the method will limit the returned list // to all of the digest algorithms supported by the installation of Lasso cipher_list(-digest)

// return the SHA-256 digest. Dependant on SHA-256 being an available digest method cipher_digest('Rosetta Code', -digest='SHA-256',-hex=true) </lang>

Lua

Works with: Lua 5.1.4
Library: sha2

(luarocks install sha2)

<lang Lua>#!/usr/bin/lua

require "sha2"

print(sha2.sha256hex("Rosetta code"))</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Mathematica

<lang>Hash["Rosetta code","SHA256","HexString"]</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

NetRexx

This solution is basically the same as that for MD5, substituting "SHA-256" for "MD5" as the algorithm to use in the MessageDigest instance. <lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary

import java.security.MessageDigest

SHA256('Rosetta code', '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf')

return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA256(messageText, verifyCheck) public static

 algorithm   = 'SHA-256'
 digestSum = getDigest(messageText, algorithm)
 say '<Message>'messageText'</Message>'
 say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>'
 say Rexx('<Verify>').right(12) || verifyCheck'</Verify>'
 if digestSum == verifyCheck then say algorithm 'Confirmed'
                             else say algorithm 'Failed'
 return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx

 algorithm = algorithm.upper
 encoding  = encoding.upper
 message      = String(messageText)
 messageBytes = byte[]
 digestBytes  = byte[]
 digestSum    = Rexx 
 do
   messageBytes = message.getBytes(encoding)
   md = MessageDigest.getInstance(algorithm)
   md.update(messageBytes)
   digestBytes = md.digest
   loop b_ = 0 to digestBytes.length - 1
     bb = Rexx(digestBytes[b_]).d2x(2)
     if lowercase then digestSum = digestSum || bb.lower
                  else digestSum = digestSum || bb.upper
     end b_
 catch ex = Exception
   ex.printStackTrace
 end
 
 return digestSum

</lang> Output:

<Message>Rosetta code</Message>
   <SHA-256>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</SHA-256>
    <Verify>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</Verify>
SHA-256 Confirmed

NewLISP

<lang NewLISP>;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html

(import native functions from the crypto library, provided by OpenSSL)

(module "crypto.lsp") (crypto:sha256 "Rosetta Code")</lang>

Nim

Library: OpenSSL

Compile with nim -d:ssl c sha256.nim: <lang nim>import strutils

const SHA256Len = 32

proc SHA256(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: "libssl.so", importc.}

proc SHA256(s: string): string =

 result = ""
 let s = SHA256(s.cstring, s.len.culong)
 for i in 0 .. < SHA256Len:
   result.add s[i].BiggestInt.toHex(2).toLower

echo SHA256("Rosetta code")</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Oberon-2

Works with: oo2c
Library: crypto

<lang oberon2> MODULE SHA256; IMPORT

 Crypto:SHA256,
 Crypto:Utils,
 Strings,
 Out;

VAR

 h: SHA256.Hash;
 str: ARRAY 128 OF CHAR;

BEGIN

 h := SHA256.NewHash();
 h.Initialize;
 str := "Rosetta code";
 h.Update(str,0,Strings.Length(str));
 h.GetHash(str,0);
 Out.String("SHA256: ");Utils.PrintHex(str,0,h.size);Out.Ln

END SHA256. </lang>

Output:
SHA256: 
   764FAF5C   61AC315F   1497F9DF   A5427139   65B785E5   CC2F707D
   6468D7D1   124CDFCF

Objeck

<lang Objeck> class ShaHash {

  function : Main(args : String[]) ~ Nil {
     hash:= Encryption.Hash->SHA256("Rosetta code"->ToByteArray());
     str := hash->ToHexString()->ToLower();
     str->PrintLine();
     str->Equals("764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")->PrintLine();
  }

} </lang>

764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
true

Objective-C

Build with something like

clang -o rosetta_sha256 rosetta_sha256.m /System/Library/Frameworks/Cocoa.framework/Cocoa

or in XCode. <lang objc>#import <Cocoa/Cocoa.h>

  1. import <CommonCrypto/CommonDigest.h>


int main(int argc, char ** argv) {

   NSString * msg = @"Rosetta code";
   unsigned char buf[CC_SHA256_DIGEST_LENGTH];
   const char * rc = [msg cStringUsingEncoding:NSASCIIStringEncoding];
   if (! CC_SHA256(rc, strlen(rc), buf)) {
       NSLog(@"Failure...");
       return -1;
   }
   NSMutableString * res = [NSMutableString stringWithCapacity:(CC_SHA256_DIGEST_LENGTH * 2)];
   for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) {
       [res appendFormat:@"%02x", buf[i]];
   }
   NSLog(@"Output: %@", res);
   return 0;

} </lang>

OCaml

Library: caml-sha

<lang ocaml>let () =

 let s = "Rosetta code" in
 let digest = Sha256.string s in
 print_endline (Sha256.to_hex digest)</lang>

Running this script in interpreted mode:

$ ocaml -I +sha sha256.cma sha.ml
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

OS X sha256sum

Apple OS X command line with echo and sha256sum.

<lang sha256sum>echo -n 'Rosetta code' | sha256sum</lang>

Using the -n flag for echo is required as echo normally outputs a newline.

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf  -

PARI/GP

It works on Linux systems.

<lang parigp>sha256(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha256sum|cut -d' ' -f1`)\"")</lang>

The code above creates a new function sha256(s) which returns SHA-256 hash of item s.

Output:
sha256("Rosetta code") = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"

Perl

The preferred way to do a task like this is to use an already written module, for example: <lang Perl>#!/usr/bin/perl use strict ; use warnings ; use Digest::SHA qw( sha256_hex ) ;

my $digest = sha256_hex my $phrase = "Rosetta code" ; print "SHA-256('$phrase'): $digest\n" ; </lang>

Output:
SHA-256('Rosetta code'): 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

On the other hand, one of perl's mottos is There Is More Than One Way To Do It, so of course you could write your own implementation if you wanted to. <lang Perl> package Digest::SHA256::PP;

use strict; use warnings;

use constant WORD => 2**32; use constant MASK => WORD - 1;

my @h; my @k;

for my $p ( 2 .. 311 ) { # Horrible primality test, but sufficient for this task. next if ("1" x $p) =~ /^(11+?)\1+$/; # The choice to generate h and k instead of hard coding # them is inspired by the Raku implementation. my $c = $p ** ( 1/3 ); push @k, int( ($c - int $c) * WORD ); next if @h == 8; my $s = $p ** ( 1/2 ); push @h, int( ($s - int $s) * WORD ); }

sub new { my %self = ( state => [@h], str => "", len => 0 ); bless \%self, shift; }

my $rightrotate = sub { my $lo = $_[0] >> $_[1]; my $hi = $_[0] << (32 - $_[1]); ($hi | $lo); };

  1. This is adapted from the wikipedia entry on SHA2.

my $compress = sub { my ($state, $bytes) = @_; my @w = unpack 'N*', $bytes; @w == 16 or die 'internal error'; my ($a, $b, $c, $d, $e, $f, $g, $h) = @$state; until( @w == 64 ) { my $s0 = $w[-15] >> 3; my $s1 = $w[-2] >> 10; $s0 ^= $rightrotate->($w[-15], $_) for 7, 18; $s1 ^= $rightrotate->($w[-2], $_) for 17, 19; push @w, ($w[-16] + $s0 + $w[-7] + $s1) & MASK; } my $i = 0; for my $w (@w) { my $ch = ($e & $f) ^ ((~$e) & $g); my $maj = ($a & $b) ^ ($a & $c) ^ ($b & $c); my ($S0, $S1) = (0, 0); $S1 ^= $rightrotate->( $e, $_ ) for 6, 11, 25; $S0 ^= $rightrotate->( $a, $_ ) for 2, 13, 22; my $temp1 = $h + $S1 + $ch + $k[$i++] + $w; my $temp2 = $S0 + $maj; ($h, $g, $f, $e, $d, $c, $b, $a) = ($g, $f, $e, ($d+$temp1)&MASK, $c, $b, $a, ($temp1+$temp2)&MASK); } my $j = 0; $state->[$j++] += $_ for $a, $b, $c, $d, $e, $f, $g, $h; };

use constant can_Q => eval { length pack 'Q>', 0 };

sub add { my ($self, $bytes) = @_; $self->{len} += 8 * length $bytes; if( !can_Q and $self->{len} >= WORD ) { my $hi = int( $self->{len} / WORD ); $self->{big} += $hi; $self->{len} -= $hi * WORD; } my $len = length $self->{str}; if( ($len + length $bytes) < 64 ) { $self->{str} .= $bytes; return $self; } my $off = 64 - $len; $compress->( $self->{state}, $self->{str} . substr( $bytes, 0, $off ) ); $len = length $_[0]; while( $off+64 <= $len ) { $compress->( $self->{state}, substr( $bytes, $off, 64 ) ); $off += 64; } $self->{str} = substr( $bytes, $off ); $self; }

sub addfile { my ($self, $fh) = @_; my $s = ""; while( read( $fh, $s, 2**13 ) ) { $self->add( $s ); } $self; }


sub digest { my $self = shift; my $final = $self->{str}; $final .= chr 0x80; while( ( 8+length $final ) % 64 ) { $final .= chr 0; } if( can_Q ) { $final .= pack 'Q>', $self->{len}; } else { $self->{big} ||= 0; $final .= pack 'NN', $self->{big}, $self->{len}; } $compress->( $self->{state}, substr $final, 0, 64, "" ) while length $final; if( wantarray ) { map pack('N', $_), @{ $self->{state} }; } else { pack 'N*', @{ $self->{state} }; } }

sub hexdigest { if( wantarray ) { map unpack( 'H*', $_), &digest; } else { unpack 'H*', &digest; } }

unless( caller ) { my @testwith = (@ARGV ? @ARGV : 'Rosetta code'); for my $str (@testwith) { my $digester = __PACKAGE__->new; $digester->add($str); print "'$str':\n"; print join(" ", $digester->hexdigest), "\n"; } }

1; </lang>

Output:
'Rosetta code':
764faf5c 61ac315f 1497f9df a5427139 65b785e5 cc2f707d 6468d7d1 124cdfcf

Phix

<lang Phix>include builtins\sha256.e

function asHex(string s) string res = ""

   for i=1 to length(s) do
       res &= sprintf("%02X",s[i])
   end for
   return res

end function

?asHex(sha256("Rosetta code"))</lang>

Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"

The standard include file sha256.e is now mainly optimised inline assembly, but the following is, I feel, more in the spirit of this site <lang Phix>-- -- demo\rosetta\sha-256.exw -- ======================== -- -- fairly faithful rendition of https://en.wikipedia.org/wiki/SHA-2 -- with slightly improved names (eg s0 -> sigma0) from elsewhere. -- See also sha-256asm.exw for a faster inline asm version, and -- sha-256dll.exw is much shorter as it uses a pre-built dll.

--Initial array of round constants --(first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311): constant k = {

  0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
  0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
  0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
  0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
  0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
  0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
  0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
  0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}

function pad64(integer v) -- round v up to multiple of 64

   return floor((v+63)/64)*64

end function

constant m4 = allocate(4) -- scratch area, for uint32

function uint32(atom v) -- -- (note: I have experimented to call this as few times as possible. -- It wouldn't hurt to perform this on every maths op, but a -- few leading bits in a few work fields don't matter much.) --

   poke4(m4,v)
   return peek4u(m4)

end function

function sq_uint32(sequence s) -- apply unit32 to all elements of s

   for i=1 to length(s) do
       s[i] = uint32(s[i])
   end for
   return s

end function

function dword(string msg, integer i) -- get dword as big-endian

   return msg[i]*#1000000+msg[i+1]*#10000+msg[i+2]*#100+msg[i+3]

end function

function shr(atom v, integer bits)

   return floor(v/power(2,bits))

end function

function ror(atom v, integer bits)

   return or_bits(shr(v,bits),v*power(2,32-bits))

end function

function sha256(string msg) -- main function atom s0,s1,a,b,c,d,e,f,g,h,ch,temp1,maj,temp2,x sequence w = repeat(0,64) sequence res integer len = length(msg)+1 --Initial hash values --(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) atom h0 = 0x6a09e667,

    h1 = 0xbb67ae85,
    h2 = 0x3c6ef372,
    h3 = 0xa54ff53a,
    h4 = 0x510e527f,
    h5 = 0x9b05688c,
    h6 = 0x1f83d9ab,
    h7 = 0x5be0cd19
   -- add the '1' bit and space for size in bits, padded to multiple of 64
   msg &= #80&repeat('\0',pad64(len+8)-len)
   len = (len-1)*8
   for i=length(msg) to 1 by -1 do
       msg[i] = and_bits(len,#FF)
       len = floor(len/#100)
       if len=0 then exit end if
   end for
   -- Process the message in successive 512-bit (64 byte) chunks
   for chunk=1 to length(msg) by 64 do
       for i=1 to 16 do
           w[i] = dword(msg,chunk+(i-1)*4)
       end for
       -- Extend the first 16 words into the remaining 48 words w[17..64] of the message schedule array
       for i=17 to 64 do
           x = w[i-15]; s0 = xor_bits(xor_bits(ror(x, 7),ror(x,18)),shr(x, 3))
           x = w[i-2];  s1 = xor_bits(xor_bits(ror(x,17),ror(x,19)),shr(x,10))
           w[i] = uint32(w[i-16]+s0+w[i-7]+s1)
       end for
       -- Initialize working variables to current hash value
       {a,b,c,d,e,f,g,h} = {h0,h1,h2,h3,h4,h5,h6,h7}
    
       -- Compression function main loop
       for i=1 to 64 do
           s1 = xor_bits(xor_bits(ror(e,6),ror(e,11)),ror(e,25))
           ch = xor_bits(and_bits(e,f),and_bits(not_bits(e),g))
           temp1 = h+s1+ch+k[i]+w[i]
           s0 = xor_bits(xor_bits(ror(a,2),ror(a,13)),ror(a,22))
           maj = xor_bits(xor_bits(and_bits(a,b),and_bits(a,c)),and_bits(b,c))
           temp2 = s0+maj
    
           {h,g,f,e,d,c,b,a} = sq_uint32({g,f,e,d+temp1,c,b,a,temp1+temp2})
       end for
       -- Add the compressed chunk to the current hash value
       {h0,h1,h2,h3,h4,h5,h6,h7} = sq_add({h0,h1,h2,h3,h4,h5,h6,h7},{a,b,c,d,e,f,g,h})
   end for
   -- Produce the final hash value (big-endian)
   res = sq_uint32({h0, h1, h2, h3, h4, h5, h6, h7}) -- (or do sq_unit32 on the sq_add above)
   for i=1 to length(res) do
       res[i] = sprintf("%08x",res[i])
   end for
   return join(res)

end function

?sha256("Rosetta code")</lang>

Output:
"764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF"

PHP

<lang php><?php echo hash('sha256', 'Rosetta code'); </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

PicoLisp

Library and implementation. <lang PicoLisp>(setq *Sha256-K

  (mapcar hex 
     '("428A2F98" "71374491" "B5C0FBCF" "E9B5DBA5" "3956C25B" 
       "59F111F1" "923F82A4" "AB1C5ED5" "D807AA98" "12835B01"
       "243185BE" "550C7DC3" "72BE5D74" "80DEB1FE" "9BDC06A7" 
       "C19BF174" "E49B69C1" "EFBE4786" "0FC19DC6" "240CA1CC"
       "2DE92C6F" "4A7484AA" "5CB0A9DC" "76F988DA" "983E5152"
       "A831C66D" "B00327C8" "BF597FC7" "C6E00BF3" "D5A79147"
       "06CA6351" "14292967" "27B70A85" "2E1B2138" "4D2C6DFC" 
       "53380D13" "650A7354" "766A0ABB" "81C2C92E" "92722C85"
       "A2BFE8A1" "A81A664B" "C24B8B70" "C76C51A3" "D192E819"
       "D6990624" "F40E3585" "106AA070" "19A4C116" "1E376C08"
       "2748774C" "34B0BCB5" "391C0CB3" "4ED8AA4A" "5B9CCA4F"
       "682E6FF3" "748F82EE" "78A5636F" "84C87814" "8CC70208"
       "90BEFFFA" "A4506CEB" "BEF9A3F7" "C67178F2") ) )

(de rightRotate (X C)

  (| (mod32 (>> C X)) (mod32 (>> (- C 32) X))) )

(de mod32 (N)

  (& N `(hex "FFFFFFFF")) )
  

(de not32 (N)

  (x| N `(hex "FFFFFFFF")) )   
  

(de add32 @

  (mod32 (pass +)) )   
  

(de sha256 (Str)

  (let Len (length Str)
     (setq Str
        (conc
           (need
              (- 
                 8 
                 (* 64 (/ (+ Len 1 8 63) 64)) )
              (conc (mapcar char (chop Str)) (cons `(hex "80")))
              0 ) 
           (flip 
              (make
                 (setq Len (* 8 Len))
                 (do 8
                    (link (& Len 255))
                    (setq Len (>> 8 Len )) ) ) ) ) ) )
  (let
     (H0 `(hex "6A09E667")
        H1 `(hex "BB67AE85")
        H2 `(hex "3C6EF372")
        H3 `(hex "A54FF53A")
        H4 `(hex "510E527F")
        H5 `(hex "9B05688C")
        H6 `(hex "1F83D9AB")
        H7 `(hex "5BE0CD19") )
     (while Str                  
        (let
           (A H0
              B H1
              C H2
              D H3
              E H4
              F H5
              G H6
              H H7
              W 
              (conc
                (make
                   (do 16
                      (link
                         (apply 
                            |
                            (mapcar >> (-24 -16 -8 0) (cut 4 'Str)) ) ) ) )
                (need 48 0) ) )
              (for (I 17 (>= 64 I) (inc I))
                 (let 
                    (Wi15 (get W (- I 15)) 
                       Wi2 (get W (- I 2))
                       S0
                       (x| 
                          (rightRotate Wi15 7)
                          (rightRotate Wi15 18)
                          (>> 3 Wi15) )
                       S1
                       (x| 
                          (rightRotate Wi2 17)
                          (rightRotate Wi2 19)
                          (>> 10 Wi2) ) )
                    (set (nth W I)
                       (add32
                          (get W (- I 16))
                          S0
                          (get W (- I 7))
                          S1 ) ) ) )
              (use (Tmp1 Tmp2)
                 (for I 64
                    (setq 
                       Tmp1
                       (add32
                          H
                          (x|
                             (rightRotate E 6)
                             (rightRotate E 11)
                             (rightRotate E 25) )
                          (x| (& E F) (& (not32 E) G))
                          (get *Sha256-K I)
                          (get W I) )
                       Tmp2
                       (add32
                          (x|
                             (rightRotate A 2)
                             (rightRotate A 13)
                             (rightRotate A 22) )
                          (x| 
                             (& A B)
                             (& A C)
                             (& B C) ) )
                       H G
                       G F
                       F E
                       E (add32 D Tmp1)
                       D C
                       C B
                       B A
                       A (add32 Tmp1 Tmp2) ) ) )
              (setq
                 H0 (add32 H0 A)
                 H1 (add32 H1 B)
                 H2 (add32 H2 C)
                 H3 (add32 H3 D) 
                 H4 (add32 H4 E) 
                 H5 (add32 H5 F) 
                 H6 (add32 H6 G) 
                 H7 (add32 H7 H) ) ) )
     (mapcan
        '((N)
           (flip
              (make
                 (do 4
                    (link (& 255 N))
                    (setq N (>> 8 N)) ) ) ) )
        (list H0 H1 H2 H3 H4 H5 H6 H7) ) ) )
        

(let Str "Rosetta code"

  (println
     (pack
        (mapcar 
           '((B) (pad 2 (hex B))) 
           (sha256 Str) ) ) )
  (println
     (pack
        (mapcar 
           '((B) (pad 2 (hex B)))
           (native 
              "libcrypto.so"
              "SHA256"
              '(B . 32)
              Str
              (length Str)
              '(NIL (32)) ) ) ) ) )

(bye)</lang>

Pike

<lang Pike> string input = "Rosetta code"; string out = Crypto.SHA256.hash(input); write( String.string2hex(out) +"\n"); </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

PowerShell

Works with: PowerShell 5.0

<lang PowerShell> Set-Content -Value "Rosetta code" -Path C:\Colors\blue.txt -NoNewline -Force Get-FileHash -Path C:\Colors\blue.txt -Algorithm SHA256 </lang>

Output:
Algorithm       Hash                                                                   Path
---------       ----                                                                   ----
SHA256          764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF       C:\Colors\blue.txt

PureBasic

PB Version 5.40 <lang purebasic>a$="Rosetta code" bit.i= 256

UseSHA2Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_SHA2, bit)

OpenConsole() Print("[SHA2 "+Str(bit)+" bit] Text: "+a$+" ==> "+b$) Input()</lang>

Output:
[SHA2 256 bit] Text: Rosetta code ==> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Python

Python has a standard module for this: <lang python>>>> import hashlib >>> hashlib.sha256( "Rosetta code".encode() ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> </lang>

R

<lang rsplus> library(digest)

input <- "Rosetta code" cat(digest(input, algo = "sha256", serialize = FALSE), "\n") </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Racket

<lang racket>

  1. lang racket/base
define a quick SH256 FFI interface, similar to the Racket's default
SHA1 interface

(require ffi/unsafe ffi/unsafe/define openssl/libcrypto

        (only-in openssl/sha1 bytes->hex-string))

(define-ffi-definer defcrypto libcrypto) (defcrypto SHA256_Init (_fun _pointer -> _int)) (defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) (defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) (define (sha256 bytes)

 (define ctx (malloc 128))
 (define result (make-bytes 32))
 (SHA256_Init ctx)
 (SHA256_Update ctx bytes (bytes-length bytes))
 (SHA256_Final result ctx)
 (bytes->hex-string result))
use the defined wrapper to solve the task

(displayln (sha256 #"Rosetta code")) </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Raku

(formerly Perl 6)

Pure Raku

The following implementation takes all data as input. Ideally, input should be given lazily or something.

<lang perl6>say sha256 "Rosetta code";

sub init(&f) {

   map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int },
   state @ = grep *.is-prime, 2 .. *;

}

sub infix:<m+> { ($^a + $^b) % 2**32 } sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }

proto sha256($) returns Blob {*} multi sha256(Str $str where all($str.ords) < 128) {

   sha256 $str.encode: 'ascii'

} multi sha256(Blob $data) {

   constant K = init(* **(1/3))[^64];
   my @b = flat $data.list, 0x80;
   push @b, 0 until (8 * @b - 448) %% 512;
   push @b, slip reverse (8 * $data).polymod(256 xx 7);
   my @word = :256[@b.shift xx 4] xx @b/4;

   my @H = init(&sqrt)[^8];
   my @w;
   loop (my $i = 0; $i < @word; $i += 16) {
       my @h = @H;
       for ^64 -> $j {
           @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !!
           [m+]
           rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3,
           @w[$j-7],
           rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19)  +^ @w[$j-2] +> 10,
           @w[$j-16];
           my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6];
           my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2];
           my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22;
           my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25;
           my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j];
           my $t2 = $σ0 m+ $maj;
           @h = flat $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6];
       }
       @H [Z[m+]]= @h;
   }
   return Blob.new: map { |reverse .polymod(256 xx 3) }, @H;

}</lang>

Output:
Buf:0x<76 4f af 5c 61 ac 31 5f 14 97 f9 df a5 42 71 39 65 b7 85 e5 cc 2f 70 7d 64 68 d7 d1 12 4c df cf>

Library implementation

<lang perl6>use Digest::SHA256::Native;

  1. If you want a string

say sha256-hex 'Rosetta code';

  1. If you want a binary Blob

say sha256 'Rosetta code';</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Blob:0x<76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF>

Ring

<lang ring>

  1. Project: SHA-256

load "stdlib.ring" str = "Rosetta code" see "String: " + str + nl see "SHA-256: " see sha256(str) + nl </lang> Output:

String: Rosetta code
SHA-256: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Ruby

<lang ruby>require 'digest/sha2' puts Digest::SHA256.hexdigest('Rosetta code')</lang>

Rust

<lang rust>use sha2::{Digest, Sha256};

fn hex_string(input: &[u8]) -> String {

   input.as_ref().iter().map(|b| format!("{:x}", b)).collect()

}

fn main() {

   // create a Sha256 object
   let mut hasher = Sha256::new();
   // write input message
   hasher.input(b"Rosetta code");
   // read hash digest and consume hasher
   let result = hasher.result();
   let hex = hex_string(&result);
   assert_eq!(
       hex,
       "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
   );
   
   println!("{}", hex)

} </lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Scala

Library: Scala

<lang Scala>object RosettaSHA256 extends App {

 def MD5(s: String): String = {
   // Besides "MD5", "SHA-256", and other hashes are available
   val m = java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8"))
   m.map("%02x".format(_)).mkString
 }
 assert(MD5("Rosetta code") == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")
 println("Successfully completed without errors.")

}</lang>

Seed7

<lang seed7>$ include "seed7_05.s7i";

 include "msgdigest.s7i";

const proc: main is func

 begin
   writeln(hex(sha256("Rosetta code")));
 end func;</lang>
Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Sidef

<lang ruby>var sha = frequire('Digest::SHA'); say sha.sha256_hex('Rosetta code');</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

Smalltalk

Use the Cryptography library:

<lang smalltalk> (SHA256 new hashStream: 'Rosetta code' readStream) hex. </lang>

Tcl

<lang tcl>package require sha256

puts [sha2::sha256 -hex "Rosetta code"]</lang>

Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf

zkl

Uses shared library zklMsgHash.so <lang zkl>var MsgHash=Import("zklMsgHash"); MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"</lang>

Output:
True