Sha256 Hashes in Fortran

Here’s the translation of the SHA256 hashes example to Fortran, formatted in Markdown suitable for Hugo:

Our program demonstrates how to compute SHA256 hashes in Fortran. 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.

program sha256_hashes
    use iso_fortran_env, only: int8, int32
    use, intrinsic :: iso_c_binding, only: c_char, c_ptr, c_loc, c_size_t
    implicit none

    interface
        subroutine sha256_init() bind(c, name='SHA256_Init')
        end subroutine sha256_init

        subroutine sha256_update(data, len) bind(c, name='SHA256_Update')
            import :: c_ptr, c_size_t
            type(c_ptr), value :: data
            integer(c_size_t), value :: len
        end subroutine sha256_update

        subroutine sha256_final(md) bind(c, name='SHA256_Final')
            import :: c_ptr
            type(c_ptr), value :: md
        end subroutine sha256_final
    end interface

    character(len=:), allocatable :: s
    integer(int8), dimension(32) :: hash
    integer :: i

    s = "sha256 this string"

    ! Initialize the SHA256 context
    call sha256_init()

    ! Update the context with the input string
    call sha256_update(c_loc(s), len(s))

    ! Finalize the hash
    call sha256_final(c_loc(hash))

    ! Print the original string
    print *, s

    ! Print the hash in hexadecimal format
    write(*, '(*(Z2.2))', advance='no') hash
    print *
end program sha256_hashes

In this Fortran implementation:

  1. We use the iso_fortran_env and iso_c_binding modules for interoperability with C libraries.

  2. We declare interfaces for the C functions SHA256_Init, SHA256_Update, and SHA256_Final from the OpenSSL library.

  3. We create a string s that we want to hash.

  4. We initialize the SHA256 context using sha256_init().

  5. We update the context with our input string using sha256_update().

  6. We finalize the hash using sha256_final().

  7. Finally, we print the original string and the computed hash in hexadecimal format.

To compile and run this program, you’ll need to link against the OpenSSL library:

$ gfortran -o sha256_hashes sha256_hashes.f90 -lcrypto
$ ./sha256_hashes
sha256 this string
1af1dfa857bf1d8814fe1af8983c18080019922e557f15a8a...

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

Fortran doesn’t have built-in cryptographic functions like some other languages, so we’re using the OpenSSL library here. In a real-world scenario, you might want to use a Fortran-specific cryptography library or write more robust error handling and memory management.