Public
Authored by Nicholas Chambers 👻

Secure Hashing Algorithm 1

Calculate the SHA-1 digest of a given string

Edited
sha-1.c 2.84 KB
  • Currently fails with a string of length 56 or greater:

    ~ λ str=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
    ~ λ printf '%d\n' "${#str}"
    55
    ~ λ sha-1 "$str"
    C1C8BBDC22796E28C0E15163D20899B65621D65A
    ~ λ printf %s "$str" | openssl sha1
    (stdin)= c1c8bbdc22796e28c0e15163d20899b65621d65a
    ~ λ sha-1 "a$str"
    ECB89BCA2A113451AE3B527F45D99E333C591FAA
    ~ λ printf a%s "$str" | openssl sha1
    (stdin)= c2db330f6083854c99d4b5bfb6e8f29f201be699
  • Just kidding, it works now :)

  • Special thanks to Darkf for practically walking me through the entire thing

  • Stress testing can be done with the following Bash script:

    #!/usr/bin/env bash
    
    str=a
    
    for (( i=1; i < ${MAX_STRESS:-10000}; i++ )); do
      hash1=$(sha-1 "$str")
      hash2=$(printf %s "$str" | openssl sha1 -hex)
    
      if [[ $hash1 != "${hash2^^}" ]]; then
        printf 'round %d: string %s failed.\n' "$i" "$str" >&2
        printf 'hash 1 = %s\n' "$hash1" >&2
        printf 'hash 2 = %s\n' "$hash2" >&2
        exit 1
      fi
    
      str=a$str
    done
    
    printf 'all tests successful!\n'
    exit 0
    Edited by Nicholas Chambers
  • ~ λ MAX_STRESS=100000 stress
    all tests successful!
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment