SHA-256
You are encouraged to solve this task according to the task description, using any language you may know.
SHA-256 is the recommended stronger alternative to SHA-1. See 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
AArch64 Assembly
<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 lsl x4,x2,#3 // length in bits mov x3,#0
addZeroes:
lsr x5,x2,#6 lsl x5,x5,#6 sub x5,x2,x5 cmp x5,#56 beq storeLength // yes -> end add strb w3,[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 //vidregtit avantloop //mov x0,x2 //vidmemtit verifBloc x0 10
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 */ //ldr x0,qAdrtbW //vidmemtit verifW80 x0 20 // 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
mov x0,#0 // routine OK
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"
</lang>
- Output:
pi@debian-buster-64:~/asm64/rosetta/asm5 $ sha256_64 Rosetta code => 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF Program End ok.
Ada
<lang Ada>with Ada.Text_IO;
with CryptAda.Pragmatics; with CryptAda.Digests.Message_Digests.SHA_256; with CryptAda.Digests.Hashes; with CryptAda.Utils.Format;
procedure RC_SHA_256 is
use CryptAda.Pragmatics; use CryptAda.Digests.Message_Digests; use CryptAda.Digests;
function To_Byte_Array (Item : String) return Byte_Array is Result : Byte_Array (Item'Range); begin for I in Result'Range loop Result (I) := Byte (Character'Pos (Item (I))); end loop; return Result; end To_Byte_Array;
Text : constant String := "Rosetta code"; Bytes : constant Byte_Array := To_Byte_Array (Text); Handle : constant Message_Digest_Handle := SHA_256.Get_Message_Digest_Handle; Pointer : constant Message_Digest_Ptr := Get_Message_Digest_Ptr (Handle); Hash : Hashes.Hash;
begin
Digest_Start (Pointer); Digest_Update (Pointer, Bytes); Digest_End (Pointer, Hash);
Ada.Text_IO.Put_Line ("""" & Text & """: " & CryptAda.Utils.Format.To_Hex_String (Hashes.Get_Bytes (Hash)));
end RC_SHA_256;</lang>
- Output:
"Rosetta code": 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
ARM Assembly
<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" </lang>
- Output:
Rosetta code => 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF Program End ok.
AutoHotkey
Source: SHA-256 @github by jNizM <lang AutoHotkey>str := "Rosetta code" MsgBox, % "File:`n" (file) "`n`nSHA-256:`n" FileSHA256(file)
- SHA256 ============================================================================
SHA256(string, encoding = "utf-8") {
return CalcStringHash(string, 0x800c, encoding)
}
- CalcAddrHash ======================================================================
CalcAddrHash(addr, length, algid, byref hash = 0, byref hashlength = 0) {
static h := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] static b := h.minIndex() o := "" if (DllCall("advapi32\CryptAcquireContext", "Ptr*", hProv, "Ptr", 0, "Ptr", 0, "UInt", 24, "UInt", 0xF0000000)) { if (DllCall("advapi32\CryptCreateHash", "Ptr", hProv, "UInt", algid, "UInt", 0, "UInt", 0, "Ptr*", hHash)) { if (DllCall("advapi32\CryptHashData", "Ptr", hHash, "Ptr", addr, "UInt", length, "UInt", 0)) { if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", 0, "UInt*", hashlength, "UInt", 0)) { VarSetCapacity(hash, hashlength, 0) if (DllCall("advapi32\CryptGetHashParam", "Ptr", hHash, "UInt", 2, "Ptr", &hash, "UInt*", hashlength, "UInt", 0)) { loop, % hashlength { v := NumGet(hash, A_Index - 1, "UChar") o .= h[(v >> 4) + b] h[(v & 0xf) + b] } } } } DllCall("advapi32\CryptDestroyHash", "Ptr", hHash) } DllCall("advapi32\CryPtreleaseContext", "Ptr", hProv, "UInt", 0) } return o
}
- CalcStringHash ====================================================================
CalcStringHash(string, algid, encoding = "utf-8", byref hash = 0, byref hashlength = 0) {
chrlength := (encoding = "cp1200" || encoding = "utf-16") ? 2 : 1 length := (StrPut(string, encoding) - 1) * chrlength VarSetCapacity(data, length, 0) StrPut(string, &data, floor(length / chrlength), encoding) return CalcAddrHash(&data, length, algid, hash, hashlength)
}</lang>
- Output:
String: Rosetta code SHA-256: 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
AWK
Using the system function as a 'library'. <lang AWK>{
("echo -n " $0 " | sha256sum") | getline sha; gsub(/[^0-9a-zA-Z]/, "", sha); print sha;
} </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
BaCon
<lang qbasic>PRAGMA INCLUDE <openssl/sha.h> PRAGMA LDFLAGS -lcrypto
OPTION MEMTYPE unsigned char
DECLARE result TYPE unsigned char*
result = SHA256("Rosetta code", 12, 0)
FOR i = 0 TO SHA256_DIGEST_LENGTH-1
PRINT PEEK(result+i) FORMAT "%02x"
NEXT
PRINT</lang>
- Output:
user@host $ bacon sha256 Converting 'sha256.bac'... done, 14 lines were processed in 0.002 seconds. Compiling 'sha256.bac'... cc -c sha256.bac.c cc -o sha256 sha256.bac.o -lbacon -lm -lcrypto Done, program 'sha256' ready. user@host $ ./sha256 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
BBC BASIC
Library
<lang bbcbasic> PRINT FNsha256("Rosetta code")
END DEF FNsha256(message$) LOCAL buflen%, buffer%, hcont%, hprov%, hhash%, hash$, i% CALG_SHA_256 = &800C HP_HASHVAL = 2 CRYPT_NEWKEYSET = 8 PROV_RSA_AES = 24 buflen% = 128 DIM buffer% LOCAL buflen%-1 SYS "CryptAcquireContext", ^hcont%, 0, \ \ "Microsoft Enhanced RSA and AES Cryptographic Provider", \ \ PROV_RSA_AES, CRYPT_NEWKEYSET SYS "CryptAcquireContext", ^hprov%, 0, 0, PROV_RSA_AES, 0 SYS "CryptCreateHash", hprov%, CALG_SHA_256, 0, 0, ^hhash% SYS "CryptHashData", hhash%, message$, LEN(message$), 0 SYS "CryptGetHashParam", hhash%, HP_HASHVAL, buffer%, ^buflen%, 0 SYS "CryptDestroyHash", hhash% SYS "CryptReleaseContext", hprov% SYS "CryptReleaseContext", hcont% FOR i% = 0 TO buflen%-1 hash$ += RIGHT$("0" + STR$~buffer%?i%, 2) NEXT = hash$</lang>
Output:
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
Native
<lang bbcbasic> REM SHA-256 calculation by Richard Russell in BBC BASIC for Windows
REM Must run in FLOAT64 mode: *FLOAT64 REM Test message for validation: message$ = "Rosetta code" REM Initialize variables: h0% = &6A09E667 h1% = &BB67AE85 h2% = &3C6EF372 h3% = &A54FF53A h4% = &510E527F h5% = &9B05688C h6% = &1F83D9AB h7% = &5BE0CD19 REM Create table of constants: DIM k%(63) : k%() = \ \ &428A2F98, &71374491, &B5C0FBCF, &E9B5DBA5, &3956C25B, &59F111F1, &923F82A4, &AB1C5ED5, \ \ &D807AA98, &12835B01, &243185BE, &550C7DC3, &72BE5D74, &80DEB1FE, &9BDC06A7, &C19BF174, \ \ &E49B69C1, &EFBE4786, &0FC19DC6, &240CA1CC, &2DE92C6F, &4A7484AA, &5CB0A9DC, &76F988DA, \ \ &983E5152, &A831C66D, &B00327C8, &BF597FC7, &C6E00BF3, &D5A79147, &06CA6351, &14292967, \ \ &27B70A85, &2E1B2138, &4D2C6DFC, &53380D13, &650A7354, &766A0ABB, &81C2C92E, &92722C85, \ \ &A2BFE8A1, &A81A664B, &C24B8B70, &C76C51A3, &D192E819, &D6990624, &F40E3585, &106AA070, \ \ &19A4C116, &1E376C08, &2748774C, &34B0BCB5, &391C0CB3, &4ED8AA4A, &5B9CCA4F, &682E6FF3, \ \ &748F82EE, &78A5636F, &84C87814, &8CC70208, &90BEFFFA, &A4506CEB, &BEF9A3F7, &C67178F2 Length% = LEN(message$)*8 REM Pre-processing: REM append the bit '1' to the message: message$ += CHR$&80 REM append k bits '0', where k is the minimum number >= 0 such that REM the resulting message length (in bits) is congruent to 448 (mod 512) WHILE (LEN(message$) MOD 64) <> 56 message$ += CHR$0 ENDWHILE REM append length of message (before pre-processing), in bits, as REM 64-bit big-endian integer: FOR I% = 56 TO 0 STEP -8 message$ += CHR$(Length% >>> I%) NEXT REM Process the message in successive 512-bit chunks: REM break message into 512-bit chunks, for each chunk REM break chunk into sixteen 32-bit big-endian words w[i], 0 <= i <= 15 DIM w%(63) FOR chunk% = 0 TO LEN(message$) DIV 64 - 1 FOR i% = 0 TO 15 w%(i%) = !(!^message$ + 64*chunk% + 4*i%) SWAP ?(^w%(i%)+0),?(^w%(i%)+3) SWAP ?(^w%(i%)+1),?(^w%(i%)+2) NEXT i% REM Extend the sixteen 32-bit words into sixty-four 32-bit words: FOR i% = 16 TO 63 s0% = FNrr(w%(i%-15),7) EOR FNrr(w%(i%-15),18) EOR (w%(i%-15) >>> 3) s1% = FNrr(w%(i%-2),17) EOR FNrr(w%(i%-2),19) EOR (w%(i%-2) >>> 10) w%(i%) = FN32(w%(i%-16) + s0% + w%(i%-7) + s1%) NEXT i% REM Initialize hash value for this chunk: a% = h0% b% = h1% c% = h2% d% = h3% e% = h4% f% = h5% g% = h6% h% = h7% REM Main loop: FOR i% = 0 TO 63 s0% = FNrr(a%,2) EOR FNrr(a%,13) EOR FNrr(a%,22) maj% = (a% AND b%) EOR (a% AND c%) EOR (b% AND c%) t2% = FN32(s0% + maj%) s1% = FNrr(e%,6) EOR FNrr(e%,11) EOR FNrr(e%,25) ch% = (e% AND f%) EOR ((NOT e%) AND g%) t1% = FN32(h% + s1% + ch% + k%(i%) + w%(i%)) h% = g% g% = f% f% = e% e% = FN32(d% + t1%) d% = c% c% = b% b% = a% a% = FN32(t1% + t2%) NEXT i% REM Add this chunk's hash to result so far: h0% = FN32(h0% + a%) h1% = FN32(h1% + b%) h2% = FN32(h2% + c%) h3% = FN32(h3% + d%) h4% = FN32(h4% + e%) h5% = FN32(h5% + f%) h6% = FN32(h6% + g%) h7% = FN32(h7% + h%) NEXT chunk% REM Produce the final hash value (big-endian): hash$ = FNhex(h0%) + " " + FNhex(h1%) + " " + FNhex(h2%) + " " + FNhex(h3%) + \ \ " " + FNhex(h4%) + " " + FNhex(h5%) + " " + FNhex(h6%) + " " + FNhex(h7%) PRINT hash$ END DEF FNrr(A%,I%) = (A% >>> I%) OR (A% << (32-I%)) DEF FNhex(A%) = RIGHT$("0000000"+STR$~A%,8) DEF FN32(n#) WHILE n# > &7FFFFFFF : n# -= 2^32 : ENDWHILE WHILE n# < &80000000 : n# += 2^32 : ENDWHILE = n#</lang>
Output:
764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF
C
Requires OpenSSL, compile flag: -lssl -lcrypto
<lang c>#include <stdio.h>
- include <string.h>
- include <openssl/sha.h>
int main (void) { const char *s = "Rosetta code"; unsigned char *d = SHA256(s, strlen(s), 0);
int i; for (i = 0; i < SHA256_DIGEST_LENGTH; i++) printf("%02x", d[i]); putchar('\n');
return 0; }</lang>
C#
<lang csharp>using System; using System.Security.Cryptography; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RosettaCode.SHA256 {
[TestClass] public class SHA256ManagedTest { [TestMethod] public void TestComputeHash() { var buffer = Encoding.UTF8.GetBytes("Rosetta code"); var hashAlgorithm = new SHA256Managed(); var hash = hashAlgorithm.ComputeHash(buffer); Assert.AreEqual( "76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF", BitConverter.ToString(hash)); } }
}</lang>
C++
Uses 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
<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; } </lang>
Caché ObjectScript
USER>set hash=$System.Encryption.SHAHash(256, "Rosetta code") USER>zzdump hash 0000: 76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 0010: 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF
Clojure
<lang clojure>(use 'pandect.core) (sha256 "Rosetta code")</lang>
- Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
Common Lisp
<lang lisp>(ql:quickload 'ironclad) (defun sha-256 (str)
(ironclad:byte-array-to-hex-string (ironclad:digest-sequence :sha256 (ironclad:ascii-string-to-byte-array str))))
(sha-256 "Rosetta code")</lang>
- Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
Crystal
<lang ruby>require "openssl" puts OpenSSL::Digest.new("SHA256").update("Rosetta code") </lang> Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
D
Standard Version
<lang d>void main() {
import std.stdio, std.digest.sha;
writefln("%-(%02x%)", "Rosetta code".sha256Of);
}</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Simple Implementation
<lang d>// Copyright (C) 2005, 2006 Free Software Foundation, Inc. GNU License. // Translated to D language. Only lightly tested, not for serious use.
import core.stdc.string: memcpy; import core.bitop: bswap;
struct SHA256 {
enum uint BLOCK_SIZE = 4096; static assert(BLOCK_SIZE % 64 == 0, "Invalid BLOCK_SIZE.");
uint[8] state; uint[2] total; uint bufLen; union { uint[32] buffer; ubyte[buffer.sizeof] bufferB; }
alias TResult = ubyte[256 / 8];
version(WORDS_BIGENDIAN) { static uint bswap(in uint n) pure nothrow @safe @nogc { return n; } }
// Bytes used to pad the buffer to the next 64-byte boundary. static immutable ubyte[64] fillBuf = [0x80, 0 /* , 0, 0, ... */];
/** Initialize structure containing state of computation. Takes a pointer to a 256 bit block of data (eight 32 bit ints) and intializes it to the start constants of the SHA256 algorithm. This must be called before using hash in the call to sha256_hash. */ void init() pure nothrow @safe @nogc { state = [0x6a09e667U, 0xbb67ae85U, 0x3c6ef372U, 0xa54ff53aU, 0x510e527fU, 0x9b05688cU, 0x1f83d9abU, 0x5be0cd19U]; total[] = 0; bufLen = 0; }
/** Starting with the result of former calls of this function (or the initialization function) update the context for the next LEN bytes starting at BUFFER. It is not required that LEN is a multiple of 64. */ void processBytes(in ubyte[] inBuffer) pure nothrow @nogc { // When we already have some bits in our internal // buffer concatenate both inputs first. const(ubyte)* inBufferPtr = inBuffer.ptr; auto len = inBuffer.length;
if (bufLen != 0) { immutable size_t left_over = bufLen; immutable size_t add = (128 - left_over > len) ? len : 128 - left_over;
memcpy(&bufferB[left_over], inBufferPtr, add); bufLen += add;
if (bufLen > 64) { processBlock(bufferB[0 .. bufLen & ~63]);
bufLen &= 63; // The regions in the following copy operation cannot overlap. memcpy(bufferB.ptr, &bufferB[(left_over + add) & ~63], bufLen); }
inBufferPtr += add; len -= add; }
// Process available complete blocks. if (len >= 64) { processBlock(inBufferPtr[0 .. len & ~63]); inBufferPtr += (len & ~63); len &= 63; }
// Move remaining bytes in internal buffer. if (len > 0) { size_t left_over = bufLen;
memcpy(&bufferB[left_over], inBufferPtr, len); left_over += len; if (left_over >= 64) { processBlock(bufferB[0 .. 64]); left_over -= 64; memcpy(bufferB.ptr, &bufferB[64], left_over); } bufLen = left_over; } }
/** Starting with the result of former calls of this function (or the initialization function) update the context ctx for the next len bytes starting at buffer. It is necessary that len is a multiple of 64. */ void processBlock(in ubyte[] inBuffer) pure nothrow @nogc in { assert(inBuffer.length % 64 == 0); } body { // Round functions. static uint F1(in uint e, in uint f, in uint g) pure nothrow @safe @nogc { return g ^ (e & (f ^ g)); }
static uint F2(in uint a, in uint b, in uint c) pure nothrow @safe @nogc { return (a & b) | (c & (a | b)); }
immutable len = inBuffer.length; auto words = cast(uint*)inBuffer.ptr; immutable size_t nWords = len / uint.sizeof; const uint* endp = words + nWords; uint[16] x = void; auto a = state[0]; auto b = state[1]; auto c = state[2]; auto d = state[3]; auto e = state[4]; auto f = state[5]; auto g = state[6]; auto h = state[7];
// First increment the byte count. FIPS PUB 180-2 specifies the // possible length of the file up to 2^64 bits. Here we only // compute the number of bytes. Do a double word increment. total[0] += len; if (total[0] < len) total[1]++;
static uint rol(in uint x, in uint n) pure nothrow @safe @nogc { return (x << n) | (x >> (32 - n)); } static uint S0(in uint x) pure nothrow @safe @nogc { return rol(x, 25) ^ rol(x, 14) ^ (x >> 3); } static uint S1(in uint x) pure nothrow @safe @nogc { return rol(x, 15) ^ rol(x, 13) ^ (x >> 10); } static uint SS0(in uint x) pure nothrow @safe @nogc { return rol(x, 30) ^ rol(x,19) ^ rol(x, 10); } static uint SS1(in uint x) pure nothrow @safe @nogc { return rol(x, 26) ^ rol(x, 21) ^ rol(x, 7); }
uint M(in uint I) pure nothrow @safe @nogc { immutable uint tm = S1(x[(I - 2) & 0x0f]) + x[(I - 7) & 0x0f] + S0(x[(I - 15) & 0x0f]) + x[I & 0x0f]; x[I & 0x0f] = tm; return tm; }
static void R(in uint a, in uint b, in uint c, ref uint d, in uint e, in uint f, in uint g, ref uint h, in uint k, in uint m) pure nothrow @safe @nogc { immutable t0 = SS0(a) + F2(a, b, c); immutable t1 = h + SS1(e) + F1(e, f, g) + k + m; d += t1; h = t0 + t1; }
// SHA256 round constants. static immutable uint[64] K = [ 0x428a2f98U, 0x71374491U, 0xb5c0fbcfU, 0xe9b5dba5U, 0x3956c25bU, 0x59f111f1U, 0x923f82a4U, 0xab1c5ed5U, 0xd807aa98U, 0x12835b01U, 0x243185beU, 0x550c7dc3U, 0x72be5d74U, 0x80deb1feU, 0x9bdc06a7U, 0xc19bf174U, 0xe49b69c1U, 0xefbe4786U, 0x0fc19dc6U, 0x240ca1ccU, 0x2de92c6fU, 0x4a7484aaU, 0x5cb0a9dcU, 0x76f988daU, 0x983e5152U, 0xa831c66dU, 0xb00327c8U, 0xbf597fc7U, 0xc6e00bf3U, 0xd5a79147U, 0x06ca6351U, 0x14292967U, 0x27b70a85U, 0x2e1b2138U, 0x4d2c6dfcU, 0x53380d13U, 0x650a7354U, 0x766a0abbU, 0x81c2c92eU, 0x92722c85U, 0xa2bfe8a1U, 0xa81a664bU, 0xc24b8b70U, 0xc76c51a3U, 0xd192e819U, 0xd6990624U, 0xf40e3585U, 0x106aa070U, 0x19a4c116U, 0x1e376c08U, 0x2748774cU, 0x34b0bcb5U, 0x391c0cb3U, 0x4ed8aa4aU, 0x5b9cca4fU, 0x682e6ff3U, 0x748f82eeU, 0x78a5636fU, 0x84c87814U, 0x8cc70208U, 0x90befffaU, 0xa4506cebU, 0xbef9a3f7U, 0xc67178f2U];
while (words < endp) { foreach (ref xi; x) { xi = bswap(*words); words++; }
R(a, b, c, d, e, f, g, h, K[ 0], x[ 0]); R(h, a, b, c, d, e, f, g, K[ 1], x[ 1]); R(g, h, a, b, c, d, e, f, K[ 2], x[ 2]); R(f, g, h, a, b, c, d, e, K[ 3], x[ 3]); R(e, f, g, h, a, b, c, d, K[ 4], x[ 4]); R(d, e, f, g, h, a, b, c, K[ 5], x[ 5]); R(c, d, e, f, g, h, a, b, K[ 6], x[ 6]); R(b, c, d, e, f, g, h, a, K[ 7], x[ 7]); R(a, b, c, d, e, f, g, h, K[ 8], x[ 8]); R(h, a, b, c, d, e, f, g, K[ 9], x[ 9]); R(g, h, a, b, c, d, e, f, K[10], x[10]); R(f, g, h, a, b, c, d, e, K[11], x[11]); R(e, f, g, h, a, b, c, d, K[12], x[12]); R(d, e, f, g, h, a, b, c, K[13], x[13]); R(c, d, e, f, g, h, a, b, K[14], x[14]); R(b, c, d, e, f, g, h, a, K[15], x[15]); R(a, b, c, d, e, f, g, h, K[16], M(16)); R(h, a, b, c, d, e, f, g, K[17], M(17)); R(g, h, a, b, c, d, e, f, K[18], M(18)); R(f, g, h, a, b, c, d, e, K[19], M(19)); R(e, f, g, h, a, b, c, d, K[20], M(20)); R(d, e, f, g, h, a, b, c, K[21], M(21)); R(c, d, e, f, g, h, a, b, K[22], M(22)); R(b, c, d, e, f, g, h, a, K[23], M(23)); R(a, b, c, d, e, f, g, h, K[24], M(24)); R(h, a, b, c, d, e, f, g, K[25], M(25)); R(g, h, a, b, c, d, e, f, K[26], M(26)); R(f, g, h, a, b, c, d, e, K[27], M(27)); R(e, f, g, h, a, b, c, d, K[28], M(28)); R(d, e, f, g, h, a, b, c, K[29], M(29)); R(c, d, e, f, g, h, a, b, K[30], M(30)); R(b, c, d, e, f, g, h, a, K[31], M(31)); R(a, b, c, d, e, f, g, h, K[32], M(32)); R(h, a, b, c, d, e, f, g, K[33], M(33)); R(g, h, a, b, c, d, e, f, K[34], M(34)); R(f, g, h, a, b, c, d, e, K[35], M(35)); R(e, f, g, h, a, b, c, d, K[36], M(36)); R(d, e, f, g, h, a, b, c, K[37], M(37)); R(c, d, e, f, g, h, a, b, K[38], M(38)); R(b, c, d, e, f, g, h, a, K[39], M(39)); R(a, b, c, d, e, f, g, h, K[40], M(40)); R(h, a, b, c, d, e, f, g, K[41], M(41)); R(g, h, a, b, c, d, e, f, K[42], M(42)); R(f, g, h, a, b, c, d, e, K[43], M(43)); R(e, f, g, h, a, b, c, d, K[44], M(44)); R(d, e, f, g, h, a, b, c, K[45], M(45)); R(c, d, e, f, g, h, a, b, K[46], M(46)); R(b, c, d, e, f, g, h, a, K[47], M(47)); R(a, b, c, d, e, f, g, h, K[48], M(48)); R(h, a, b, c, d, e, f, g, K[49], M(49)); R(g, h, a, b, c, d, e, f, K[50], M(50)); R(f, g, h, a, b, c, d, e, K[51], M(51)); R(e, f, g, h, a, b, c, d, K[52], M(52)); R(d, e, f, g, h, a, b, c, K[53], M(53)); R(c, d, e, f, g, h, a, b, K[54], M(54)); R(b, c, d, e, f, g, h, a, K[55], M(55)); R(a, b, c, d, e, f, g, h, K[56], M(56)); R(h, a, b, c, d, e, f, g, K[57], M(57)); R(g, h, a, b, c, d, e, f, K[58], M(58)); R(f, g, h, a, b, c, d, e, K[59], M(59)); R(e, f, g, h, a, b, c, d, K[60], M(60)); R(d, e, f, g, h, a, b, c, K[61], M(61)); R(c, d, e, f, g, h, a, b, K[62], M(62)); R(b, c, d, e, f, g, h, a, K[63], M(63));
a = state[0] += a; b = state[1] += b; c = state[2] += c; d = state[3] += d; e = state[4] += e; f = state[5] += f; g = state[6] += g; h = state[7] += h; } }
/** Process the remaining bytes in the internal buffer and the usual prolog according to the standard and write the result to resBuf. Important: On some systems it is required that resBuf is correctly aligned for a 32-bit value. */ void conclude() pure nothrow @nogc { // Take yet unprocessed bytes into account. immutable bytes = bufLen; immutable size_t size = (bytes < 56) ? 64 / 4 : 64 * 2 / 4;
// Now count remaining bytes. total[0] += bytes; if (total[0] < bytes) total[1]++;
// Put the 64-bit file length in *bits* at the end of // the buffer. buffer[size - 2] = bswap((total[1] << 3) | (total[0] >> 29)); buffer[size - 1] = bswap(total[0] << 3);
memcpy(&bufferB[bytes], fillBuf.ptr, (size - 2) * 4 - bytes);
// Process last bytes. processBlock(bufferB[0 .. size * 4]); }
/** Put result from this in first 32 bytes following resBuf. The result must be in little endian byte order. Important: On some systems it is required that resBuf is correctly aligned for a 32-bit value. */ ref TResult read(return ref TResult resBuf) pure nothrow @nogc { foreach (immutable i, immutable s; state) (cast(uint*)resBuf.ptr)[i] = bswap(s); return resBuf; }
/** Process the remaining bytes in the buffer and put result from CTX in first 32 (28) bytes following resBuf. The result is always in little endian byte order, so that a byte-wise output yields to the wanted ASCII representation of the message digest. Important: On some systems it is required that resBuf be correctly aligned for a 32 bits value. */ ref TResult finish(return ref TResult resBuf) pure nothrow @nogc { conclude; return read(resBuf); }
/** Compute SHA512 message digest for LEN bytes beginning at buffer. The result is always in little endian byte order, so that a byte-wise output yields to the wanted ASCII representation of the message digest. */ static ref TResult digest(in ubyte[] inBuffer, return ref TResult resBuf) pure nothrow @nogc { SHA256 sha = void;
// Initialize the computation context. sha.init;
// Process whole buffer but last len % 64 bytes. sha.processBytes(inBuffer);
// Put result in desired memory area. return sha.finish(resBuf); }
/// ditto static TResult digest(in ubyte[] inBuffer) pure nothrow @nogc { align(4) TResult resBuf = void; return digest(inBuffer, resBuf); }
}
version (sha_256_main) {
void main() { import std.stdio, std.string;
immutable data = "Rosetta code".representation; writefln("%(%02x%)", SHA256.digest(data)); }
}</lang> Compile with -version=sha_256_main to run the main function.
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
This is a moderately efficient implementation, about 100 MB/s on a 4096 bytes input buffer on a 32 bit system, using the ldc2 compiler. On a more modern CPU (Intel Ivy Bridge) using HyperThreading, handwritten assembly by Intel is about twice faster.
Delphi
Part of DCPcrypt Cryptographic Component Library v2.1[1] by David Barton.
<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.
</lang>
- Output:
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
DWScript
<lang delphi>PrintLn( HashSHA256.HashData('Rosetta code') );</lang>
Emacs Lisp
<lang Lisp>(secure-hash 'sha256 "Rosetta code") ;; as string of hex digits</lang>
Erlang
More code to get the correct display format than doing the calculation.
- Output:
10> Binary = crypto:hash( sha256, "Rosetta code" ). 11> lists:append( [erlang:integer_to_list(X, 16) || <<X:8/integer>> <= Binary] ). "764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF"
F#
<lang fsharp>open System.Security.Cryptography open System.Text
"Rosetta code" |> Encoding.ASCII.GetBytes |> (new SHA256Managed()).ComputeHash |> System.BitConverter.ToString |> printfn "%s" </lang>
- Output:
76-4F-AF-5C-61-AC-31-5F-14-97-F9-DF-A5-42-71-39-65-B7-85-E5-CC-2F-70-7D-64-68-D7-D1-12-4C-DF-CF
Factor
<lang factor>USING: checksums checksums.sha io math.parser ;
"Rosetta code" sha-256 checksum-bytes bytes>hex-string print</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Fortran
Intel Fortran on Windows
Using Windows API. See CryptAcquireContext, CryptCreateHash, CryptHashData and CryptGetHashParam on MSDN.
With the file rc.txt containing the string "Rosetta Code":
sha256 rc.txt 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF rc.txt (12 bytes)
<lang fortran>module sha256_mod
use kernel32 use advapi32 implicit none integer, parameter :: SHA256LEN = 32
contains
subroutine sha256hash(name, hash, dwStatus, filesize) implicit none character(*) :: name integer, parameter :: BUFLEN = 32768 integer(HANDLE) :: hFile, hProv, hHash integer(DWORD) :: dwStatus, nRead integer(BOOL) :: status integer(BYTE) :: buffer(BUFLEN) integer(BYTE) :: hash(SHA256LEN) integer(UINT64) :: filesize dwStatus = 0 filesize = 0 hFile = CreateFile(trim(name) // char(0), GENERIC_READ, FILE_SHARE_READ, NULL, & OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL) if (hFile == INVALID_HANDLE_VALUE) then dwStatus = GetLastError() print *, "CreateFile failed." return end if if (CryptAcquireContext(hProv, NULL, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, & CRYPT_VERIFYCONTEXT) == FALSE) then dwStatus = GetLastError() print *, "CryptAcquireContext failed.", dwStatus goto 3 end if if (CryptCreateHash(hProv, CALG_SHA_256, 0_ULONG_PTR, 0_DWORD, hHash) == FALSE) then dwStatus = GetLastError() print *, "CryptCreateHash failed." go to 2 end if do status = ReadFile(hFile, loc(buffer), BUFLEN, nRead, NULL) if (status == FALSE .or. nRead == 0) exit filesize = filesize + nRead if (CryptHashData(hHash, buffer, nRead, 0) == FALSE) then dwStatus = GetLastError() print *, "CryptHashData failed." go to 1 end if end do if (status == FALSE) then dwStatus = GetLastError() print *, "ReadFile failed." go to 1 end if nRead = SHA256LEN if (CryptGetHashParam(hHash, HP_HASHVAL, hash, nRead, 0) == FALSE) then dwStatus = GetLastError() print *, "CryptGetHashParam failed." end if 1 status = CryptDestroyHash(hHash) 2 status = CryptReleaseContext(hProv, 0) 3 status = CloseHandle(hFile) end subroutine
end module
program sha256
use sha256_mod implicit none integer :: n, m, i, j character(:), allocatable :: name integer(DWORD) :: dwStatus integer(BYTE) :: hash(SHA256LEN) integer(UINT64) :: filesize n = command_argument_count() do i = 1, n call get_command_argument(i, length=m) allocate(character(m) :: name) call get_command_argument(i, name) call sha256hash(name, hash, dwStatus, filesize) if (dwStatus == 0) then do j = 1, SHA256LEN write(*, "(Z2.2)", advance="NO") hash(j) end do write(*, "(' ',A,' (',G0,' bytes)')") name, filesize end if deallocate(name) end do
end program</lang>
Free Pascal
<lang pascal>program rosettaCodeSHA256;
uses
SysUtils, DCPsha256;
var
ros: String; sha256 : TDCP_sha256; digest : array[0..63] of byte; i: Integer; output: String;
begin
ros := 'Rosetta code';
sha256 := TDCP_sha256.Create(nil); sha256.init; sha256.UpdateStr(ros); sha256.Final(digest);
output := ;
for i := 0 to 31 do begin output := output + intToHex(digest[i], 2); end;
writeln(lowerCase(output));
end.</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
FreeBASIC
<lang freebasic>' version 20-10-2016 ' FIPS PUB 180-4 ' compile with: fbc -s console
Function SHA_256(test_str As String) As String
#Macro Ch (x, y, z) (((x) And (y)) Xor ((Not (x)) And z)) #EndMacro
#Macro Maj (x, y, z) (((x) And (y)) Xor ((x) And (z)) Xor ((y) And (z))) #EndMacro
#Macro sigma0 (x) (((x) Shr 2 Or (x) Shl 30) Xor ((x) Shr 13 Or (x) Shl 19) Xor ((x) Shr 22 Or (x) Shl 10)) #EndMacro
#Macro sigma1 (x) (((x) Shr 6 Or (x) Shl 26) Xor ((x) Shr 11 Or (x) Shl 21) Xor ((x) Shr 25 Or (x) Shl 7)) #EndMacro
#Macro sigma2 (x) (((x) Shr 7 Or (x) Shl 25) Xor ((x) Shr 18 Or (x) Shl 14) Xor ((x) Shr 3)) #EndMacro
#Macro sigma3 (x) (((x) Shr 17 Or (x) Shl 15) Xor ((x) Shr 19 Or (x) Shl 13) Xor ((x) Shr 10)) #EndMacro
Dim As String message = test_str ' strings are passed as ByRef's
Dim As Long i, j Dim As UByte Ptr ww1 Dim As UInteger<32> Ptr ww4
Dim As ULongInt l = Len(message) ' set the first bit after the message to 1 message = message + Chr(1 Shl 7) ' add one char to the length Dim As ULong padding = 64 - ((l +1) Mod (512 \ 8)) ' 512 \ 8 = 64 char.
' check if we have enough room for inserting the length If padding < 8 Then padding = padding + 64
message = message + String(padding, Chr(0)) ' adjust length Dim As ULong l1 = Len(message) ' new length
l = l * 8 ' orignal length in bits ' create ubyte ptr to point to l ( = length in bits) Dim As UByte Ptr ub_ptr = Cast(UByte Ptr, @l)
For i = 0 To 7 'copy length of message to the last 8 bytes message[l1 -1 - i] = ub_ptr[i] Next
'table of constants Dim As UInteger<32> K(0 To ...) = _ { &H428a2f98, &H71374491, &Hb5c0fbcf, &He9b5dba5, &H3956c25b, &H59f111f1, _ &H923f82a4, &Hab1c5ed5, &Hd807aa98, &H12835b01, &H243185be, &H550c7dc3, _ &H72be5d74, &H80deb1fe, &H9bdc06a7, &Hc19bf174, &He49b69c1, &Hefbe4786, _ &H0fc19dc6, &H240ca1cc, &H2de92c6f, &H4a7484aa, &H5cb0a9dc, &H76f988da, _ &H983e5152, &Ha831c66d, &Hb00327c8, &Hbf597fc7, &Hc6e00bf3, &Hd5a79147, _ &H06ca6351, &H14292967, &H27b70a85, &H2e1b2138, &H4d2c6dfc, &H53380d13, _ &H650a7354, &H766a0abb, &H81c2c92e, &H92722c85, &Ha2bfe8a1, &Ha81a664b, _ &Hc24b8b70, &Hc76c51a3, &Hd192e819, &Hd6990624, &Hf40e3585, &H106aa070, _ &H19a4c116, &H1e376c08, &H2748774c, &H34b0bcb5, &H391c0cb3, &H4ed8aa4a, _ &H5b9cca4f, &H682e6ff3, &H748f82ee, &H78a5636f, &H84c87814, &H8cc70208, _ &H90befffa, &Ha4506ceb, &Hbef9a3f7, &Hc67178f2 }
Dim As UInteger<32> h0 = &H6a09e667 Dim As UInteger<32> h1 = &Hbb67ae85 Dim As UInteger<32> h2 = &H3c6ef372 Dim As UInteger<32> h3 = &Ha54ff53a Dim As UInteger<32> h4 = &H510e527f Dim As UInteger<32> h5 = &H9b05688c Dim As UInteger<32> h6 = &H1f83d9ab Dim As UInteger<32> h7 = &H5be0cd19 Dim As UInteger<32> a, b, c, d, e, f, g, h Dim As UInteger<32> t1, t2, w(0 To 63)
For j = 0 To (l1 -1) \ 64 ' split into block of 64 bytes ww1 = Cast(UByte Ptr, @message[j * 64]) ww4 = Cast(UInteger<32> Ptr, @message[j * 64])
For i = 0 To 60 Step 4 'little endian -> big endian Swap ww1[i ], ww1[i +3] Swap ww1[i +1], ww1[i +2] Next
For i = 0 To 15 ' copy the 16 32bit block into the array W(i) = ww4[i] Next
For i = 16 To 63 ' fill the rest of the array w(i) = sigma3(W(i -2)) + W(i -7) + sigma2(W(i -15)) + W(i -16) Next
a = h0 : b = h1 : c = h2 : d = h3 : e = h4 : f = h5 : g = h6 : h = h7
For i = 0 To 63 t1 = h + sigma1(e) + Ch(e, f, g) + K(i) + W(i) t2 = sigma0(a) + Maj(a, b, c) h = g : g = f : f = e e = d + t1 d = c : c = b : b = a a = t1 + t2 Next
h0 += a : h1 += b : h2 += c : h3 += d h4 += e : h5 += f : h6 += g : h7 += h
Next j
Dim As String answer = Hex(h0, 8) + Hex(h1, 8) + Hex(h2, 8) + Hex(h3, 8) answer += Hex(h4, 8) + Hex(h5, 8) + Hex(h6, 8) + Hex(h7, 8)
Return LCase(answer)
End Function
' ------=< MAIN >=------
Dim As String test = "Rosetta code" Print test; " => "; SHA_256(test)
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</lang>
- Output:
Rosetta code => 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Frink
Frink has convenience methods to use any message hashing algorithm provided by your Java Virtual Machine. The result can be returned as a hexadecimal string, an integer, or an array of bytes. <lang frink>println[messageDigest["Rosetta code", "SHA-256"]]</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
FunL
A SHA-256 function can be defined using the Java support library.
<lang funl>native java.security.MessageDigest
def sha256Java( message ) = map( a -> format('%02x', a), list(MessageDigest.getInstance('SHA-256').digest(message.getBytes('UTF-8'))) ).mkString()</lang>
Here is a definition implemented as a direct translation of the pseudocode at SHA-256.
<lang funl>def sha256( message ) =
//Initialize hash values h0 = 0x6a09e667 h1 = 0xbb67ae85 h2 = 0x3c6ef372 h3 = 0xa54ff53a h4 = 0x510e527f h5 = 0x9b05688c h6 = 0x1f83d9ab h7 = 0x5be0cd19
// Initialize array of round constants k(0..63) = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]
// Pre-processing bits = BitArray( message.getBytes('UTF-8') ) len = bits.length() bits.append( 1 ) r = bits.length()%512 bits.appendAll( 0 | _ <- 1..(if r > 448 then 512 - r + 448 else 448 - r) ) bits.appendInt( 0 ) bits.appendInt( len )
words = bits.toIntVector()
// Process the message in successive 512-bit chunks for chunk <- 0:words.length():16 w(0..15) = words(chunk..chunk+15)
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array for i <- 16..63 s0 = (w(i-15) rotateright 7) xor (w(i-15) rotateright 18) xor (w(i-15) >>> 3) s1 = (w(i-2) rotateright 17) xor (w(i-2) rotateright 19) xor (w(i-2) >>> 10) w(i) = w(i-16) + s0 + w(i-7) + s1
// Initialize working variables to current hash value a = h0 b = h1 c = h2 d = h3 e = h4 f = h5 g = h6 h = h7
// Compression function main loop for i <- 0..63 S1 = (e rotateright 6) xor (e rotateright 11) xor (e rotateright 25) ch = (e and f) xor ((not e) and g) temp1 = h + S1 + ch + k(i) + w(i) S0 = (a rotateright 2) xor (a rotateright 13) xor (a rotateright 22) maj = (a and b) xor (a and c) xor (b and c) temp2 = S0 + maj
h = g g = f f = e e = d + temp1 d = c c = b b = a a = temp1 + temp2
// Add the compressed chunk to the current hash value h0 = h0 + a h1 = h1 + b h2 = h2 + c h3 = h3 + d h4 = h4 + e h5 = h5 + f h6 = h6 + g h7 = h7 + h
// Produce the final hash value (big-endian) map( a -> format('%08x', a.intValue()), [h0, h1, h2, h3, h4, h5, h6, h7] ).mkString()</lang>
Here is a test comparing the two and also verifying the hash values of the empty message string.
<lang funl>message = 'Rosetta code'
println( 'FunL: "' + message + '" ~> ' + sha256(message) ) println( 'Java: "' + message + '" ~> ' + sha256Java(message) )
message =
println( 'FunL: "' + message + '" ~> ' + sha256(message) ) println( 'Java: "' + message + '" ~> ' + sha256Java(message) )</lang>
- Output:
FunL: "Rosetta code" ~> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf Java: "Rosetta code" ~> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf FunL: "" ~> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 Java: "" ~> e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
Genie
<lang genie>[indent=4] /*
SHA-256 in Genie
valac SHA-256.gs ./SHA-256
- /
init
var msg = "Rosetta code" var digest = Checksum.compute_for_string(ChecksumType.SHA256, msg, -1) print msg print digest
assert(digest == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")</lang>
- Output:
prompt$ valac SHA-256.gs prompt$ ./SHA-256 Rosetta code 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Go
<lang go>package main
import (
"crypto/sha256" "fmt" "log"
)
func main() {
h := sha256.New() if _, err := h.Write([]byte("Rosetta code")); err != nil { log.Fatal(err) } fmt.Printf("%x\n", h.Sum(nil))
}</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Groovy
<lang groovy>def sha256Hash = { text ->
java.security.MessageDigest.getInstance("SHA-256").digest(text.bytes) .collect { String.format("%02x", it) }.join()
}</lang> Testing <lang groovy>assert sha256Hash('Rosetta code') == '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf'</lang>
Halon
<lang halon>$var = "Rosetta code"; echo sha2($var, 256);</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Haskell
<lang haskell>import Data.Char (ord) import Crypto.Hash.SHA256 (hash) import Data.ByteString (unpack, pack) import Text.Printf (printf)
main = putStrLn $ -- output to terminal
concatMap (printf "%02x") $ -- to hex string unpack $ -- to array of Word8 hash $ -- SHA-256 hash to ByteString pack $ -- to ByteString map (fromIntegral.ord) -- to array of Word8 "Rosetta code"
</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Haxe
<lang haxe>import haxe.crypto.Sha256;
class Main {
static function main() { var sha256 = Sha256.encode("Rosetta code"); Sys.println(sha256); }
}</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
J
Solution: From J8 the ide/qt addon provides bindings to Qt libraries that include support for various hashing algorithms including SHA-256. <lang j>require '~addons/ide/qt/qt.ijs' getsha256=: 'sha256'&gethash_jqtide_</lang> Example Usage: <lang j> getsha256 'Rosetta code' 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</lang>
Note that the older version Qt4 libraries currently shipped by default on many Linux distributions don't support SHA-256. On Windows and Mac, J8 includes the later Qt5 libraries that include support for SHA-256.
Starting in J8.06, the sha family of hashes have built-in support.
<lang j>sha256=: 3&(128!:6)</lang>
<lang j> sha256 'Rosetta code' 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</lang>
Java
The solution to this task would be a small modification to MD5 (replacing "MD5" with "SHA-256" as noted here).
JavaScript
<lang javascript> const crypto = require('crypto');
const msg = 'Rosetta code'; const hash = crypto.createHash('sha256').update(msg).digest('hex');
console.log(hash); </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Jsish
<lang javascript>/* SHA-256 hash in Jsish */ var str = 'Rosetta code'; puts(Util.hash(str, {type:'sha256'}));
/*
!EXPECTSTART!
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
!EXPECTEND!
- /</lang>
- Output:
prompt$ jsish sha-256.jsi 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf prompt$ jsish -u sha-256.jsi [PASS] sha-256.jsi
Julia
<lang julia>msg = "Rosetta code"
using Nettle digest = hexdigest("sha256", msg)
- native
using SHA digest1 = join(num2hex.(sha256(msg)))
@assert digest == digest1</lang>
Kotlin
<lang scala>// version 1.0.6
import java.security.MessageDigest
fun main(args: Array<String>) {
val text = "Rosetta code" val bytes = text.toByteArray() val md = MessageDigest.getInstance("SHA-256") val digest = md.digest(bytes) for (byte in digest) print("%02x".format(byte)) println()
}</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Lasso
Lasso supports the ciphers as supplied by the operating system.
SHA-256 is not supplied by all operating systems by default.
Use the cipher_list method to view these algorithms.
<lang Lasso>// The following will return a list of all the cipher // algorithms supported by the installation of Lasso cipher_list
// With a -digest parameter the method will limit the returned list // to all of the digest algorithms supported by the installation of Lasso cipher_list(-digest)
// return the SHA-256 digest. Dependant on SHA-256 being an available digest method cipher_digest('Rosetta Code', -digest='SHA-256',-hex=true) </lang>
Lua
<lang Lua>#!/usr/bin/lua
require "sha2"
print(sha2.sha256hex("Rosetta code"))</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Mathematica
<lang>Hash["Rosetta code","SHA256","HexString"]</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
min
<lang min>"Rosetta code" sha256 puts!</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
NetRexx
This solution is basically the same as that for MD5, substituting "SHA-256" for "MD5" as the algorithm to use in the MessageDigest instance. <lang NetRexx>/* NetRexx */ options replace format comments java crossref savelog symbols binary
import java.security.MessageDigest
SHA256('Rosetta code', '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf')
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method SHA256(messageText, verifyCheck) public static
algorithm = 'SHA-256' digestSum = getDigest(messageText, algorithm)
say '<Message>'messageText'</Message>' say Rexx('<'algorithm'>').right(12) || digestSum'</'algorithm'>' say Rexx('<Verify>').right(12) || verifyCheck'</Verify>' if digestSum == verifyCheck then say algorithm 'Confirmed' else say algorithm 'Failed'
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method getDigest(messageText = Rexx, algorithm = Rexx 'MD5', encoding = Rexx 'UTF-8', lowercase = boolean 1) public static returns Rexx
algorithm = algorithm.upper encoding = encoding.upper
message = String(messageText) messageBytes = byte[] digestBytes = byte[] digestSum = Rexx
do messageBytes = message.getBytes(encoding) md = MessageDigest.getInstance(algorithm) md.update(messageBytes) digestBytes = md.digest
loop b_ = 0 to digestBytes.length - 1 bb = Rexx(digestBytes[b_]).d2x(2) if lowercase then digestSum = digestSum || bb.lower else digestSum = digestSum || bb.upper end b_ catch ex = Exception ex.printStackTrace end return digestSum
</lang> Output:
<Message>Rosetta code</Message> <SHA-256>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</SHA-256> <Verify>764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf</Verify> SHA-256 Confirmed
NewLISP
<lang NewLISP>;; using the crypto module from http://www.newlisp.org/code/modules/crypto.lsp.html
- (import native functions from the crypto library, provided by OpenSSL)
(module "crypto.lsp") (crypto:sha256 "Rosetta Code")</lang>
Nim
Using the third party library nimcrypto
, the program is very simple:
<lang Nim>import nimcrypto
echo sha256.digest("Rosetta code")</lang>
- Output:
764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF
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:
<lang nim>import strutils
const SHA256Len = 32
proc SHA256(d: cstring, n: culong, md: cstring = nil): cstring {.cdecl, dynlib: "libssl.so", importc.}
proc SHA256(s: string): string =
result = "" let s = SHA256(s.cstring, s.len.culong) for i in 0 ..< SHA256Len: result.add s[i].BiggestInt.toHex(2).toLower
echo SHA256("Rosetta code")</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Oberon-2
<lang oberon2> MODULE SHA256; IMPORT
Crypto:SHA256, Crypto:Utils, Strings, Out;
VAR
h: SHA256.Hash; str: ARRAY 128 OF CHAR;
BEGIN
h := SHA256.NewHash(); h.Initialize; str := "Rosetta code"; h.Update(str,0,Strings.Length(str)); h.GetHash(str,0); Out.String("SHA256: ");Utils.PrintHex(str,0,h.size);Out.Ln
END SHA256. </lang>
- Output:
SHA256: 764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF
Objeck
<lang Objeck> class ShaHash {
function : Main(args : String[]) ~ Nil { hash:= Encryption.Hash->SHA256("Rosetta code"->ToByteArray()); str := hash->ToHexString()->ToLower(); str->PrintLine(); str->Equals("764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf")->PrintLine(); }
} </lang>
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf true
Objective-C
Build with something like
clang -o rosetta_sha256 rosetta_sha256.m /System/Library/Frameworks/Cocoa.framework/Cocoa
or in XCode. <lang objc>#import <Cocoa/Cocoa.h>
- import <CommonCrypto/CommonDigest.h>
int main(int argc, char ** argv) {
NSString * msg = @"Rosetta code"; unsigned char buf[CC_SHA256_DIGEST_LENGTH]; const char * rc = [msg cStringUsingEncoding:NSASCIIStringEncoding]; if (! CC_SHA256(rc, strlen(rc), buf)) { NSLog(@"Failure..."); return -1; } NSMutableString * res = [NSMutableString stringWithCapacity:(CC_SHA256_DIGEST_LENGTH * 2)]; for (int i = 0; i < CC_SHA256_DIGEST_LENGTH; ++i) { [res appendFormat:@"%02x", buf[i]]; } NSLog(@"Output: %@", res); return 0;
} </lang>
OCaml
<lang ocaml>let () =
let s = "Rosetta code" in let digest = Sha256.string s in print_endline (Sha256.to_hex digest)</lang>
Running this script in interpreted mode:
$ ocaml -I +sha sha256.cma sha.ml 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
OS X sha256sum
Apple OS X command line with echo and sha256sum.
<lang sha256sum>echo -n 'Rosetta code' | sha256sum</lang>
Using the -n flag for echo is required as echo normally outputs a newline.
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf -
PARI/GP
It works on Linux systems.
<lang parigp>sha256(s)=extern("echo \"Str(`echo -n '"Str(s)"'|sha256sum|cut -d' ' -f1`)\"")</lang>
The code above creates a new function sha256(s) which returns SHA-256 hash of item s.
- Output:
sha256("Rosetta code") = "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
Perl
The preferred way to do a task like this is to use an already written module, for example: <lang Perl>#!/usr/bin/perl use strict ; use warnings ; use Digest::SHA qw( sha256_hex ) ;
my $digest = sha256_hex my $phrase = "Rosetta code" ; print "SHA-256('$phrase'): $digest\n" ; </lang>
- Output:
SHA-256('Rosetta code'): 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
On the other hand, one of perl's mottos is There Is More Than One Way To Do It, so of course you could write your own implementation if you wanted to. <lang Perl> package Digest::SHA256::PP;
use strict; use warnings;
use constant WORD => 2**32; use constant MASK => WORD - 1;
my @h; my @k;
for my $p ( 2 .. 311 ) { # Horrible primality test, but sufficient for this task. next if ("1" x $p) =~ /^(11+?)\1+$/; # The choice to generate h and k instead of hard coding # them is inspired by the Raku implementation. my $c = $p ** ( 1/3 ); push @k, int( ($c - int $c) * WORD ); next if @h == 8; my $s = $p ** ( 1/2 ); push @h, int( ($s - int $s) * WORD ); }
sub new { my %self = ( state => [@h], str => "", len => 0 ); bless \%self, shift; }
my $rightrotate = sub { my $lo = $_[0] >> $_[1]; my $hi = $_[0] << (32 - $_[1]); ($hi | $lo); };
- This is adapted from the wikipedia entry on SHA2.
my $compress = sub { my ($state, $bytes) = @_; my @w = unpack 'N*', $bytes; @w == 16 or die 'internal error'; my ($a, $b, $c, $d, $e, $f, $g, $h) = @$state; until( @w == 64 ) { my $s0 = $w[-15] >> 3; my $s1 = $w[-2] >> 10; $s0 ^= $rightrotate->($w[-15], $_) for 7, 18; $s1 ^= $rightrotate->($w[-2], $_) for 17, 19; push @w, ($w[-16] + $s0 + $w[-7] + $s1) & MASK; } my $i = 0; for my $w (@w) { my $ch = ($e & $f) ^ ((~$e) & $g); my $maj = ($a & $b) ^ ($a & $c) ^ ($b & $c); my ($S0, $S1) = (0, 0); $S1 ^= $rightrotate->( $e, $_ ) for 6, 11, 25; $S0 ^= $rightrotate->( $a, $_ ) for 2, 13, 22; my $temp1 = $h + $S1 + $ch + $k[$i++] + $w; my $temp2 = $S0 + $maj; ($h, $g, $f, $e, $d, $c, $b, $a) = ($g, $f, $e, ($d+$temp1)&MASK, $c, $b, $a, ($temp1+$temp2)&MASK); } my $j = 0; $state->[$j++] += $_ for $a, $b, $c, $d, $e, $f, $g, $h; };
use constant can_Q => eval { length pack 'Q>', 0 };
sub add { my ($self, $bytes) = @_; $self->{len} += 8 * length $bytes; if( !can_Q and $self->{len} >= WORD ) { my $hi = int( $self->{len} / WORD ); $self->{big} += $hi; $self->{len} -= $hi * WORD; } my $len = length $self->{str}; if( ($len + length $bytes) < 64 ) { $self->{str} .= $bytes; return $self; } my $off = 64 - $len; $compress->( $self->{state}, $self->{str} . substr( $bytes, 0, $off ) ); $len = length $_[0]; while( $off+64 <= $len ) { $compress->( $self->{state}, substr( $bytes, $off, 64 ) ); $off += 64; } $self->{str} = substr( $bytes, $off ); $self; }
sub addfile { my ($self, $fh) = @_; my $s = ""; while( read( $fh, $s, 2**13 ) ) { $self->add( $s ); } $self; }
sub digest {
my $self = shift;
my $final = $self->{str};
$final .= chr 0x80;
while( ( 8+length $final ) % 64 ) {
$final .= chr 0;
}
if( can_Q ) {
$final .= pack 'Q>', $self->{len};
} else {
$self->{big} ||= 0;
$final .= pack 'NN', $self->{big}, $self->{len};
}
$compress->( $self->{state}, substr $final, 0, 64, "" ) while length $final;
if( wantarray ) {
map pack('N', $_), @{ $self->{state} };
} else {
pack 'N*', @{ $self->{state} };
}
}
sub hexdigest { if( wantarray ) { map unpack( 'H*', $_), &digest; } else { unpack 'H*', &digest; } }
unless( caller ) { my @testwith = (@ARGV ? @ARGV : 'Rosetta code'); for my $str (@testwith) { my $digester = __PACKAGE__->new; $digester->add($str); print "'$str':\n"; print join(" ", $digester->hexdigest), "\n"; } }
1; </lang>
- Output:
'Rosetta code': 764faf5c 61ac315f 1497f9df a5427139 65b785e5 cc2f707d 6468d7d1 124cdfcf
Phix
<lang Phix>include builtins\sha256.e
function asHex(string s) string res = ""
for i=1 to length(s) do res &= sprintf("%02X",s[i]) end for return res
end function
?asHex(sha256("Rosetta code"))</lang>
- Output:
"764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"
The standard include file sha256.e is now mainly optimised inline assembly, but the following is, I feel, more in the spirit of this site <lang Phix>-- -- demo\rosetta\sha-256.exw -- ======================== -- -- fairly faithful rendition of https://en.wikipedia.org/wiki/SHA-2 -- with slightly improved names (eg s0 -> sigma0) from elsewhere. -- See also sha-256asm.exw for a faster inline asm version, and -- sha-256dll.exw is much shorter as it uses a pre-built dll.
--Initial array of round constants --(first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311): constant k = {
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}
function pad64(integer v) -- round v up to multiple of 64
return floor((v+63)/64)*64
end function
constant m4 = allocate(4) -- scratch area, for uint32
function uint32(atom v) -- -- (note: I have experimented to call this as few times as possible. -- It wouldn't hurt to perform this on every maths op, but a -- few leading bits in a few work fields don't matter much.) --
poke4(m4,v) return peek4u(m4)
end function
function sq_uint32(sequence s) -- apply unit32 to all elements of s
for i=1 to length(s) do s[i] = uint32(s[i]) end for return s
end function
function dword(string msg, integer i) -- get dword as big-endian
return msg[i]*#1000000+msg[i+1]*#10000+msg[i+2]*#100+msg[i+3]
end function
function shr(atom v, integer bits)
return floor(v/power(2,bits))
end function
function ror(atom v, integer bits)
return or_bits(shr(v,bits),v*power(2,32-bits))
end function
function sha256(string msg) -- main function atom s0,s1,a,b,c,d,e,f,g,h,ch,temp1,maj,temp2,x sequence w = repeat(0,64) sequence res integer len = length(msg)+1 --Initial hash values --(first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19) atom h0 = 0x6a09e667,
h1 = 0xbb67ae85, h2 = 0x3c6ef372, h3 = 0xa54ff53a, h4 = 0x510e527f, h5 = 0x9b05688c, h6 = 0x1f83d9ab, h7 = 0x5be0cd19
-- add the '1' bit and space for size in bits, padded to multiple of 64 msg &= #80&repeat('\0',pad64(len+8)-len) len = (len-1)*8 for i=length(msg) to 1 by -1 do msg[i] = and_bits(len,#FF) len = floor(len/#100) if len=0 then exit end if end for
-- Process the message in successive 512-bit (64 byte) chunks for chunk=1 to length(msg) by 64 do for i=1 to 16 do w[i] = dword(msg,chunk+(i-1)*4) end for -- Extend the first 16 words into the remaining 48 words w[17..64] of the message schedule array for i=17 to 64 do x = w[i-15]; s0 = xor_bits(xor_bits(ror(x, 7),ror(x,18)),shr(x, 3)) x = w[i-2]; s1 = xor_bits(xor_bits(ror(x,17),ror(x,19)),shr(x,10)) w[i] = uint32(w[i-16]+s0+w[i-7]+s1) end for -- Initialize working variables to current hash value {a,b,c,d,e,f,g,h} = {h0,h1,h2,h3,h4,h5,h6,h7} -- Compression function main loop for i=1 to 64 do s1 = xor_bits(xor_bits(ror(e,6),ror(e,11)),ror(e,25)) ch = xor_bits(and_bits(e,f),and_bits(not_bits(e),g)) temp1 = h+s1+ch+k[i]+w[i] s0 = xor_bits(xor_bits(ror(a,2),ror(a,13)),ror(a,22)) maj = xor_bits(xor_bits(and_bits(a,b),and_bits(a,c)),and_bits(b,c)) temp2 = s0+maj {h,g,f,e,d,c,b,a} = sq_uint32({g,f,e,d+temp1,c,b,a,temp1+temp2})
end for
-- Add the compressed chunk to the current hash value {h0,h1,h2,h3,h4,h5,h6,h7} = sq_add({h0,h1,h2,h3,h4,h5,h6,h7},{a,b,c,d,e,f,g,h}) end for
-- Produce the final hash value (big-endian) res = sq_uint32({h0, h1, h2, h3, h4, h5, h6, h7}) -- (or do sq_unit32 on the sq_add above) for i=1 to length(res) do res[i] = sprintf("%08x",res[i]) end for return join(res)
end function
?sha256("Rosetta code")</lang>
- Output:
"764FAF5C 61AC315F 1497F9DF A5427139 65B785E5 CC2F707D 6468D7D1 124CDFCF"
PHP
<lang php><?php echo hash('sha256', 'Rosetta code'); </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
PicoLisp
Library and implementation. <lang PicoLisp>(setq *Sha256-K
(mapcar hex '("428A2F98" "71374491" "B5C0FBCF" "E9B5DBA5" "3956C25B" "59F111F1" "923F82A4" "AB1C5ED5" "D807AA98" "12835B01" "243185BE" "550C7DC3" "72BE5D74" "80DEB1FE" "9BDC06A7" "C19BF174" "E49B69C1" "EFBE4786" "0FC19DC6" "240CA1CC" "2DE92C6F" "4A7484AA" "5CB0A9DC" "76F988DA" "983E5152" "A831C66D" "B00327C8" "BF597FC7" "C6E00BF3" "D5A79147" "06CA6351" "14292967" "27B70A85" "2E1B2138" "4D2C6DFC" "53380D13" "650A7354" "766A0ABB" "81C2C92E" "92722C85" "A2BFE8A1" "A81A664B" "C24B8B70" "C76C51A3" "D192E819" "D6990624" "F40E3585" "106AA070" "19A4C116" "1E376C08" "2748774C" "34B0BCB5" "391C0CB3" "4ED8AA4A" "5B9CCA4F" "682E6FF3" "748F82EE" "78A5636F" "84C87814" "8CC70208" "90BEFFFA" "A4506CEB" "BEF9A3F7" "C67178F2") ) )
(de rightRotate (X C)
(| (mod32 (>> C X)) (mod32 (>> (- C 32) X))) )
(de mod32 (N)
(& N `(hex "FFFFFFFF")) )
(de not32 (N)
(x| N `(hex "FFFFFFFF")) )
(de add32 @
(mod32 (pass +)) )
(de sha256 (Str)
(let Len (length Str) (setq Str (conc (need (- 8 (* 64 (/ (+ Len 1 8 63) 64)) ) (conc (mapcar char (chop Str)) (cons `(hex "80"))) 0 ) (flip (make (setq Len (* 8 Len)) (do 8 (link (& Len 255)) (setq Len (>> 8 Len )) ) ) ) ) ) ) (let (H0 `(hex "6A09E667") H1 `(hex "BB67AE85") H2 `(hex "3C6EF372") H3 `(hex "A54FF53A") H4 `(hex "510E527F") H5 `(hex "9B05688C") H6 `(hex "1F83D9AB") H7 `(hex "5BE0CD19") ) (while Str (let (A H0 B H1 C H2 D H3 E H4 F H5 G H6 H H7 W (conc (make (do 16 (link (apply | (mapcar >> (-24 -16 -8 0) (cut 4 'Str)) ) ) ) ) (need 48 0) ) ) (for (I 17 (>= 64 I) (inc I)) (let (Wi15 (get W (- I 15)) Wi2 (get W (- I 2)) S0 (x| (rightRotate Wi15 7) (rightRotate Wi15 18) (>> 3 Wi15) ) S1 (x| (rightRotate Wi2 17) (rightRotate Wi2 19) (>> 10 Wi2) ) ) (set (nth W I) (add32 (get W (- I 16)) S0 (get W (- I 7)) S1 ) ) ) ) (use (Tmp1 Tmp2) (for I 64 (setq Tmp1 (add32 H (x| (rightRotate E 6) (rightRotate E 11) (rightRotate E 25) ) (x| (& E F) (& (not32 E) G)) (get *Sha256-K I) (get W I) ) Tmp2 (add32 (x| (rightRotate A 2) (rightRotate A 13) (rightRotate A 22) ) (x| (& A B) (& A C) (& B C) ) ) H G G F F E E (add32 D Tmp1) D C C B B A A (add32 Tmp1 Tmp2) ) ) ) (setq H0 (add32 H0 A) H1 (add32 H1 B) H2 (add32 H2 C) H3 (add32 H3 D) H4 (add32 H4 E) H5 (add32 H5 F) H6 (add32 H6 G) H7 (add32 H7 H) ) ) ) (mapcan '((N) (flip (make (do 4 (link (& 255 N)) (setq N (>> 8 N)) ) ) ) ) (list H0 H1 H2 H3 H4 H5 H6 H7) ) ) )
(let Str "Rosetta code"
(println (pack (mapcar '((B) (pad 2 (hex B))) (sha256 Str) ) ) ) (println (pack (mapcar '((B) (pad 2 (hex B))) (native "libcrypto.so" "SHA256" '(B . 32) Str (length Str) '(NIL (32)) ) ) ) ) )
(bye)</lang>
Pike
<lang Pike> string input = "Rosetta code"; string out = Crypto.SHA256.hash(input); write( String.string2hex(out) +"\n"); </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
PowerShell
<lang PowerShell> Set-Content -Value "Rosetta code" -Path C:\Colors\blue.txt -NoNewline -Force Get-FileHash -Path C:\Colors\blue.txt -Algorithm SHA256 </lang>
- Output:
Algorithm Hash Path --------- ---- ---- SHA256 764FAF5C61AC315F1497F9DFA542713965B785E5CC2F707D6468D7D1124CDFCF C:\Colors\blue.txt
PureBasic
PB Version 5.40 <lang purebasic>a$="Rosetta code" bit.i= 256
UseSHA2Fingerprint() : b$=StringFingerprint(a$, #PB_Cipher_SHA2, bit)
OpenConsole() Print("[SHA2 "+Str(bit)+" bit] Text: "+a$+" ==> "+b$) Input()</lang>
- Output:
[SHA2 256 bit] Text: Rosetta code ==> 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Python
Python has a standard module for this: <lang python>>>> import hashlib >>> hashlib.sha256( "Rosetta code".encode() ).hexdigest() '764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf' >>> </lang>
R
<lang rsplus> library(digest)
input <- "Rosetta code" cat(digest(input, algo = "sha256", serialize = FALSE), "\n") </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Racket
<lang racket>
- lang racket/base
- define a quick SH256 FFI interface, similar to the Racket's default
- SHA1 interface
(require ffi/unsafe ffi/unsafe/define openssl/libcrypto
(only-in openssl/sha1 bytes->hex-string))
(define-ffi-definer defcrypto libcrypto) (defcrypto SHA256_Init (_fun _pointer -> _int)) (defcrypto SHA256_Update (_fun _pointer _pointer _long -> _int)) (defcrypto SHA256_Final (_fun _pointer _pointer -> _int)) (define (sha256 bytes)
(define ctx (malloc 128)) (define result (make-bytes 32)) (SHA256_Init ctx) (SHA256_Update ctx bytes (bytes-length bytes)) (SHA256_Final result ctx) (bytes->hex-string result))
- use the defined wrapper to solve the task
(displayln (sha256 #"Rosetta code")) </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Raku
(formerly Perl 6)
Pure Raku
The following implementation takes all data as input. Ideally, input should be given lazily or something.
<lang perl6>say sha256 "Rosetta code";
sub init(&f) {
map { my $f = $^p.&f; (($f - $f.Int)*2**32).Int }, state @ = grep *.is-prime, 2 .. *;
}
sub infix:<m+> { ($^a + $^b) % 2**32 } sub rotr($n, $b) { $n +> $b +| $n +< (32 - $b) }
proto sha256($) returns Blob {*} multi sha256(Str $str where all($str.ords) < 128) {
sha256 $str.encode: 'ascii'
} multi sha256(Blob $data) {
constant K = init(* **(1/3))[^64]; my @b = flat $data.list, 0x80; push @b, 0 until (8 * @b - 448) %% 512; push @b, slip reverse (8 * $data).polymod(256 xx 7); my @word = :256[@b.shift xx 4] xx @b/4; my @H = init(&sqrt)[^8]; my @w; loop (my $i = 0; $i < @word; $i += 16) { my @h = @H; for ^64 -> $j { @w[$j] = $j < 16 ?? @word[$j + $i] // 0 !! [m+] rotr(@w[$j-15], 7) +^ rotr(@w[$j-15], 18) +^ @w[$j-15] +> 3, @w[$j-7], rotr(@w[$j-2], 17) +^ rotr(@w[$j-2], 19) +^ @w[$j-2] +> 10, @w[$j-16]; my $ch = @h[4] +& @h[5] +^ +^@h[4] % 2**32 +& @h[6]; my $maj = @h[0] +& @h[2] +^ @h[0] +& @h[1] +^ @h[1] +& @h[2]; my $σ0 = [+^] map { rotr @h[0], $_ }, 2, 13, 22; my $σ1 = [+^] map { rotr @h[4], $_ }, 6, 11, 25; my $t1 = [m+] @h[7], $σ1, $ch, K[$j], @w[$j]; my $t2 = $σ0 m+ $maj; @h = flat $t1 m+ $t2, @h[^3], @h[3] m+ $t1, @h[4..6]; } @H [Z[m+]]= @h; } return Blob.new: map { |reverse .polymod(256 xx 3) }, @H;
}</lang>
- Output:
Buf:0x<76 4f af 5c 61 ac 31 5f 14 97 f9 df a5 42 71 39 65 b7 85 e5 cc 2f 70 7d 64 68 d7 d1 12 4c df cf>
Library implementation
<lang perl6>use Digest::SHA256::Native;
- If you want a string
say sha256-hex 'Rosetta code';
- If you want a binary Blob
say sha256 'Rosetta code';</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf Blob:0x<76 4F AF 5C 61 AC 31 5F 14 97 F9 DF A5 42 71 39 65 B7 85 E5 CC 2F 70 7D 64 68 D7 D1 12 4C DF CF>
Ring
<lang ring>
- Project: SHA-256
load "stdlib.ring" str = "Rosetta code" see "String: " + str + nl see "SHA-256: " see sha256(str) + nl </lang> Output:
String: Rosetta code SHA-256: 764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Ruby
<lang ruby>require 'digest/sha2' puts Digest::SHA256.hexdigest('Rosetta code')</lang>
Rust
<lang rust>use sha2::{Digest, Sha256};
fn hex_string(input: &[u8]) -> String {
input.as_ref().iter().map(|b| format!("{:x}", b)).collect()
}
fn main() {
// create a Sha256 object let mut hasher = Sha256::new();
// write input message hasher.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);
} </lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Scala
<lang Scala>object RosettaSHA256 extends App {
def MD5(s: String): String = { // Besides "MD5", "SHA-256", and other hashes are available val m = java.security.MessageDigest.getInstance("SHA-256").digest(s.getBytes("UTF-8")) m.map("%02x".format(_)).mkString }
assert(MD5("Rosetta code") == "764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf") println("Successfully completed without errors.")
}</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
include "msgdigest.s7i";
const proc: main is func
begin writeln(hex(sha256("Rosetta code"))); end func;</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Sidef
<lang ruby>var sha = frequire('Digest::SHA'); say sha.sha256_hex('Rosetta code');</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Smalltalk
Use the Cryptography library:
<lang smalltalk> (SHA256 new hashStream: 'Rosetta code' readStream) hex. </lang>
Tcl
<lang tcl>package require sha256
puts [sha2::sha256 -hex "Rosetta code"]</lang>
- Output:
764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf
Wren
This is based on the pseudo-code in the Wikipedia article. <lang ecmascript>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)
}</lang>
- Output:
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'
zkl
Uses shared library zklMsgHash.so <lang zkl>var MsgHash=Import("zklMsgHash"); MsgHash.SHA256("Rosetta code")=="764faf5c61ac315f1497f9dfa542713965b785e5cc2f707d6468d7d1124cdfcf"</lang>
- Output:
True
- Programming Tasks
- Checksums
- AArch64 Assembly
- Ada
- CryptAda
- ARM Assembly
- AutoHotkey
- AWK
- BaCon
- BBC BASIC
- C
- C sharp
- C++
- Caché ObjectScript
- Clojure
- Pandect
- Common Lisp
- Ironclad
- Crystal
- D
- Delphi
- System.SysUtils
- DCPsha256
- DWScript
- Emacs Lisp
- Erlang
- F Sharp
- Factor
- Fortran
- Free Pascal
- FreeBASIC
- Frink
- FunL
- Genie
- Go
- Groovy
- Halon
- Haskell
- Haxe
- J
- Java
- JavaScript
- Jsish
- Julia
- Kotlin
- Lasso
- Lua
- Sha2
- Mathematica
- Min
- NetRexx
- NewLISP
- Nim
- Nimcrypto
- OpenSSL
- Oberon-2
- Crypto
- Objeck
- Objective-C
- OCaml
- Caml-sha
- OS X sha256sum
- PARI/GP
- Perl
- Phix
- PHP
- PicoLisp
- Pike
- PowerShell
- PureBasic
- Python
- R
- Racket
- Raku
- Ring
- Ruby
- Rust
- Scala
- Seed7
- Sidef
- Smalltalk
- Tcl
- Wren
- Wren-crypto
- Wren-fmt
- Zkl
- Brlcad/Omit
- GUISS/Omit
- Lilypond/Omit
- Openscad/Omit
- TPP/Omit