SHA-256: Difference between revisions

105,629 bytes added ,  4 months ago
m
(Added Haskell version)
m (→‎{{header|Wren}}: Minor tidy)
(101 intermediate revisions by 54 users not shown)
Line 1:
{{task|Checksums}}
'''[[wp:SHA-256|SHA-256]]''' is the recommended stronger alternative to [[SHA-1]]. See [http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf FIPS PUB 180-4] for implementation details.
 
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
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits <br> or android 64 bits with application Termux }}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sha256_64.s */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
 
.equ LGHASH, 32 // result length
 
 
/*******************************************/
/* Structures */
/********************************************/
/* example structure variables */
.struct 0
var_a: // a
.struct var_a + 4
var_b: // b
.struct var_b + 4
var_c: // c
.struct var_c + 4
var_d: // d
.struct var_d + 4
var_e: // e
.struct var_e + 4
var_f: // f
.struct var_f + 4
var_g: // g
.struct var_g + 4
var_h: // h
.struct var_h + 4
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRosetta: .asciz "Rosetta code"
szMessTest1: .asciz "abc"
szMessSup64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.ascii "abcdefghijklmnopqrstuvwxyz"
.asciz "1234567890AZERTYUIOP"
szMessTest2: .asciz "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
szMessFinPgm: .asciz "Program End ok.\n"
szMessResult: .asciz "Rosetta code => "
szCarriageReturn: .asciz "\n"
 
/* array constantes Hi */
tbConstHi: .int 0x6A09E667 // H0
.int 0xBB67AE85 // H1
.int 0x3C6EF372 // H2
.int 0xA54FF53A // H3
.int 0x510E527F // H4
.int 0x9B05688C // H5
.int 0x1F83D9AB // H6
.int 0x5BE0CD19 // H7
/* array 64 constantes Kt */
tbConstKt:
.int 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5
.int 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174
.int 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da
.int 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967
.int 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85
.int 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070
.int 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3
.int 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
qNbBlocs: .skip 8
sZoneConv: .skip 24
sZoneTrav: .skip 1000
.align 8
tbH: .skip 4 * 8 // 8 variables H
tbabcdefgh: .skip 4 * 8
tbW: .skip 4 * 64 // 64 words W
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrszMessRosetta
//ldr x0,qAdrszMessTest1
//ldr x0,qAdrszMessTest2
//ldr x0,qAdrszMessSup64
bl computeSHA256 // call routine SHA1
 
ldr x0,qAdrszMessResult
bl affichageMess // display message
 
ldr x0, qAdrtbH
bl displaySHA1
 
ldr x0,qAdrszMessFinPgm
bl affichageMess // display message
 
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrszMessResult: .quad szMessResult
qAdrszMessRosetta: .quad szMessRosetta
qAdrszMessTest1: .quad szMessTest1
qAdrszMessTest2: .quad szMessTest2
qAdrsZoneTrav: .quad sZoneTrav
qAdrsZoneConv: .quad sZoneConv
qAdrszMessFinPgm: .quad szMessFinPgm
qAdrszMessSup64: .quad szMessSup64
/******************************************************************/
/* compute SHA1 */
/******************************************************************/
/* x0 contains the address of the message */
computeSHA256:
stp x1,lr,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
mov x2,#0 // counter length
debCopy: // copy string in work area
ldrb w3,[x0,x2]
strb w3,[x1,x2]
cmp x3,#0
add x4,x2,1
csel x2,x4,x2,ne
bne debCopy
lsl x6,x2,#3 // initial message length in bits
mov x3,#0b10000000 // add bit 1 at end of string
strb w3,[x1,x2]
add x2,x2,#1 // length in bytes
str xzr,[x1,x2] // zeroes in end of array
lsl x4,x2,#3 // length in bits
addZeroes:
lsr x5,x2,#6
lsl x5,x5,#6
sub x5,x2,x5
cmp x5,#56
beq storeLength // yes -> end add
str xzr,[x1,x2] // add zero at message end
add x2,x2,#1 // increment lenght bytes
add x4,x4,#8 // increment length in bits
b addZeroes
storeLength:
add x2,x2,#4 // add four bytes
rev w6,w6 // inversion bits initials message length
str w6,[x1,x2] // and store at end
 
