SHA-256
SHA-256 is the recommended stronger alternative to SHA-1.
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
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
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
<lang c>#include <stdio.h>
- include <string.h>
- 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>
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
<lang clojure>(use 'pandect.core) (sha256 "Rosetta code")</lang>
- Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
Common Lisp
<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 { 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 { 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 { // 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 in { assert(inBuffer.length % 64 == 0); } body { // Round functions. static uint F1(in uint e, in uint f, in uint g) pure nothrow { return g ^ (e & (f ^ g)); }
static uint F2(in uint a, in uint b, in uint c) pure nothrow { 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 { return (x << n) | (x >> (32 - n)); } static uint S0(in uint x) pure nothrow { return rol(x, 25) ^ rol(x, 14) ^ (x >> 3); } static uint S1(in uint x) pure nothrow { return rol(x, 15) ^ rol(x, 13) ^ (x >> 10); } static uint SS0(in uint x) pure nothrow { return rol(x, 30) ^ rol(x,19) ^ rol(x, 10); } static uint SS1(in uint x) pure nothrow { return rol(x, 26) ^ rol(x, 21) ^ rol(x, 7); }
uint M(in uint I) nothrow { 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 { 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 { // 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(ref TResult resBuf) const pure nothrow { 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(ref TResult resBuf) pure nothrow { 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, ref TResult resBuf) pure nothrow { 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 { 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.
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
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) shiftright 3) s1 = (w(i-2) rotateright 17) xor (w(i-2) rotateright 19) xor (w(i-2) shiftright 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
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>
Java
The solution to this task would be a small modification to MD5 (replacing "MD5" with "SHA-256" as noted here).
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
<lang Lua>#!/usr/bin/lua
require "sha2"
print(sha2.sha256hex("Rosetta code"))</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Mathematica
<lang>IntegerString[Hash["Rosetta code", "SHA256"], 16]</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>
Nimrod
Compile with nimrod -d:ssl c sha256.nim
:
<lang nimrod>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
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>
- 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
<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
Perl
<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
Perl 6
The following implementation takes all data as input. Ideally, input should be given lazily or something.
<lang Perl 6>say .list».fmt("%02x").join given sha256 "Rosetta code";
constant primes = grep &is-prime, 2 .. *; sub init(&f) {
map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, primes
}
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 $l = 8 * my @b = $data.list; push @b, 0x80; push @b, 0 until (8*@b-448) %% 512; push @b, reverse gather for ^8 { take $l%256; $l div=256 } 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 = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; } @H = @H Z[m+] @h; } return Blob.new: map -> $word is rw { reverse gather for ^4 { take $word % 256; $word div= 256 } }, @H;
}</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>
PHP
<lang php><?php echo hash('sha256', 'Rosetta code'); </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Python
Python has a standard module for this: <lang python>>>> import hashlib >>> hashlib.sha256( "Rosetta code".encode() ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> </lang>
Racket
<lang racket>
- 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
Ruby
<lang ruby>require 'digest/sha2' puts Digest::SHA256.hexdigest('Rosetta code')</lang>
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
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