sodium.cr/src/sodium/nonce.cr

43 lines
821 B
Crystal
Raw Normal View History

2017-07-12 05:13:52 +02:00
require "./lib_sodium"
2018-02-14 01:39:15 +01:00
require "random/secure"
2017-07-12 05:13:52 +02:00
module Sodium
2017-07-12 05:13:52 +02:00
class Nonce
2019-08-06 23:30:16 +02:00
class Error < Sodium::Error
class Reused < Error
end
end
NONCE_SIZE = LibSodium::NONCE_SIZE.to_i
getter? used
@used = false
2017-07-12 05:13:52 +02:00
delegate to_slice, to: @bytes
2017-07-12 05:13:52 +02:00
def initialize(@bytes : Bytes)
if bytes.bytesize != NONCE_SIZE
raise ArgumentError.new("Nonce must be #{NONCE_SIZE} bytes, got #{bytes.bytesize}")
2017-07-12 05:13:52 +02:00
end
end
2019-08-06 23:30:16 +02:00
def self.random
self.new Random::Secure.random_bytes(NONCE_SIZE)
end
def self.zero
self.new Bytes.new(NONCE_SIZE)
end
def increment
LibSodium.sodium_increment @bytes, @bytes.bytesize
@used = false
end
def used!
raise Error::Reused.new("attempted nonce reuse") if @used
@used = true
2017-07-12 05:13:52 +02:00
end
end
end