ldr x7,qAdrtbConstHi // constantes H address
ldr x4,qAdrtbH // start area H
mov x5,#0
loopConst: // init array H with start constantes
ldr w6,[x7,x5,lsl #2] // load constante
str w6,[x4,x5,lsl #2] // and store
add x5,x5,#1
cmp x5,#8
blt loopConst
// split into block of 64 bytes
add x2,x2,#4 //
lsr x4,x2,#6 // blocks number
ldr x0,qAdrqNbBlocs
str x4,[x0] // save block maxi
mov x7,#0 // n° de block et x1 contient l adresse zone de travail
loopBlock: // begin loop of each block of 64 bytes
mov x0,x7
bl inversion // inversion each word because little indian
ldr x3,qAdrtbW // working area W address
mov x6,#0 // indice t
/* x2 address begin each block */
ldr x1,qAdrsZoneTrav
add x2,x1,x7,lsl #6 // compute block begin indice * 4 * 16
 
loopPrep: // loop for expand 80 words
cmp x6,#15 //
bgt expand1
ldr w0,[x2,x6,lsl #2] // load word message
str w0,[x3,x6,lsl #2] // store in first 16 block
b expandEnd
 
expand1:
sub x8,x6,#2
ldr w9,[x3,x8,lsl #2]
ror w10,w9,#17 // fonction e1 (256)
ror w11,w9,#19
eor w10,w10,w11
lsr w11,w9,#10
eor w10,w10,w11
sub x8,x6,#7
ldr w9,[x3,x8,lsl #2]
add w9,w9,w10 // + w - 7
sub x8,x6,#15
ldr w10,[x3,x8,lsl #2]
ror w11,w10,#7 // fonction e0 (256)
ror w12,w10,#18
eor w11,w11,w12
lsr w12,w10,#3
eor w10,w11,w12
add w9,w9,w10
sub x8,x6,#16
ldr w11,[x3,x8,lsl #2]
add w9,w9,w11
 
str w9,[x3,x6,lsl #2]
expandEnd:
add x6,x6,#1
cmp x6,#64 // 64 words ?
blt loopPrep // and loop
 
 
/* COMPUTING THE MESSAGE DIGEST */
/* x1 area H constantes address */
/* x3 working area W address */
/* x5 address constantes K */
/* x6 counter t */
/* x7 block counter */
/* x8 addresse variables a b c d e f g h */
// init variable a b c d e f g h
ldr x0,qAdrtbH
ldr x8,qAdrtbabcdefgh
mov x1,#0
loopInita:
ldr w9,[x0,x1,lsl #2]
str w9,[x8,x1,lsl #2]
add x1,x1,#1
cmp x1,#8
blt loopInita
 
ldr x1,qAdrtbConstHi
ldr x5,qAdrtbConstKt
mov x6,#0
loop64T: // begin loop 64 t
ldr w9,[x8,#var_h]
ldr w10,[x8,#var_e] // calcul T1
ror w11,w10,#6 // fonction sigma 1
ror w12,w10,#11
eor w11,w11,w12
ror w12,w10,#25
eor w11,w11,w12
add w9,w9,w11 // h + sigma1 (e)
ldr w0,[x8,#var_f] // fonction ch x and y xor (non x and z)
ldr w4,[x8,#var_g]
and w11,w10,w0
mvn w12,w10
and w12,w12,w4
eor w11,w11,w12
add w9,w9,w11 // h + sigma1 (e) + ch (e,f,g)
ldr w0,[x5,x6,lsl #2] // load constantes k0
add w9,w9,w0
ldr w0,[x3,x6,lsl #2] // Wt
add w9,w9,w0
// calcul T2
ldr w10,[x8,#var_a] // fonction sigma 0
ror w11,w10,#2
ror w12,w10,#13
eor w11,w11,w12
ror w12,w10,#22
eor w11,w11,w12
ldr w2,[x8,#var_b]
ldr w4,[x8,#var_c]
// fonction maj x and y xor x and z xor y and z
and w12,w10,w2
and w0,w10,w4
eor w12,w12,w0
and w0,w2,w4
eor w12,w12,w0 //
add w12,w12,w11 // T2
// compute variables
ldr w4,[x8,#var_g]
str w4,[x8,#var_h]
ldr w4,[x8,#var_f]
str w4,[x8,#var_g]
ldr w4,[x8,#var_e]
str w4,[x8,#var_f]
ldr w4,[x8,#var_d]
add w4,w4,w9 // add T1
str w4,[x8,#var_e]
ldr w4,[x8,#var_c]
str w4,[x8,#var_d]
ldr w4,[x8,#var_b]
str w4,[x8,#var_c]
ldr w4,[x8,#var_a]
str w4,[x8,#var_b]
add w4,w9,w12 // add T1 T2
str w4,[x8,#var_a]
 
add x6,x6,#1 // increment t
cmp x6,#64
blt loop64T
// End block
ldr x0,qAdrtbH // start area H
mov x10,#0
loopStoreH:
ldr w9,[x8,x10,lsl #2]
ldr w3,[x0,x10,lsl #2]
add w3,w3,w9
str w3,[x0,x10,lsl #2] // store variables in H0
add x10,x10,#1
cmp x10,#8
blt loopStoreH
// other bloc
add x7,x7,#1 // increment block
ldr x0,qAdrqNbBlocs
ldr x4,[x0] // restaur maxi block
cmp x7,x4 // maxi ?
 
blt loopBlock // loop other block
 
ldr x0,qAdrtbH // return result address
 
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrtbConstHi: .quad tbConstHi
qAdrtbConstKt: .quad tbConstKt
qAdrtbH: .quad tbH
qAdrtbW: .quad tbW
qAdrtbabcdefgh: .quad tbabcdefgh
qAdrqNbBlocs: .quad qNbBlocs
/******************************************************************/
/* inversion des mots de 32 bits d un bloc */
/******************************************************************/
/* x0 contains N° block */
inversion:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
ldr x1,qAdrsZoneTrav
add x1,x1,x0,lsl #6 // debut du bloc
mov x2,#0
1: // start loop
ldr w3,[x1,x2,lsl #2]
rev w3,w3
str w3,[x1,x2,lsl #2]
add x2,x2,#1
cmp x2,#16
blt 1b
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* x0 contains the address of hash */
displaySHA1:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x3,x0
mov x2,#0
1:
ldr w0,[x3,x2,lsl #2] // load 4 bytes
//rev x0,x0 // reverse bytes
ldr x1,qAdrsZoneConv
bl conversion16_4W // conversion hexa
ldr x0,qAdrsZoneConv
bl affichageMess
add x2,x2,#1
cmp x2,#LGHASH / 4
blt 1b // and loop
ldr x0,qAdrszCarriageReturn
bl affichageMess // display message
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* conversion hexadecimal register 32 bits */
/******************************************************************/
/* x0 contains value and x1 address zone receptrice */
conversion16_4W:
stp x0,lr,[sp,-48]! // save registres
stp x1,x2,[sp,32] // save registres
stp x3,x4,[sp,16] // save registres
mov x2,#28 // start bit position
mov x4,#0xF0000000 // mask
mov x3,x0 // save entry value
1: // start loop
and x0,x3,x4 // value register and mask
lsr x0,x0,x2 // right shift
cmp x0,#10 // >= 10 ?
bge 2f // yes
add x0,x0,#48 // no is digit
b 3f
2:
add x0,x0,#55 // else is a letter A-F
3:
strb w0,[x1],#1 // load result and + 1 in address
lsr x4,x4,#4 // shift mask 4 bits left
subs x2,x2,#4 // decrement counter 4 bits <= zero ?
bge 1b // no -> loop
 
100: // fin standard de la fonction
ldp x3,x4,[sp,16] // restaur des 2 registres
ldp x1,x2,[sp,32] // restaur des 2 registres
ldp x0,lr,[sp],48 // restaur des 2 registres
ret
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
pi@debian-buster-64:~/asm64/rosetta/asm5 $ sha256_64
Rosetta code => 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
Program End ok.
</pre>
=={{header|Ada}}==
{{libheader|CryptAda}}
<syntaxhighlight 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;</syntaxhighlight>
{{out}}
<pre>"Rosetta code": 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF</pre>
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
/* ARM assembly Raspberry PI */
/* program sha256.s */
 
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
 
.equ LGHASH, 32 // result length
 
/*******************************************/
/* Structures */
/********************************************/
/* example structure variables */
.struct 0
var_a: // a
.struct var_a + 4
var_b: // b
.struct var_b + 4
var_c: // c
.struct var_c + 4
var_d: // d
.struct var_d + 4
var_e: // e
.struct var_e + 4
var_f: // f
.struct var_f + 4
var_g: // g
.struct var_g + 4
var_h: // h
.struct var_h + 4
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessRosetta: .asciz "Rosetta code"
szMessTest1: .asciz "abc"
szMessSup64: .ascii "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.ascii "abcdefghijklmnopqrstuvwxyz"
.asciz "1234567890AZERTYUIOP"
szMessTest2: .asciz "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
szMessFinPgm: .asciz "Program End ok.\n"
szMessResult: .asciz "Rosetta code => "
szCarriageReturn: .asciz "\n"
 
/* array constantes Hi */
tbConstHi: .int 0x6A09E667 @ H0
.int 0xBB67AE85 @ H1
.int 0x3C6EF372 @ H2
.int 0xA54FF53A @ H3
.int 0x510E527F @ H4
.int 0x9B05688C @ H5
.int 0x1F83D9AB @ H6
.int 0x5BE0CD19 @ H7
/* array 64 constantes Kt */
tbConstKt:
.int 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5
.int 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174
.int 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da
.int 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967
.int 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85
.int 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070
.int 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3
.int 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
 
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
iNbBlocs: .skip 4
sZoneConv: .skip 24
sZoneTrav: .skip 1000
.align 8
tbH: .skip 4 * 8 @ 8 variables H
tbabcdefgh: .skip 4 * 8
tbW: .skip 4 * 64 @ 64 words W
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrszMessRosetta
//ldr r0,iAdrszMessTest1
//ldr r0,iAdrszMessTest2
//ldr r0,iAdrszMessSup64
bl computeSHA256 @ call routine SHA1
 
ldr r0,iAdrszMessResult
bl affichageMess @ display message
 
ldr r0, iAdrtbH
bl displaySHA1
 
ldr r0,iAdrszMessFinPgm
bl affichageMess @ display message
 
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrszCarriageReturn: .int szCarriageReturn
iAdrszMessResult: .int szMessResult
iAdrszMessRosetta: .int szMessRosetta
iAdrszMessTest1: .int szMessTest1
iAdrszMessTest2: .int szMessTest2
iAdrsZoneTrav: .int sZoneTrav
iAdrsZoneConv: .int sZoneConv
iAdrszMessFinPgm: .int szMessFinPgm
iAdrszMessSup64: .int szMessSup64
/******************************************************************/
/* compute SHA1 */
/******************************************************************/
/* r0 contains the address of the message */
computeSHA256:
push {r1-r12,lr} @ save registres
ldr r1,iAdrsZoneTrav
mov r2,#0 @ counter length
debCopy: @ copy string in work area
ldrb r3,[r0,r2]
strb r3,[r1,r2]
cmp r3,#0
addne r2,r2,#1
bne debCopy
lsl r6,r2,#3 @ initial message length in bits
mov r3,#0b10000000 @ add bit 1 at end of string
strb r3,[r1,r2]
add r2,r2,#1 @ length in bytes
lsl r4,r2,#3 @ length in bits
mov r3,#0
addZeroes:
lsr r5,r2,#6
lsl r5,r5,#6
sub r5,r2,r5
cmp r5,#56
beq storeLength @ yes -> end add
strb r3,[r1,r2] @ add zero at message end
add r2,#1 @ increment lenght bytes
add r4,#8 @ increment length in bits
b addZeroes
storeLength:
add r2,#4 @ add four bytes
rev r6,r6 @ inversion bits initials message length
str r6,[r1,r2] @ and store at end
 
ldr r7,iAdrtbConstHi @ constantes H address
ldr r4,iAdrtbH @ start area H
mov r5,#0
loopConst: @ init array H with start constantes
ldr r6,[r7,r5,lsl #2] @ load constante
str r6,[r4,r5,lsl #2] @ and store
add r5,r5,#1
cmp r5,#8
blt loopConst
@ split into block of 64 bytes
add r2,#4 @ TODO : à revoir
lsr r4,r2,#6 @ blocks number
ldr r0,iAdriNbBlocs
str r4,[r0] @ save block maxi
mov r7,#0 @ n° de block et r1 contient l adresse zone de travail
loopBlock: @ begin loop of each block of 64 bytes
mov r0,r7
bl inversion @ inversion each word because little indian
ldr r3,iAdrtbW @ working area W address
mov r6,#0 @ indice t
/* r2 address begin each block */
ldr r1,iAdrsZoneTrav
add r2,r1,r7,lsl #6 @ compute block begin indice * 4 * 16
//vidregtit avantloop
//mov r0,r2
//vidmemtit verifBloc r0 10
loopPrep: @ loop for expand 80 words
cmp r6,#15 @
bgt expand1
ldr r0,[r2,r6,lsl #2] @ load byte message
str r0,[r3,r6,lsl #2] @ store in first 16 block
b expandEnd
 
expand1:
sub r8,r6,#2
ldr r9,[r3,r8,lsl #2]
ror r10,r9,#17 @ fonction e1 (256)
ror r11,r9,#19
eor r10,r10,r11
lsr r11,r9,#10
eor r10,r10,r11
sub r8,r6,#7
ldr r9,[r3,r8,lsl #2]
add r9,r9,r10 @ + w - 7
sub r8,r6,#15
ldr r10,[r3,r8,lsl #2]
ror r11,r10,#7 @ fonction e0 (256)
ror r12,r10,#18
eor r11,r12
lsr r12,r10,#3
eor r10,r11,r12
add r9,r9,r10
sub r8,r6,#16
ldr r11,[r3,r8,lsl #2]
add r9,r9,r11
 
str r9,[r3,r6,lsl #2]
expandEnd:
add r6,r6,#1
cmp r6,#64 @ 64 words ?
blt loopPrep @ and loop
 
 
/* COMPUTING THE MESSAGE DIGEST */
/* r1 area H constantes address */
/* r3 working area W address */
/* r5 address constantes K */
/* r6 counter t */
/* r7 block counter */
/* r8 addresse variables a b c d e f g h */
//ldr r0,iAdrtbW
//vidmemtit verifW80 r0 20
@ init variable a b c d e f g h
ldr r0,iAdrtbH
ldr r8,iAdrtbabcdefgh
mov r1,#0
loopInita:
ldr r9,[r0,r1,lsl #2]
str r9,[r8,r1,lsl #2]
add r1,r1,#1
cmp r1,#8
blt loopInita
 
ldr r1,iAdrtbConstHi
ldr r5,iAdrtbConstKt
mov r6,#0
loop64T: @ begin loop 64 t
ldr r9,[r8,#var_h]
ldr r10,[r8,#var_e] @ calcul T1
ror r11,r10,#6 @ fonction sigma 1
ror r12,r10,#11
eor r11,r12
ror r12,r10,#25
eor r11,r12
add r9,r9,r11 @ h + sigma1 (e)
ldr r0,[r8,#var_f] @ fonction ch x and y xor (non x and z)
ldr r4,[r8,#var_g]
and r11,r10,r0
mvn r12,r10
and r12,r12,r4
eor r11,r12
add r9,r9,r11 @ h + sigma1 (e) + ch (e,f,g)
ldr r0,[r5,r6,lsl #2] @ load constantes k0
add r9,r9,r0
ldr r0,[r3,r6,lsl #2] @ Wt
add r9,r9,r0
@ calcul T2
ldr r10,[r8,#var_a] @ fonction sigma 0
ror r11,r10,#2
ror r12,r10,#13
eor r11,r11,r12
ror r12,r10,#22
eor r11,r11,r12
ldr r2,[r8,#var_b]
ldr r4,[r8,#var_c]
@ fonction maj x and y xor x and z xor y and z
and r12,r10,r2
and r0,r10,r4
eor r12,r12,r0
and r0,r2,r4
eor r12,r12,r0 @
add r12,r12,r11 @ T2
@ compute variables
ldr r4,[r8,#var_g]
str r4,[r8,#var_h]
ldr r4,[r8,#var_f]
str r4,[r8,#var_g]
ldr r4,[r8,#var_e]
str r4,[r8,#var_f]
ldr r4,[r8,#var_d]
add r4,r4,r9 @ add T1
str r4,[r8,#var_e]
ldr r4,[r8,#var_c]
str r4,[r8,#var_d]
ldr r4,[r8,#var_b]
str r4,[r8,#var_c]
ldr r4,[r8,#var_a]
str r4,[r8,#var_b]
add r4,r9,r12 @ add T1 T2
str r4,[r8,#var_a]
mov r0,r8
 
add r6,r6,#1 @ increment t
cmp r6,#64
blt loop64T
@ End block
ldr r0,iAdrtbH @ start area H
mov r10,#0
loopStoreH:
ldr r9,[r8,r10,lsl #2]
ldr r3,[r0,r10,lsl #2]
add r3,r9
str r3,[r0,r10,lsl #2] @ store variables in H0
add r10,r10,#1
cmp r10,#8
blt loopStoreH
@ other bloc
add r7,#1 @ increment block
ldr r0,iAdriNbBlocs
ldr r4,[r0] @ restaur maxi block
cmp r7,r4 @ maxi ?
 
blt loopBlock @ loop other block
 
mov r0,#0 @ routine OK
100:
pop {r1-r12,lr} @ restaur registers
bx lr @ return
iAdrtbConstHi: .int tbConstHi
iAdrtbConstKt: .int tbConstKt
iAdrtbH: .int tbH
iAdrtbW: .int tbW
iAdrtbabcdefgh: .int tbabcdefgh
iAdriNbBlocs: .int iNbBlocs
/******************************************************************/
/* inversion des mots de 32 bits d un bloc */
/******************************************************************/
/* r0 contains N° block */
inversion:
push {r1-r3,lr} @ save registers
ldr r1,iAdrsZoneTrav
add r1,r0,lsl #6 @ debut du bloc
mov r2,#0
1: @ start loop
ldr r3,[r1,r2,lsl #2]
rev r3,r3
str r3,[r1,r2,lsl #2]
add r2,r2,#1
cmp r2,#16
blt 1b
100:
pop {r1-r3,lr} @ restaur registres
bx lr @return
/******************************************************************/
/* display hash SHA1 */
/******************************************************************/
/* r0 contains the address of hash */
displaySHA1:
push {r1-r3,lr} @ save registres
mov r3,r0
mov r2,#0
1:
ldr r0,[r3,r2,lsl #2] @ load 4 bytes
//rev r0,r0 @ reverse bytes
ldr r1,iAdrsZoneConv
bl conversion16 @ conversion hexa
ldr r0,iAdrsZoneConv
bl affichageMess
add r2,r2,#1
cmp r2,#LGHASH / 4
blt 1b @ and loop
ldr r0,iAdrszCarriageReturn
bl affichageMess @ display message
100:
pop {r1-r3,lr} @ restaur registers
bx lr @ return
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
</syntaxhighlight>
{{Output}}
<pre>
Rosetta code => 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
Program End ok.
</pre>
=={{header|AutoHotkey}}==
Source: [https://github.com/jNizM/AutoHotkey_Scripts/tree/master/Functions/Checksums SHA-256 @github] by jNizM
<langsyntaxhighlight AutoHotkeylang="autohotkey">str := "Rosetta code"
MsgBox, % "File:`n" (file) "`n`nSHA-256:`n" FileSHA256(file)
 
 
 
; SHA256 ============================================================================
Line 57 ⟶ 893:
StrPut(string, &data, floor(length / chrlength), encoding)
return CalcAddrHash(&data, length, algid, hash, hashlength)
}</langsyntaxhighlight>
{{out}}
<pre>String: Rosetta code
SHA-256: 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF</pre>
 
=={{header|BBC BASICAWK}}==
Using the system function as a 'library'.
===Library===
<syntaxhighlight lang="awk">{
("echo -n " $0 " | sha256sum") | getline sha;
gsub(/[^0-9a-zA-Z]/, "", sha);
print sha;
}
</syntaxhighlight>
 
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|BASIC}}==
==={{header|BaCon}}===
<syntaxhighlight 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</syntaxhighlight>
{{out}}
<pre>
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
</pre>
 
==={{header|BBC BASIC}}===
====Library====
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> PRINT FNsha256("Rosetta code")
END
Line 89 ⟶ 964:
hash$ += RIGHT$("0" + STR$~buffer%?i%, 2)
NEXT
= hash$</langsyntaxhighlight>
{{out}}
'''Output:'''
<pre>
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
</pre>
 
====Native====
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight lang="bbcbasic"> REM SHA-256 calculation by Richard Russell in BBC BASIC for Windows
REM Must run in FLOAT64 mode:
Line 220 ⟶ 1,095:
WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE
WHILE n# < &80000000 : n# += 2^32 : ENDWHILE
= n#</langsyntaxhighlight>
{{out}}
'''Output:'''
<pre>
764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF
Line 227 ⟶ 1,102:
 
=={{header|C}}==
Requires OpenSSL, compile flag: <code>-lssl -lcrypto</code>
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <string.h>
#include <openssl/sha.h>
Line 242 ⟶ 1,117:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp}}==
<langsyntaxhighlight lang="csharp">using System;
using System.Security.Cryptography;
using System.Text;
Line 266 ⟶ 1,141:
}
}
}</langsyntaxhighlight>
 
=={{header|C++}}==
Uses [https://www.cryptopp.com/ crypto++]. Compile it with -lcryptopp
 
https://www.cryptopp.com/wiki/Linux#apt-get
Missing description how to use g++ or other program linux\windows 10
 
<syntaxhighlight lang="cpp">#include <iostream>
#include <cryptopp/filters.h>
#include <cryptopp/hex.h>
#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;
}
</syntaxhighlight>
 
===Implementation===
<syntaxhighlight lang="c++">
#include <bit>
#include <cstdint>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <string>
#include <vector>
 
class SHA256 {
public:
std::string message_digest(const std::string& message) {
std::vector<int64_t> hash = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
 
const std::vector<int8_t> bytes = add_padding(message);
for ( uint64_t i = 0; i < bytes.size() / BLOCK_LENGTH; ++i ) {
std::vector<int32_t> words(BLOCK_LENGTH, 0);
for ( int32_t j = 0; j < BLOCK_LENGTH; ++j ) {
words[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 );
}
for ( int32_t j = 16; j < BLOCK_LENGTH; j++ ) {
words[j] = sigma(3, words[j - 2]) + words[j - 7] + sigma(2, words[j - 15]) + words[j - 16];
}
 
int32_t a = hash[0], b = hash[1], c = hash[2], d = hash[3],
e = hash[4], f = hash[5], g = hash[6], h = hash[7];
 
for ( int32_t j = 0; j < BLOCK_LENGTH; ++j ) {
int32_t t = h + sigma(1, e) + ch(e, f, g) + kk[j] + words[j];
int32_t tt = sigma(0, a) + maj(a, b, c);
h = g; g = f; f = e;
e = d + t;
d = c; c = b; b = a;
a = t + tt;
}
 
hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d;
hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h;
}
 
std::stringstream stream;
for ( int32_t i = 0; i < BLOCK_LENGTH; ++i ) {
int8_t byte_value = static_cast<int8_t>(hash[i / 8] >> ( 7 - i % 8 ) * 4);
stream << std::hex << ( byte_value & 0xf );
}
return stream.str();
}
 
private:
std::vector<int8_t> add_padding(const std::string& message) {
std::vector<int8_t> bytes(message.begin(), message.end());
bytes.emplace_back(static_cast<uint8_t>(0x80));
 
uint32_t padding = BLOCK_LENGTH - ( bytes.size() % BLOCK_LENGTH );
if ( padding < 8 ) {
padding += BLOCK_LENGTH;
}
bytes.resize(bytes.size() + padding - 8, static_cast<int8_t>(0x0));
 
const uint64_t bit_length = 8 * message.length();
for ( int32_t i = 7; i >= 0; --i ) {
bytes.emplace_back(static_cast<int8_t>(bit_length >> ( 8 * i )));
}
return bytes;
}
 
int32_t sigma(const uint32_t& group, const uint32_t& x) {
int32_t result;
switch ( group ) {
case 0 : result = std::rotr(x, 2) ^ std::rotr(x, 13) ^ std::rotr(x, 22); break;
case 1 : result = std::rotr(x, 6) ^ std::rotr(x, 11) ^ std::rotr(x, 25); break;
case 2 : result = std::rotr(x, 7) ^ std::rotr(x, 18) ^ ( x >> 3 ); break;
case 3 : result = std::rotr(x, 17) ^ std::rotr(x, 19) ^ ( x >> 10 ); break;
default : throw std::invalid_argument("Unexpected argument for sigma: " + std::to_string(group));
}
return result;
}
 
int32_t ch(const int32_t& x, const int32_t y, const int32_t z) {
return ( x & y ) ^ ( ~x & z );
}
 
int32_t maj(const int32_t& x, const int32_t y, const int32_t z) {
return ( x & y ) ^ ( x & z ) ^ ( y & z );
}
 
const std::vector<int64_t> kk = {
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 };
 
const int32_t BLOCK_LENGTH = 64;
};
 
int main() {
SHA256 sha256;
std::cout << sha256.message_digest("Rosetta code") << std::endl;
}
</syntaxhighlight>
{{ out }}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Caché ObjectScript}}==
Line 277 ⟶ 1,290:
=={{header|Clojure}}==
{{libheader|pandect}}
<langsyntaxhighlight lang="clojure">(use 'pandect.core)
(sha256 "Rosetta code")</langsyntaxhighlight>
 
{{Out}}
Line 285 ⟶ 1,298:
=={{header|Common Lisp}}==
{{libheader|Ironclad}}
<langsyntaxhighlight lang="lisp">(ql:quickload 'ironclad)
(defun sha-256 (str)
(ironclad:byte-array-to-hex-string
Line 291 ⟶ 1,304:
(ironclad:ascii-string-to-byte-array str))))
 
(sha-256 "Rosetta code")</langsyntaxhighlight>
 
{{Out}}
<pre>"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"</pre>
 
=={{header|Crystal}}==
<syntaxhighlight lang="ruby">require "openssl"
puts OpenSSL::Digest.new("SHA256").update("Rosetta code")
</syntaxhighlight>
Output:
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|D}}==
===Standard Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.digest.sha;
 
writefln("%-(%02x%)", "Rosetta code".sha256Of);
}</langsyntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
===Simple Implementation===
<langsyntaxhighlight lang="d">// Copyright (C) 2005, 2006 Free Software Foundation, Inc. GNU License.
// Translated to D language. Only lightly tested, not for serious use.
 
Line 408 ⟶ 1,428:
pure nothrow @nogc in {
assert(inBuffer.length % 64 == 0);
} bodydo {
// Round functions.
static uint F1(in uint e, in uint f, in uint g) pure nothrow @safe @nogc {
Line 654 ⟶ 1,674:
writefln("%(%02x%)", SHA256.digest(data));
}
}</langsyntaxhighlight>
Compile with -version=sha_256_main to run the main function.
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
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.
 
=={{header|Delphi}}==
{{libheader| System.SysUtils}}
{{libheader| DCPsha256}} Part of '''DCPcrypt Cryptographic Component Library v2.1'''[https://bitbucket.org/wpostma/dcpcrypt2010] by David Barton.
<syntaxhighlight lang="delphi">
program SHA_256;
 
{$APPTYPE CONSOLE}
 
uses
System.SysUtils,
DCPsha256;
 
function SHA256(const Str: string): string;
var
HashDigest: array of byte;
d: Byte;
begin
Result := '';
with TDCP_sha256.Create(nil) do
begin
Init;
UpdateStr(Str);
SetLength(HashDigest, GetHashSize div 8);
final(HashDigest[0]);
for d in HashDigest do
Result := Result + d.ToHexString(2);
Free;
end;
end;
 
begin
Writeln(SHA256('Rosetta code'));
readln;
 
end.
 
</syntaxhighlight>
{{out}}
<pre>
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
</pre>
=={{header|DWScript}}==
<syntaxhighlight lang="delphi">PrintLn( HashSHA256.HashData('Rosetta code') );</syntaxhighlight>
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="lisp">(secure-hash 'sha256 "Rosetta code") ;; as string of hex digits</langsyntaxhighlight>
 
=={{header|Erlang}}==
Line 673 ⟶ 1,737:
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System.Security.Cryptography
open System.Text
 
Line 681 ⟶ 1,745:
|> System.BitConverter.ToString
|> printfn "%s"
</syntaxhighlight>
</lang>
{{out}}
<pre>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
</pre>
 
=={{header|Factor}}==
{{works with|Factor|0.98}}
<syntaxhighlight lang="factor">USING: checksums checksums.sha io math.parser ;
 
"Rosetta code" sha-256 checksum-bytes bytes>hex-string print</syntaxhighlight>
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Forth}}==
===GNU Forth 0.7.9 on Linux===
Uses the information from the C version on which libraries to reference.
<syntaxhighlight lang="forth">
c-library crypto
 
s" ssl" add-lib
s" crypto" add-lib
 
\c #include <openssl/sha.h>
c-function sha256 SHA256 a n a -- a
 
end-c-library
 
: 2h. ( n1 -- ) base @ swap hex s>d <# # # #> type base ! ;
 
: .digest ( a -- )
32 bounds do i c@ 2h. loop space ;
 
s" Rosetta code" 0 sha256 .digest cr
bye
</syntaxhighlight>
{{Out}}
<pre>
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
</pre>
 
=={{header|Fortran}}==
===Intel Fortran on Windows===
Using Windows API. See [https://msdn.microsoft.com/en-us/library/aa379886.aspx CryptAcquireContext], [https://msdn.microsoft.com/en-us/library/aa379908.aspx CryptCreateHash], [https://msdn.microsoft.com/en-us/library/aa380202.aspx CryptHashData] and [https://msdn.microsoft.com/en-us/library/aa379947.aspx CryptGetHashParam] on MSDN.
 
With the file rc.txt containing the string "Rosetta Code":
<pre>sha256 rc.txt
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF rc.txt (12 bytes)</pre>
 
<syntaxhighlight 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</syntaxhighlight>
 
=={{header|Free Pascal}}==
<syntaxhighlight 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.</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|FreeBASIC}}==
<syntaxhighlight 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</syntaxhighlight>
{{out}}
<pre>Rosetta code => 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|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.
<syntaxhighlight lang="frink">println[messageDigest["Rosetta code", "SHA-256"]]</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|FunL}}==
A SHA-256 function can be defined using the Java support library.
 
<langsyntaxhighlight 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()</langsyntaxhighlight>
 
Here is a definition implemented as a direct translation of the pseudocode at '''[[wp:SHA-256|SHA-256]]'''.
 
<langsyntaxhighlight lang="funl">def sha256( message ) =
//Initialize hash values
h0 = 0x6a09e667
Line 778 ⟶ 2,158:
 
// Produce the final hash value (big-endian)
map( a -> format('%08x', a.intValue()), [h0, h1, h2, h3, h4, h5, h6, h7] ).mkString()</langsyntaxhighlight>
 
Here is a test comparing the two and also verifying the hash values of the empty message string.
 
<langsyntaxhighlight lang="funl">message = 'Rosetta code'
 
println( 'FunL: "' + message + '" ~> ' + sha256(message) )
Line 790 ⟶ 2,170:
 
println( 'FunL: "' + message + '" ~> ' + sha256(message) )
println( 'Java: "' + message + '" ~> ' + sha256Java(message) )</langsyntaxhighlight>
 
{{out}}
Line 800 ⟶ 2,180:
Java: "" ~> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
</pre>
 
=={{header|Genie}}==
<syntaxhighlight 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")</syntaxhighlight>
 
{{out}}
<pre>prompt$ valac SHA-256.gs
prompt$ ./SHA-256
Rosetta code
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 816 ⟶ 2,219:
}
fmt.Printf("%x\n", h.Sum(nil))
}</langsyntaxhighlight>
{{out}}
<pre>
Line 823 ⟶ 2,226:
 
=={{header|Groovy}}==
<langsyntaxhighlight lang="groovy">def sha256Hash = { text ->
java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes)
.collect { String.format("%02x", it) }.join('')
}</langsyntaxhighlight>
Testing
<langsyntaxhighlight lang="groovy">assert sha256Hash('Rosetta code') == '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'</langsyntaxhighlight>
 
=={{header|Halon}}==
<syntaxhighlight lang="halon">$var = "Rosetta code";
echo sha2($var, 256);</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import Data.Char (ord)
import Crypto.Hash.SHA256 (hash)
import Data.ByteString (unpack, pack)
Line 842 ⟶ 2,252:
map (fromIntegral.ord) -- to array of Word8
"Rosetta code"
</syntaxhighlight>
</lang>
{{out}}
<pre style="font-size:80%">764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Haxe}}==
<syntaxhighlight lang="haxe">import haxe.crypto.Sha256;
 
class Main {
static function main() {
var sha256 = Sha256.encode("Rosetta code");
Sys.println(sha256);
}
}</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|J}}==
'''Solution:'''
From J8 the <tt>ide/qt</tt> addon provides bindings to Qt libraries that include support for various hashing algorithms including SHA-256.
<syntaxhighlight lang="j">require '~addons/ide/qt/qt.ijs'
getsha256=: 'sha256'&gethash_jqtide_</syntaxhighlight>
'''Example Usage:'''
<syntaxhighlight lang="j"> getsha256 'Rosetta code'
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</syntaxhighlight>
 
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.
 
<syntaxhighlight lang="j">sha256=: 3&(128!:6)</syntaxhighlight>
 
<syntaxhighlight lang="j"> sha256 'Rosetta code'
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</syntaxhighlight>
 
=={{header|Java}}==
The solution to this task would be a small modification to [[MD5#Java|MD5]] (replacing "MD5" with "SHA-256" as noted [http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#MessageDigest here]).
 
===Implementation===
<syntaxhighlight lang = "java">
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
 
public final class SHA256Task {
 
public static void main(String[] args) {
System.out.println(SHA256.messageDigest("Rosetta code"));
}
 
}
 
final class SHA256 {
public static String messageDigest(String message) {
int[] hash = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };
final byte[] bytes = addPadding(message);
for ( int i = 0; i < bytes.length / BLOCK_LENGTH; i++ ) {
int[] words = new int[BLOCK_LENGTH];
for ( int j = 0; j < BLOCK_LENGTH; j++ ) {
words[j / 4] |= ( bytes[i * BLOCK_LENGTH + j] & 0xff ) << ( ( 3 - j % 4 ) * 8 );
}
for ( int j = 16; j < BLOCK_LENGTH; j++ ) {
words[j] = sigma(3, words[j - 2]) + words[j - 7] + sigma(2, words[j - 15]) + words[j - 16];
}
int a = hash[0], b = hash[1], c = hash[2], d = hash[3],
e = hash[4], f = hash[5], g = hash[6], h = hash[7];
for ( int j = 0; j < BLOCK_LENGTH; j++ ) {
int t = h + sigma(1, e) + ch(e, f, g) + kk[j] + words[j];
int tt = sigma(0, a) + maj(a, b, c);
h = g; g = f; f = e;
e = d + t;
d = c; c = b; b = a;
a = t + tt;
}
 
hash[0] += a; hash[1] += b; hash[2] += c; hash[3] += d;
hash[4] += e; hash[5] += f; hash[6] += g; hash[7] += h;
}
StringBuilder result = new StringBuilder();
for ( int i = 0; i < BLOCK_LENGTH; i++ ) {
result.append(String.format("%1x", ( hash[i / 8] >>> ( 7 - i % 8 ) * 4 ) & 0xf ));
}
return result.toString();
}
private static byte[] addPadding(String message) {
byte[] bytes = message.getBytes(StandardCharsets.UTF_8);
bytes = Arrays.copyOf(bytes, bytes.length + 1);
bytes[bytes.length - 1] = (byte) 0x80;
int padding = BLOCK_LENGTH - ( bytes.length % BLOCK_LENGTH );
if ( padding < 8 ) {
padding += BLOCK_LENGTH;
}
bytes = Arrays.copyOf(bytes, bytes.length + padding);
final long bitLength = message.length() * 8;
for ( int i = 0; i < 8; i++ ) {
bytes[bytes.length - 1 - i] = (byte) ( bitLength >>> ( 8 * i ) );
}
return bytes;
}
private static int sigma(int group, int x) {
return switch ( group ) {
case 0 -> Integer.rotateRight(x, 2) ^ Integer.rotateRight(x, 13) ^ Integer.rotateRight(x, 22);
case 1 -> Integer.rotateRight(x, 6) ^ Integer.rotateRight(x, 11) ^ Integer.rotateRight(x, 25);
case 2 -> Integer.rotateRight(x, 7) ^ Integer.rotateRight(x, 18) ^ ( x >>> 3 );
case 3 -> Integer.rotateRight(x, 17) ^ Integer.rotateRight(x, 19) ^ ( x >>> 10 );
default -> throw new AssertionError("Unexpected argument for sigma: " + group);
};
}
private static int ch(int x, int y, int z) {
return ( x & y ) ^ ( ~x & z );
}
 
private static int maj(int x, int y, int z) {
return ( x & y ) ^ ( x & z ) ^ ( y & z );
}
private static final int[] kk = new int[] {
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 };
private static final int BLOCK_LENGTH = 64;
}
</syntaxhighlight>
{{ out }}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|JavaScript}}==
<syntaxhighlight lang="javascript">
const crypto = require('crypto');
 
const msg = 'Rosetta code';
const hash = crypto.createHash('sha256').update(msg).digest('hex');
 
console.log(hash);
</syntaxhighlight>
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Jsish}}==
<syntaxhighlight lang="javascript">/* SHA-256 hash in Jsish */
var str = 'Rosetta code';
puts(Util.hash(str, {type:'sha256'}));
 
/*
=!EXPECTSTART!=
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
=!EXPECTEND!=
*/</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish sha-256.jsi
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
prompt$ jsish -u sha-256.jsi
[PASS] sha-256.jsi</pre>
 
=={{header|Julia}}==
<lang{{works with|Julia>|0.6}}
clear = "Rosetta code"
standard = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
 
<syntaxhighlight lang="julia">msg = "Rosetta code"
 
using Nettle
digest = hexdigest("sha256", msg)
 
# native
using SHA
digest1 = join(num2hex.(sha256(msg)))
 
@assert digest == digest1</syntaxhighlight>
crypt = sha256(clear)
 
=={{header|Kotlin}}==
println("Testing Julia's SHA-256:")
<syntaxhighlight lang="scala">// version 1.0.6
if crypt == standard
 
println(" OK, \"", clear, "\" => ", crypt)
import java.security.MessageDigest
else
 
println("The hash does not match the standard value.")
fun main(args: Array<String>) {
end
val text = "Rosetta code"
</lang>
val bytes = text.toByteArray()
val md = MessageDigest.getInstance("SHA-256")
val digest = md.digest(bytes)
for (byte in digest) print("%02x".format(byte))
println()
}</syntaxhighlight>
 
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Testing Julia's SHA-256:
OK, "Rosetta code" => 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
Line 879 ⟶ 2,468:
Use the cipher_list method to view these algorithms.
 
<langsyntaxhighlight Lassolang="lasso">// The following will return a list of all the cipher
// algorithms supported by the installation of Lasso
cipher_list
Line 889 ⟶ 2,478:
// return the SHA-256 digest. Dependant on SHA-256 being an available digest method
cipher_digest('Rosetta Code', -digest='SHA-256',-hex=true)
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
Line 896 ⟶ 2,485:
{{libheader|sha2}} ([http://code.google.com/p/sha2/ luarocks install sha2])
 
<langsyntaxhighlight Lualang="lua">#!/usr/bin/lua
 
require "sha2"
 
print(sha2.sha256hex("Rosetta code"))</langsyntaxhighlight>
 
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="text">Hash["Rosetta code","SHA256","HexString"]</syntaxhighlight>
 
<lang>IntegerString[Hash["Rosetta code", "SHA256"], 16]</lang>
 
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|min}}==
{{works with|min|0.19.6}}
<syntaxhighlight lang="min">"Rosetta code" sha256 puts!</syntaxhighlight>
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|NetRexx}}==
This solution is basically the same as that for [[MD5#NetRExx|MD5]], substituting "SHA-256" for "MD5" as the algorithm to use in the <tt>MessageDigest</tt> instance.
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 964 ⟶ 2,559:
return digestSum
</syntaxhighlight>
</lang>
'''Output:'''
<pre>
Line 973 ⟶ 2,568:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="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")</langsyntaxhighlight>
 
=={{header|Nim}}==
{{libheader|nimcrypto}}
Using the third party library <code>nimcrypto</code>, the program is very simple:
 
<syntaxhighlight lang="nim">import nimcrypto
 
echo sha256.digest("Rosetta code")</syntaxhighlight>
 
{{out}}
<pre>764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF</pre>
 
There is also the possibility to use directly a library such as OpenSSL. This is less convenient as we have to interface with a C library and to work with C types. Here is the way to go:
 
{{libheader|OpenSSL}}
 
Compile with <code>nim -d:ssl c sha256.nim</code>:
<langsyntaxhighlight lang="nim">import strutils
 
const SHA256Len = 32
Line 990 ⟶ 2,597:
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")</langsyntaxhighlight>
 
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Oberon-2}}==
{{works with|oo2c}}{{libheader|crypto}}
<syntaxhighlight 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.
</syntaxhighlight>
{{out}}
<pre>
SHA256:
764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D
6468D7D1 124CDFCF
</pre>
 
=={{header|Objeck}}==
<syntaxhighlight lang="objeck">
<lang Objeck>
class ShaHash {
function : Main(args : String[]) ~ Nil {
Line 1,008 ⟶ 2,644:
}
}
</syntaxhighlight>
</lang>
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Line 1,020 ⟶ 2,656:
</pre>
or in XCode.
<langsyntaxhighlight lang="objc">#import <Cocoa/Cocoa.h>
#import <CommonCrypto/CommonDigest.h>
 
Line 1,039 ⟶ 2,675:
return 0;
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
Line 1,045 ⟶ 2,681:
{{libheader|caml-sha}}
 
<langsyntaxhighlight lang="ocaml">let () =
let s = "Rosetta code" in
let digest = Sha256.string s in
print_endline (Sha256.to_hex digest)</langsyntaxhighlight>
 
Running this script in interpreted mode:
Line 1,055 ⟶ 2,691:
$ ocaml -I +sha sha256.cma sha.ml
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|OS X sha256sum}}==
Apple OS X command line with echo and sha256sum.
 
<syntaxhighlight lang="sha256sum">echo -n 'Rosetta code' | sha256sum</syntaxhighlight>
 
Using the -n flag for echo is required as echo normally outputs a newline.
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf -
</pre>
 
=={{header|PARI/GP}}==
It works on Linux systems.
 
<syntaxhighlight lang="parigp">sha256(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha256sum|cut -d' ' -f1`)\"")</syntaxhighlight>
 
The code above creates a new function sha256(s) which returns SHA-256 hash of item s.
{{out}}
<pre>
sha256("Rosetta code") = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
</pre>
 
=={{header|Perl}}==
The preferred way to do a task like this is to use an already written module, for example:
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use strict ;
use warnings ;
Line 1,066 ⟶ 2,724:
my $digest = sha256_hex my $phrase = "Rosetta code" ;
print "SHA-256('$phrase'): $digest\n" ;
</syntaxhighlight>
</lang>
{{out}}
<pre>SHA-256('Rosetta code'): 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Line 1,073 ⟶ 2,731:
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.
<syntaxhighlight lang="perl">
<lang Perl>
package Digest::SHA256::PP;
 
Line 1,089 ⟶ 2,747:
next if ("1" x $p) =~ /^(11+?)\1+$/;
# The choice to generate h and k instead of hard coding
# them is inspired by the Perl 6Raku implementation.
my $c = $p ** ( 1/3 );
push @k, int( ($c - int $c) * WORD );
Line 1,213 ⟶ 2,871:
 
1;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,220 ⟶ 2,878:
</pre>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
 
<span style="color: #008080;">include</span> <span style="color: #000000;">builtins</span><span style="color: #0000FF;">\</span><span style="color: #000000;">sha256</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
The following implementation takes all data as input. Ideally, input should be given lazily or something.
 
<lang Perl 6>say sha256 "Rosetta code";
<span style="color: #008080;">function</span> <span style="color: #000000;">asHex</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
constant primes = grep &is-prime, 2 .. *;
<span style="color: #004080;">string</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""</span>
sub init(&f) {
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, primes
<span style="color: #000000;">res</span> <span style="color: #0000FF;">&=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%02X"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">res</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">asHex</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sha256</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Rosetta code"</span><span style="color: #0000FF;">))</span>
sub infix:<m+> { ($^a + $^b) % 2**32 }
<!--</syntaxhighlight>-->
sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }
{{out}}
<pre>
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
</pre>
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
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #000080;font-style:italic;">--
-- demo\rosetta\sha-256.exw
-- ========================
--</span>
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #000080;font-style:italic;">-- fairly faithful rendition of https://en.wikipedia.org/wiki/SHA-2
proto sha256($) returns Blob {*}
-- with slightly improved names (eg s0 -&gt; sigma0) from elsewhere.
multi sha256(Str $str where all($str.ords) < 128) {
-- See also sha-256asm.exw for a faster inline asm version, and
sha256 $str.encode: 'ascii'
-- sha-256dll.exw is much shorter as it uses a pre-built dll.
}
multi sha256(Blob $data) {
constant K = init(* **(1/3))[^64];
my @b = $data.list, 0x80;
push @b, 0 until (8 * @b - 448) %% 512;
push @b, reverse (8 * $data).polymod(256 xx 7);
my @word = :256[@b.shift xx 4] xx @b/4;
--Initial array of round constants
my @H = init(&sqrt)[^8];
--(first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311):</span>
my @w;
<span style="color: #008080;">constant</span> <span style="color: #000000;">k</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span>
loop (my $i = 0; $i < @word; $i += 16) {
<span style="color: #000000;">0x428a2f98</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x71374491</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xb5c0fbcf</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xe9b5dba5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x3956c25b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x59f111f1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x923f82a4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xab1c5ed5</span><span style="color: #0000FF;">,</span>
my @h = @H;
<span style="color: #000000;">0xd807aa98</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x12835b01</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x243185be</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x550c7dc3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x72be5d74</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x80deb1fe</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x9bdc06a7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xc19bf174</span><span style="color: #0000FF;">,</span>
for ^64 -> $j {
<span style="color: #000000;">0xe49b69c1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xefbe4786</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x0fc19dc6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x240ca1cc</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x2de92c6f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x4a7484aa</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x5cb0a9dc</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x76f988da</span><span style="color: #0000FF;">,</span>
@w[$j] = $j < 16 ?? @word[$j + $i] // 0 !!
<span style="color: #000000;">0x983e5152</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xa831c66d</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xb00327c8</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xbf597fc7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xc6e00bf3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xd5a79147</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x06ca6351</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x14292967</span><span style="color: #0000FF;">,</span>
[m+]
<span style="color: #000000;">0x27b70a85</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x2e1b2138</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x4d2c6dfc</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x53380d13</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x650a7354</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x766a0abb</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x81c2c92e</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x92722c85</span><span style="color: #0000FF;">,</span>
rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3,
<span style="color: #000000;">0xa2bfe8a1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xa81a664b</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xc24b8b70</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xc76c51a3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xd192e819</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xd6990624</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xf40e3585</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x106aa070</span><span style="color: #0000FF;">,</span>
@w[$j-7],
<span style="color: #000000;">0x19a4c116</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x1e376c08</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x2748774c</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x34b0bcb5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x391c0cb3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x4ed8aa4a</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x5b9cca4f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x682e6ff3</span><span style="color: #0000FF;">,</span>
rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10,
<span style="color: #000000;">0x748f82ee</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x78a5636f</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x84c87814</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x8cc70208</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0x90befffa</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xa4506ceb</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xbef9a3f7</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">0xc67178f2</span><span style="color: #0000FF;">}</span>
@w[$j-16];
my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6];
<span style="color: #008080;">function</span> <span style="color: #000000;">pad64</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2];
<span style="color: #000080;font-style:italic;">-- round v up to multiple of 64</span>
my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22;
<span style="color: #008080;">return</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">((</span><span style="color: #000000;">v</span><span style="color: #0000FF;">+</span><span style="color: #000000;">63</span><span style="color: #0000FF;">)/</span><span style="color: #000000;">64</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">64</span>
my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25;
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j];
my $t2 = $σ0 m+ $maj;
<span style="color: #008080;">function</span> <span style="color: #000000;">uint32</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">)</span>
@h = $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6];
<span style="color: #008080;">return</span> <span style="color: #7060A8;">and_bitsu</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FFFFFFFF</span><span style="color: #0000FF;">)</span>
}
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
@H [Z[m+]]= @h;
}
<span style="color: #008080;">function</span> <span style="color: #000000;">sq_uint32</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">)</span>
return Blob.new: map { reverse .polymod(256 xx 3) }, @H;
<span style="color: #000080;font-style:italic;">-- apply uint32 to all elements of s</span>
}</lang>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">uint32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">dword</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- get dword as big-endian</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">#1000000</span><span style="color: #0000FF;">+</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">#10000</span><span style="color: #0000FF;">+</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">2</span><span style="color: #0000FF;">]*</span><span style="color: #000000;">#100</span><span style="color: #0000FF;">+</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">+</span><span style="color: #000000;">3</span><span style="color: #0000FF;">]</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">shr</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">/</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #004080;">atom</span> <span style="color: #000000;">v</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">bits</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">or_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">shr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">v</span><span style="color: #0000FF;">,</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">),</span><span style="color: #000000;">v</span><span style="color: #0000FF;">*</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">32</span><span style="color: #0000FF;">-</span><span style="color: #000000;">bits</span><span style="color: #0000FF;">))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">sha256</span><span style="color: #0000FF;">(</span><span style="color: #004080;">string</span> <span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span>
<span style="color: #000080;font-style:italic;">-- main function</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">,</span><span style="color: #000000;">temp1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">maj</span><span style="color: #0000FF;">,</span><span style="color: #000000;">temp2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">x</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">w</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">64</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">res</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)+</span><span style="color: #000000;">1</span>
<span style="color: #000080;font-style:italic;">--Initial hash values
--(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19)</span>
<span style="color: #004080;">atom</span> <span style="color: #000000;">h0</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0x6a09e667</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0xbb67ae85</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0x3c6ef372</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h3</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0xa54ff53a</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h4</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0x510e527f</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h5</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0x9b05688c</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h6</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0x1f83d9ab</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">h7</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0x5be0cd19</span>
<span style="color: #000080;font-style:italic;">-- add the '1' bit and space for size in bits, padded to multiple of 64</span>
<span style="color: #000000;">msg</span> <span style="color: #0000FF;">&=</span> <span style="color: #000000;">#80</span><span style="color: #0000FF;">&</span><span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #008000;">'\0'</span><span style="color: #0000FF;">,</span><span style="color: #000000;">pad64</span><span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">+</span><span style="color: #000000;">8</span><span style="color: #0000FF;">)-</span><span style="color: #000000;">len</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">8</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">to</span> <span style="color: #000000;">1</span> <span style="color: #008080;">by</span> <span style="color: #0000FF;">-</span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">msg</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">,</span><span style="color: #000000;">#FF</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">len</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">len</span><span style="color: #0000FF;">/</span><span style="color: #000000;">#100</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">len</span><span style="color: #0000FF;">=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Process the message in successive 512-bit (64 byte) chunks</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">chunk</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">by</span> <span style="color: #000000;">64</span> <span style="color: #008080;">do</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">16</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">dword</span><span style="color: #0000FF;">(</span><span style="color: #000000;">msg</span><span style="color: #0000FF;">,</span><span style="color: #000000;">chunk</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">1</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">4</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Extend the first 16 words into the remaining 48 words w[17..64] of the message schedule array</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">17</span> <span style="color: #008080;">to</span> <span style="color: #000000;">64</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">15</span><span style="color: #0000FF;">];</span> <span style="color: #000000;">s0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">7</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">18</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">shr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">3</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">2</span><span style="color: #0000FF;">];</span> <span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">17</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">19</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">shr</span><span style="color: #0000FF;">(</span><span style="color: #000000;">x</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">uint32</span><span style="color: #0000FF;">(</span><span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">16</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">-</span><span style="color: #000000;">7</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Initialize working variables to current hash value</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">h0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h7</span><span style="color: #0000FF;">}</span>
<span style="color: #000080;font-style:italic;">-- Compression function main loop</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">64</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">s1</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">6</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">11</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">25</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">ch</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">not_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">e</span><span style="color: #0000FF;">),</span><span style="color: #000000;">g</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">temp1</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">h</span><span style="color: #0000FF;">+</span><span style="color: #000000;">s1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">ch</span><span style="color: #0000FF;">+</span><span style="color: #000000;">k</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]+</span><span style="color: #000000;">w</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">s0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">2</span><span style="color: #0000FF;">),</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">13</span><span style="color: #0000FF;">)),</span><span style="color: #000000;">ror</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">22</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">maj</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">xor_bits</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">)),</span><span style="color: #7060A8;">and_bits</span><span style="color: #0000FF;">(</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">))</span>
<span style="color: #000000;">temp2</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s0</span><span style="color: #0000FF;">+</span><span style="color: #000000;">maj</span>
<span style="color: #000080;font-style:italic;">-- {h,g,f,e,d,c,b,a} = {g,f,e,uint32(d+temp1),c,b,a,uint32(temp1+temp2)} -- (works fine)</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">h</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sq_uint32</span><span style="color: #0000FF;">({</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">+</span><span style="color: #000000;">temp1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">temp1</span><span style="color: #0000FF;">+</span><span style="color: #000000;">temp2</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Add the compressed chunk to the current hash value</span>
<span style="color: #0000FF;">{</span><span style="color: #000000;">h0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h7</span><span style="color: #0000FF;">}</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sq_add</span><span style="color: #0000FF;">({</span><span style="color: #000000;">h0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h2</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h3</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h4</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h5</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h6</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h7</span><span style="color: #0000FF;">},{</span><span style="color: #000000;">a</span><span style="color: #0000FF;">,</span><span style="color: #000000;">b</span><span style="color: #0000FF;">,</span><span style="color: #000000;">c</span><span style="color: #0000FF;">,</span><span style="color: #000000;">d</span><span style="color: #0000FF;">,</span><span style="color: #000000;">e</span><span style="color: #0000FF;">,</span><span style="color: #000000;">f</span><span style="color: #0000FF;">,</span><span style="color: #000000;">g</span><span style="color: #0000FF;">,</span><span style="color: #000000;">h</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #000080;font-style:italic;">-- Produce the final hash value (big-endian)</span>
<span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">sq_uint32</span><span style="color: #0000FF;">({</span><span style="color: #000000;">h0</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h1</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h2</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h3</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h4</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h5</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h6</span><span style="color: #0000FF;">,</span> <span style="color: #000000;">h7</span><span style="color: #0000FF;">})</span> <span style="color: #000080;font-style:italic;">-- (or do sq_unit32 on the sq_add above)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">sprintf</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"%08x"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">res</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #008080;">return</span> <span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">res</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">sha256</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"Rosetta code"</span><span style="color: #0000FF;">)</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
<pre>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></pre>
"764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF"
</pre>
 
=={{header|PHP}}==
<syntaxhighlight lang="php"><?php
echo hash('sha256', 'Rosetta code');
</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|PicoLisp}}==
Library and implementation.
<langsyntaxhighlight PicoLisplang="picolisp">(setq *Sha256-K
(mapcar hex
'("428A2F98" "71374491" "B5C0FBCF" "E9B5DBA5" "3956C25B"
Line 1,432 ⟶ 3,193:
'(NIL (32)) ) ) ) ) )
 
(bye)</langsyntaxhighlight>
 
=={{header|PHPPike}}==
<syntaxhighlight lang="pike">
<lang php><?php
echostring hash('sha256',input '= "Rosetta code')";
string out = Crypto.SHA256.hash(input);
</lang>
write( String.string2hex(out) +"\n");
</syntaxhighlight>
{{Out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|PowerShell}}==
{{works with|PowerShell 5.0}}
<syntaxhighlight lang="powershell">
Set-Content -Value "Rosetta code" -Path C:\Colors\blue.txt -NoNewline -Force
Get-FileHash -Path C:\Colors\blue.txt -Algorithm SHA256
</syntaxhighlight>
{{out}}
<pre>
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
Algorithm Hash Path
--------- ---- ----
SHA256 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF C:\Colors\blue.txt
</pre>
 
=={{header|PureBasic}}==
PB Version 5.40
<syntaxhighlight 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()</syntaxhighlight>
{{out}}
<pre>[SHA2 256 bit] Text: Rosetta code ==> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Python}}==
Python has a standard module for this:
<langsyntaxhighlight lang="python">>>> import hashlib
>>> hashlib.sha256( "Rosetta code".encode() ).hexdigest()
'764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'
>>> </langsyntaxhighlight>
 
=={{header|R}}==
<syntaxhighlight lang="rsplus">
library(digest)
 
input <- "Rosetta code"
cat(digest(input, algo = "sha256", serialize = FALSE), "\n")
</syntaxhighlight>
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket/base
 
Line 1,470 ⟶ 3,273:
;; use the defined wrapper to solve the task
(displayln (sha256 #"Rosetta code"))
</syntaxhighlight>
</lang>
 
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Raku}}==
(formerly Perl 6)
=== Pure Raku ===
The following implementation takes all data as input. Ideally, input should be given lazily or something.
 
<syntaxhighlight lang="raku" line>say sha256 "Rosetta code";
 
our proto sha256($) returns blob8 {*}
 
multi sha256(Str $str) { samewith $str.encode }
multi sha256(blob8 $data) {
sub rotr { $^a +> $^b +| $a +< (32 - $b) }
sub init { ^Inf .grep(&is-prime).map: { (($_ - .Int)*2**32).Int } o &^f }
sub Ch { $^x +& $^y +^ +^$x +& $^z }
sub Maj { $^x +& $^y +^ $x +& $^z +^ $y +& $z }
sub Σ0 { rotr($^x, 2) +^ rotr($x, 13) +^ rotr($x, 22) }
sub Σ1 { rotr($^x, 6) +^ rotr($x, 11) +^ rotr($x, 25) }
sub σ0 { rotr($^x, 7) +^ rotr($x, 18) +^ $x +> 3 }
sub σ1 { rotr($^x, 17) +^ rotr($x, 19) +^ $x +> 10 }
 
return blob8.new:
map |*.polymod(256 xx 3).reverse,
|reduce -> $H, $block {
blob32.new: $H[] Z+
reduce -> $h, $j {
my uint32 ($T1, $T2) =
$h[7] + Σ1($h[4]) + Ch(|$h[4..6])
+ (BEGIN init(* **(1/3))[^64])[$j] +
(
(state buf32 $w .= new)[$j] = $j < 16 ?? $block[$j] !!
σ0($w[$j-15]) + $w[$j-7] + σ1($w[$j-2]) + $w[$j-16]
),
Σ0($h[0]) + Maj(|$h[0..2]);
blob32.new: $T1 + $T2, |$h[0..2], $h[3] + $T1, |$h[4..6];
}, $H, |^64;
},
(BEGIN init(&sqrt)[^8]),
|blob32.new(
blob8.new(
@$data,
0x80,
0 xx (-($data + 1 + 8) mod 64),
(8*$data).polymod(256 xx 7).reverse
).rotor(4)
.map: { :256[@$_] }
).rotor(16)
}</syntaxhighlight>
{{out}}
<pre>Blob[uint8]: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></pre>
 
=== Native implementation ===
<syntaxhighlight lang="raku" line>use Digest::SHA256::Native;
 
# If you want a string
say sha256-hex 'Rosetta code';
 
# If you want a binary Blob
say sha256 'Rosetta code';</syntaxhighlight>
{{out}}
<pre>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></pre>
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project: SHA-256
 
load "stdlib.ring"
str = "Rosetta code"
see "String: " + str + nl
see "SHA-256: "
see sha256(str) + nl
</syntaxhighlight>
Output:
<pre>
String: Rosetta code
SHA-256: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">require 'digest/sha2'
puts Digest::SHA256.hexdigest('Rosetta code')</langsyntaxhighlight>
 
=={{header|Rust}}==
<lang rust>extern crate rustc;
 
=== Library ===
use rustc::util::sha2::{Sha256, Digest};
<syntaxhighlight lang="rust">use sha2::{Digest, Sha256};
 
fn hex_string(input: &[u8]) -> String {
input.as_ref().iter().map(|b| format!("{:x}", b)).collect()
}
 
fn main() {
let mut digest = // create a Sha256::new(); object
let mut hasher = Sha256::new();
digest.input_str("Rosetta code");
 
assert!(digest.result_str() == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf".to_string());
// write input message
}</lang>
hasher.update(b"Rosetta code");
 
// read hash digest and consume hasher
let result = hasher.finalize();
 
let hex = hex_string(&result);
 
assert_eq!(
hex,
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
);
println!("{}", hex);
}
</syntaxhighlight>
 
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=== Pure Rust ===
<syntaxhighlight lang="rust">const HASH_VALUES: [u32; 8] = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
];
 
const ROUND_CONSTANTS: [u32; 64] = [
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,
];
 
const INPUT: &str = "Rosetta code";
 
fn main() {
let mut bytes = INPUT.as_bytes().to_vec();
 
let mut hash_values = HASH_VALUES.to_vec();
 
let input_len = bytes.len(); // Bytes
let input_len_byte = (input_len * 8).to_be_bytes(); // Bits
 
let padding = ((64 * ((input_len + 72) / 64)) - input_len) - 9; // Bytes
 
bytes.push(128);
bytes.append(&mut vec![0; padding]);
bytes.extend(input_len_byte);
 
for byte_chunk in bytes.chunks(64) {
let mut working_hash = hash_values.clone();
 
let mut joined_bytes: Vec<u32> = byte_chunk
.chunks(4)
.map(|chunk| u32::from_be_bytes(chunk.try_into().unwrap()))
.collect();
 
joined_bytes.append(&mut vec![0; 48]);
 
// Message loop
 
for i in 16..64 {
let chunk_index_1 = joined_bytes[i - 15];
let chunk_index_2 = joined_bytes[i - 2];
 
let sigma_1 = chunk_index_1.rotate_right(7)
^ chunk_index_1.rotate_right(18)
^ (chunk_index_1 >> 3);
let sigma_2 = chunk_index_2.rotate_right(17)
^ chunk_index_2.rotate_right(19)
^ (chunk_index_2 >> 10);
 
joined_bytes[i] = joined_bytes[i - 16]
.wrapping_add(sigma_1.wrapping_add(joined_bytes[i - 7].wrapping_add(sigma_2)));
}
 
// Compression loop
 
for i in 0..64 {
let sigma_1 = working_hash[4].rotate_right(6)
^ working_hash[4].rotate_right(11)
^ working_hash[4].rotate_right(25);
let choice =
(working_hash[4] & working_hash[5]) ^ ((!working_hash[4]) & working_hash[6]);
let temp_1 = working_hash[7].wrapping_add(sigma_1.wrapping_add(
choice.wrapping_add(ROUND_CONSTANTS[i].wrapping_add(joined_bytes[i])),
));
 
let sigma_0 = working_hash[0].rotate_right(2)
^ working_hash[0].rotate_right(13)
^ working_hash[0].rotate_right(22);
let majority = (working_hash[0] & working_hash[1])
^ (working_hash[0] & working_hash[2])
^ (working_hash[1] & working_hash[2]);
let temp_2 = sigma_0.wrapping_add(majority);
 
working_hash.pop();
working_hash.insert(0, temp_1.wrapping_add(temp_2));
working_hash[4] = working_hash[4].wrapping_add(temp_1);
}
 
hash_values = hash_values
.iter()
.zip(working_hash)
.map(|(hv1, hv2)| hv1.wrapping_add(hv2))
.collect();
}
 
let output: String = hash_values
.iter()
.map(|val| format!("{:08x}", val))
.collect::<Vec<String>>()
.join("");
 
assert_eq!(
output,
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
);
 
println!("{}", output);
}
</syntaxhighlight>
 
{{out}}
<pre>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Scala}}==
{{libheader|Scala}}<langsyntaxhighlight Scalalang="scala">object RosettaSHA256 extends App {
 
def MD5(s: String): String = {
Line 1,501 ⟶ 3,517:
assert(MD5("Rosetta code") == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")
println("Successfully completed without errors.")
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "msgdigest.s7i";
 
Line 1,510 ⟶ 3,526:
begin
writeln(hex(sha256("Rosetta code")));
end func;</langsyntaxhighlight>
 
{{out}}
Line 1,518 ⟶ 3,534:
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">var sha = frequire('Digest::SHA');
say sha.sha256_hex('Rosetta code');</langsyntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|Slope}}==
<syntaxhighlight lang="slope">(display (string->sha256 "Rosetta code"))</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
Line 1,526 ⟶ 3,547:
Use the [http://smalltalkhub.com/#!/~Cryptography/Cryptography Cryptography] library:
 
<langsyntaxhighlight lang="smalltalk">
(SHA256 new hashStream: 'Rosetta code' readStream) hex.
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require sha256
 
puts [sha2::sha256 -hex "Rosetta code"]</langsyntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</pre>
 
=={{header|TXR}}==
 
<pre>1> (sha256 "Rosetta code")
#b'764faf5c61ac315f 1497f9dfa5427139 65b785e5cc2f707d 6468d7d1124cdfcf'</pre>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">import crypto.sha256
 
fn main() {
println("${sha256.hexhash('Rosetta code')}")
 
mut h := sha256.new()
h.write('Rosetta code'.bytes()) ?
println('${h.checksum().map(it.hex()).join('')}')
}</syntaxhighlight>
{{out}}
<pre>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-crypto}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="wren">import "./crypto" for Sha256
import "./fmt" for Fmt
var strings = [
"",
"a",
"abc",
"message digest",
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
"12345678901234567890123456789012345678901234567890123456789012345678901234567890",
"The quick brown fox jumps over the lazy dog",
"The quick brown fox jumps over the lazy cog",
"Rosetta code"
]
for (s in strings) {
var hash = Sha256.digest(s)
Fmt.print("$s <== '$0s'", hash, s)
}</syntaxhighlight>
 
{{out}}
<pre>
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 <== ''
ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb <== 'a'
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad <== 'abc'
f7846f55cf23e14eebeab5b4e1550cad5b509e3348fbc4efa3a1413d393cb650 <== 'message digest'
71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73 <== 'abcdefghijklmnopqrstuvwxyz'
db4bfcbd4da0cd85a60c3c37d3fbd8805c77f15fc6b1fdfe614ee0a7c8fdb4c0 <== 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
f371bc4a311f2b009eef952dd83ca80e2b60026c8e935592d0f9c308453c813e <== '12345678901234567890123456789012345678901234567890123456789012345678901234567890'
d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 <== 'The quick brown fox jumps over the lazy dog'
e4c4d8f3bf76b692de791a173e05321150f7a345b46484fe427f6acc7ecc81be <== 'The quick brown fox jumps over the lazy cog'
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf <== 'Rosetta code'
</pre>
 
=={{header|zkl}}==
Uses shared library zklMsgHash.so
<langsyntaxhighlight lang="zkl">var MsgHash=Import("zklMsgHash");
MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"</langsyntaxhighlight>
{{out}}
<pre>True</pre>
9,486

edits