blake2s.odin 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package blake2s
  2. /*
  3. Copyright 2021 zhibog
  4. Made available under the BSD-3 license.
  5. List of contributors:
  6. zhibog, dotbmp: Initial implementation.
  7. Interface for the BLAKE2S hashing algorithm.
  8. BLAKE2B and BLAKE2B share the implementation in the _blake2 package.
  9. */
  10. import "core:os"
  11. import "core:io"
  12. import "../_blake2"
  13. /*
  14. High level API
  15. */
  16. // hash_string will hash the given input and return the
  17. // computed hash
  18. hash_string :: proc(data: string) -> [32]byte {
  19. return hash_bytes(transmute([]byte)(data))
  20. }
  21. // hash_bytes will hash the given input and return the
  22. // computed hash
  23. hash_bytes :: proc(data: []byte) -> [32]byte {
  24. hash: [32]byte
  25. ctx: _blake2.Blake2s_Context
  26. cfg: _blake2.Blake2_Config
  27. cfg.size = _blake2.BLAKE2S_SIZE
  28. ctx.cfg = cfg
  29. _blake2.init(&ctx)
  30. _blake2.update(&ctx, data)
  31. _blake2.final(&ctx, hash[:])
  32. return hash
  33. }
  34. // hash_stream will read the stream in chunks and compute a
  35. // hash from its contents
  36. hash_stream :: proc(s: io.Stream) -> ([32]byte, bool) {
  37. hash: [32]byte
  38. ctx: _blake2.Blake2s_Context
  39. cfg: _blake2.Blake2_Config
  40. cfg.size = _blake2.BLAKE2S_SIZE
  41. ctx.cfg = cfg
  42. _blake2.init(&ctx)
  43. buf := make([]byte, 512)
  44. defer delete(buf)
  45. read := 1
  46. for read > 0 {
  47. read, _ = s->impl_read(buf)
  48. if read > 0 {
  49. _blake2.update(&ctx, buf[:read])
  50. }
  51. }
  52. _blake2.final(&ctx, hash[:])
  53. return hash, true
  54. }
  55. // hash_file will read the file provided by the given handle
  56. // and compute a hash
  57. hash_file :: proc(hd: os.Handle, load_at_once := false) -> ([32]byte, bool) {
  58. if !load_at_once {
  59. return hash_stream(os.stream_from_handle(hd))
  60. } else {
  61. if buf, ok := os.read_entire_file(hd); ok {
  62. return hash_bytes(buf[:]), ok
  63. }
  64. }
  65. return [32]byte{}, false
  66. }
  67. hash :: proc {
  68. hash_stream,
  69. hash_file,
  70. hash_bytes,
  71. hash_string,
  72. }
  73. /*
  74. Low level API
  75. */
  76. Blake2s_Context :: _blake2.Blake2b_Context
  77. init :: proc(ctx: ^_blake2.Blake2s_Context) {
  78. _blake2.init(ctx)
  79. }
  80. update :: proc "contextless" (ctx: ^_blake2.Blake2s_Context, data: []byte) {
  81. _blake2.update(ctx, data)
  82. }
  83. final :: proc "contextless" (ctx: ^_blake2.Blake2s_Context, hash: []byte) {
  84. _blake2.final(ctx, hash)
  85. }