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
|
|
|
|
2019-06-29 01:17:09 +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
|
|
|
|
2019-06-28 02:35:31 +02:00
|
|
|
delegate to_slice, to: @bytes
|
|
|
|
|
2017-07-12 05:13:52 +02:00
|
|
|
def initialize(@bytes : Bytes)
|
2019-06-25 18:29:16 +02:00
|
|
|
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
|