Crypto::Secret Add #copy_from, #move_from

Fix Sodium typo
master
Didactic Drunk 2021-06-21 02:36:10 -07:00
parent d104b75296
commit 99111aa819
4 changed files with 23 additions and 4 deletions

View File

@ -77,6 +77,9 @@ slice = method_that_return_bytes()
secret = Crypto::Secret::Bidet.move_from slice # erases slice
# or
secret = Crypto::Secret::Bidet.copy_from slice
# or
secret = Crypto::Secret::Bidet size_in_bytes
secret.move_from slice
```
## What is a Secret?

View File

@ -13,9 +13,7 @@ module Crypto::Secret::ClassMethods
# Returns a **readonly** Secret
def copy_from(data : Bytes)
new(data.bytesize).tap do |obj|
obj.readwrite do |slice|
data.copy_to slice
end
obj.copy_from data
end
end

View File

@ -6,7 +6,7 @@ require "./bidet"
#
# Uses `Sodium::SecureBuffer` If "sodium" is required before "crypto-secret"
{% if @type.has_constant?("Sodium") %}
class Crypto::Secret::Key < ::Sodum::SecureBuffer
class Crypto::Secret::Key < ::Sodium::SecureBuffer
end
{% else %}
# TODO: mlock

View File

@ -38,11 +38,29 @@ module Crypto::Secret
extend ClassMethods
# For debugging.
#
# Returned String **not** tracked or wiped
def hexstring : String
readonly &.hexstring
end
# Copies then wipes *data*
#
# Prefer this method over `#copy_from`
def move_from(data : Bytes) : Nil
copy_from data
ensure
data.wipe
end
# Copies from *data*
def copy_from(data : Bytes) : Nil
readwrite do |slice|
slice.copy_from data
end
end
# Fills `Secret` with secure random data
def random : self
readwrite do |slice|
Random::Secure.random_bytes slice