Sha256 Hashes in Assembly Language

Here’s the translation of the SHA256 Hashes example to Assembly Language, formatted in Markdown suitable for Hugo:

section .data
    input db "sha256 this string", 0
    input_len equ $ - input
    format db "%s", 10, 0
    hex_format db "%02x", 0

section .bss
    hash resb 32

section .text
    global main
    extern printf
    extern SHA256_Init
    extern SHA256_Update
    extern SHA256_Final

main:
    ; Initialize SHA256 context
    push rbp
    mov rdi, hash
    call SHA256_Init

    ; Update SHA256 with input string
    mov rdi, hash
    mov rsi, input
    mov rdx, input_len
    call SHA256_Update

    ; Finalize SHA256 hash
    mov rdi, hash
    mov rsi, hash
    call SHA256_Final

    ; Print original string
    mov rdi, format
    mov rsi, input
    xor eax, eax
    call printf

    ; Print hash in hex format
    xor ecx, ecx
print_loop:
    movzx esi, byte [hash + rcx]
    mov rdi, hex_format
    xor eax, eax
    push rcx
    call printf
    pop rcx
    inc ecx
    cmp ecx, 32
    jl print_loop

    ; Print newline
    mov rdi, format
    xor rsi, rsi
    xor eax, eax
    call printf

    ; Exit program
    xor eax, eax
    pop rbp
    ret

This Assembly Language code demonstrates how to compute SHA256 hashes. SHA256 hashes are frequently used to compute short identities for binary or text blobs. For example, TLS/SSL certificates use SHA256 to compute a certificate’s signature.

In this example, we’re using the OpenSSL library functions for SHA256 computation. The code assumes that you have linked against the OpenSSL library.

Here’s a breakdown of what the code does:

  1. We define our input string in the .data section.

  2. In the .bss section, we reserve 32 bytes for the hash result.

  3. In the main function:

    • We initialize the SHA256 context using SHA256_Init.
    • We update the context with our input string using SHA256_Update.
    • We finalize the hash computation with SHA256_Final.
  4. We then print the original string.

  5. Finally, we print the computed hash in hexadecimal format. We loop through each byte of the hash, printing it as a two-digit hexadecimal number.

To run this program, you would need to assemble it with NASM, link it with the C standard library and OpenSSL, and then execute the resulting binary.

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