SHA

用法非常直接:

  1. julia> using SHA
  2. julia> bytes2hex(sha256("test"))
  3. "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"

Each exported function (at the time of this writing, SHA-1, SHA-2 224, 256, 384 and 512, and SHA-3 224, 256, 384 and 512 functions are implemented) takes in either an AbstractVector{UInt8}, an AbstractString or an IO object. This makes it trivial to checksum a file:

  1. shell> cat /tmp/test.txt
  2. test
  3. julia> using SHA
  4. julia> open("/tmp/test.txt") do f
  5. sha2_256(f)
  6. end
  7. 32-element Array{UInt8,1}:
  8. 0x9f
  9. 0x86
  10. 0xd0
  11. 0x81
  12. 0x88
  13. 0x4c
  14. 0x7d
  15. 0x65
  16. 0x5d
  17. 0x6c
  18. 0x15
  19. 0xb0
  20. 0xf0
  21. 0x0a
  22. 0x08

Due to the colloquial usage of sha256 to refer to sha2_256, convenience functions are provided, mapping shaxxx() function calls to sha2_xxx(). For SHA-3, no such colloquialisms exist and the user must use the full sha3_xxx() names.

shaxxx() takes AbstractString and array-like objects (NTuple and Array) with elements of type UInt8.

To create a hash from multiple items the SHAX_XXX_CTX() types can be used to create a stateful hash object that is updated with update! and finalized with digest!

  1. julia> ctx = SHA2_256_CTX()
  2. SHA2 256-bit hash state
  3. julia> update!(ctx, b"some data")
  4. 0x0000000000000009
  5. julia> update!(ctx, b"some more data")
  6. 0x0000000000000017
  7. julia> digest!(ctx)
  8. 32-element Vector{UInt8}:
  9. 0xbe
  10. 0xcf
  11. 0x23
  12. 0xda
  13. 0xaf
  14. 0x02
  15. 0x25
  16. 0x52
  17. 0x19
  18. 0xa0
  19. 0x8b
  20. 0xc5

Note that, at the time of this writing, the SHA3 code is not optimized, and as such is roughly an order of magnitude slower than SHA2.