From f1a225b03b14e2102de4906df83681c3d55ffd1f Mon Sep 17 00:00:00 2001 From: Didactic Drunk <1479616+didactic-drunk@users.noreply.github.com> Date: Sun, 28 Jun 2020 16:30:17 -0700 Subject: [PATCH] Sodium::Digest::Blake2b Add #hexfinal(dst). Better specs. --- spec/sodium/digest/blake2b_spec.cr | 39 +++++++++++++++++++++++++++++- spec/spec_helper.cr | 1 + src/sodium/digest/blake2b.cr | 14 +++++++++++ src/sodium/lib_sodium.cr | 1 + 4 files changed, 54 insertions(+), 1 deletion(-) diff --git a/spec/sodium/digest/blake2b_spec.cr b/spec/sodium/digest/blake2b_spec.cr index eee1d4d..56dcf01 100644 --- a/spec/sodium/digest/blake2b_spec.cr +++ b/spec/sodium/digest/blake2b_spec.cr @@ -89,8 +89,45 @@ describe Sodium::Digest::Blake2b do expect_raises ArgumentError do Sodium::Digest::Blake2b.new personal: Bytes.new(128) end + + d = Sodium::Digest::Blake2b.new + expect_raises ArgumentError do + d.hexfinal Bytes.new(1) + end + expect_raises ArgumentError do + d.hexfinal Bytes.new(256) + end end - pending "dups" do + it "can't final twice or update after final" do + d = Sodium::Digest::Blake2b.new + d.hexfinal + + expect_raises Digest::FinalizedError do + d.hexfinal + end + + expect_raises Digest::FinalizedError do + d.update Bytes.new(0) + end + end + + it "dups" do + data = "foo".to_slice + d1 = Sodium::Digest::Blake2b.new + d2 = d1.dup + d3 = d2.dup + + d1.update data + h1 = d1.hexfinal + + d2.update data + h2 = d2.hexfinal + + d3.update data + h3 = d3.hexfinal + + h1.should eq h2 + h1.should eq h3 end end diff --git a/spec/spec_helper.cr b/spec/spec_helper.cr index 3acb2a0..e3a8194 100644 --- a/spec/spec_helper.cr +++ b/spec/spec_helper.cr @@ -1,3 +1,4 @@ +require "log" require "spec" # require "../src/sodium" diff --git a/src/sodium/digest/blake2b.cr b/src/sodium/digest/blake2b.cr index fa3eeef..6dee1e6 100644 --- a/src/sodium/digest/blake2b.cr +++ b/src/sodium/digest/blake2b.cr @@ -19,6 +19,8 @@ module Sodium::Digest class Blake2b < ::Digest::Base include Wipe + Log = ::Log.for self + # 32 KEY_SIZE = LibSodium.crypto_generichash_blake2b_keybytes.to_i # 16 @@ -84,6 +86,18 @@ module Sodium::Digest def hexfinal : String final.hexstring end + + def hexfinal(dst : Bytes) : Nil + dsize = digest_size + unless dst.bytesize == dsize * 2 + raise ArgumentError.new("Incorrect dst size: #{dst.bytesize}, expected: #{dsize * 2}") + end + + sary = uninitialized StaticArray(UInt8, 64) + tmp = sary.to_slice[0, dsize] + final tmp + tmp.hexstring dst + end {% end %} # Compatibility with Crystal <= 0.32 diff --git a/src/sodium/lib_sodium.cr b/src/sodium/lib_sodium.cr index 4148b10..e846cea 100644 --- a/src/sodium/lib_sodium.cr +++ b/src/sodium/lib_sodium.cr @@ -1,3 +1,4 @@ +require "log" require "random/secure" require "./error"