Compare commits

..

No commits in common. "2e1856fedb58c80b6be21c0045481ff4e93ab7f3" and "475ce2e5c830e614a05364993358ed85880fae40" have entirely different histories.

11 changed files with 81 additions and 119 deletions

View File

@ -3,33 +3,34 @@ require "random/pcg32"
require "random/isaac"
require "../src/sodium/cipher/chalsa"
randoms = {
"PCG" => Random::PCG32.new(0),
"ISAAC" => Random::ISAAC.new(Bytes.new(32)),
"Secure" => Random::Secure,
}
pcgrand = Random::PCG32.new 0
isaacrand = Random::ISAAC.new Bytes.new(32)
ciphers = {{ Sodium::Cipher::Chalsa.subclasses }}.map do |klass|
key = Bytes.new klass.key_size
nonce = Bytes.new klass.nonce_size
cipher = klass.new key, nonce
cipher = klass.new.tap do |c|
c.key = Bytes.new c.key_size
c.nonce = Bytes.new c.nonce_size
end
# {short_name, cipher}
{klass.to_s.split("::").last, cipher}
end.to_a
# p ciphers
buf = Bytes.new 1024
Benchmark.ips warmup: 0.5 do |bm|
randoms.each do |name, random|
bm.report "#{name}" do
random.random_bytes buf
end
bm.report "PCG32" do
pcgrand.random_bytes buf
end
ciphers.each do |name, random|
bm.report "ISAAC" do
isaacrand.random_bytes buf
end
ciphers.each do |name, cipher|
bm.report "#{name}" do
random.random_bytes buf
cipher.random_bytes buf
end
end
end

View File

@ -1,8 +1,7 @@
PCG 1.29M (776.49ns) (± 1.13%) 0.0B/op 1.07× slower
ISAAC 530.69k ( 1.88µs) (± 0.98%) 0.0B/op 2.60× slower
Secure 318.19k ( 3.14µs) (± 2.30%) 0.0B/op 4.33× slower
XSalsa20 1.04M (960.42ns) (± 1.34%) 0.0B/op 1.32× slower
Salsa20 1.16M (862.14ns) (± 1.29%) 0.0B/op 1.19× slower
XChaCha20 1.22M (818.52ns) (± 1.86%) 0.0B/op 1.13× slower
ChaCha20Ietf 1.38M (726.43ns) (± 1.28%) 0.0B/op 1.00× slower
ChaCha20 1.38M (725.47ns) (± 1.33%) 0.0B/op fastest
PCG32 606.78k ( 1.65µs) (± 1.07%) 0.0B/op 4.19× slower
ISAAC 373.63k ( 2.68µs) (± 1.95%) 0.0B/op 6.80× slower
XSalsa20 1.84M (544.61ns) (± 1.17%) 0.0B/op 1.38× slower
Salsa20 2.37M (421.53ns) (± 1.24%) 0.0B/op 1.07× slower
XChaCha20 1.88M (530.86ns) (± 1.46%) 0.0B/op 1.35× slower
ChaCha20Ietf 2.54M (393.65ns) (± 1.22%) 0.0B/op fastest
ChaCha20 2.51M (398.58ns) (± 1.73%) 0.0B/op 1.01× slower

View File

@ -17,14 +17,6 @@ puts ""
{% end %}
puts ""
{% for sk in [Sodium::CryptoBox::SecretKey, Sodium::Sign::SecretKey] %}
sk = {{sk.id}}.new
pk = sk.public_key
# puts "#{sk.class} bytesize #{sk.to_slice.bytesize}"
puts "#{pk.class} bytesize #{pk.to_slice.bytesize}"
{% end %}
puts ""
{% for name in %w(KEY_SIZE NONCE_SIZE MAC_SIZE) %}
puts "Sodium::SecretBox::{{ name.id }} #{Sodium::SecretBox::{{ name.id }}}"
{% end %}
@ -55,8 +47,9 @@ puts ""
{% end %}
puts ""
{% for name in %w(XChaCha20 ChaCha20Ietf ChaCha20 XSalsa20 Salsa20) %}
c = Sodium::Cipher::{{name.id}}.random
# puts "#{c.class} key_size #{c.key_size}"
puts "#{c.class} nonce_size #{c.nonce_size}"
{% for sk in [Sodium::CryptoBox::SecretKey, Sodium::Sign::SecretKey] %}
sk = {{sk.id}}.new
pk = sk.public_key
puts "#{sk.class} bytesize #{sk.to_slice.bytesize}"
puts "#{pk.class} bytesize #{pk.to_slice.bytesize}"
{% end %}

View File

@ -19,13 +19,6 @@ require "../../../src/sodium/cipher/chalsa"
cipher2.final.should eq Bytes.new(0)
end
it "Random" do
cipher = Sodium::Cipher::{{ name.id }}.random
cipher.random_bytes(8).should_not eq(cipher.random_bytes(8))
r = 3.times.map { cipher.rand(65536) }.sum
r.should_not eq(0)
end
it "dups" do
cipher1 = Sodium::Cipher::{{ name.id }}.new Bytes.new(Sodium::Cipher::{{ name.id }}::KEY_SIZE)
cipher2 = cipher1.dup

View File

@ -5,11 +5,11 @@ CONTEXT = "8_bytess"
describe Sodium::Kdf do
it "generates master key" do
kdf1 = Sodium::Kdf.random
kdf1 = Sodium::Kdf.new
# verify loading saved key
kdf2 = kdf1.key.readonly do |kslice|
Sodium::Kdf.copy_key_from kslice.dup
Sodium::Kdf.new kslice.dup
end
kdf1.key.should eq kdf2.key
@ -21,7 +21,7 @@ describe Sodium::Kdf do
end
it "generates different keys" do
kdf1 = Sodium::Kdf.random
kdf1 = Sodium::Kdf.new
subkey1 = kdf1.derive CONTEXT, 0, 16
subkey2 = kdf1.derive CONTEXT, 1, 16
subkey1.should_not eq subkey2

View File

@ -98,9 +98,6 @@ describe Sodium::Sign::SecretKey do
end
end
pending "combined test vectors" do
end
it "RbNaCl detached test vectors" do
detached_test_vectors.each do |vec|
seckey, plaintext, signature = sign_from_vec vec

View File

@ -6,17 +6,15 @@ module Sodium::Cipher
#
# What? They're both dance?
abstract class Chalsa
include Random
getter key : Crypto::Secret
getter! nonce : Bytes?
# Advanced usage. Don't touch.
property offset = 0_u64
property offset = 0
def initialize(key : Crypto::Secret | Bytes, nonce = nil)
raise ArgumentError.new("key must be #{key_size} bytes, got #{key.bytesize}") if key.bytesize != key_size
@key = key.is_a?(Crypto::Secret) ? key : Sodium::SecureBuffer.copy_from(key)
@key = key.is_a?(Crypto::Secret) ? key : Sodium::SecureBuffer.new(key)
self.nonce = nonce if nonce
end
@ -44,7 +42,7 @@ module Sodium::Cipher
end
def random_nonce
self.nonce = ::Random::Secure.random_bytes nonce_size
self.nonce = Random::Secure.random_bytes nonce_size
end
# Xor's src with the cipher output and returns a new Slice
@ -62,14 +60,17 @@ module Sodium::Cipher
# Use as a CSPRNG.
def random_bytes(bytes : Bytes) : Bytes
# TODO: Switch to memset
Sodium.memzero bytes
update bytes, bytes
bytes
end
def next_u : UInt8
buf = uninitialized UInt8[1]
random_bytes buf.to_slice
buf.unsafe_as(UInt8)
# Use as a CSPRNG.
def random_bytes(size : Int) : Bytes
bytes = Bytes.new size
update bytes, bytes
bytes
end
# Always returns false. Sadness...
@ -86,35 +87,26 @@ module Sodium::Cipher
end
end
{% for key, val in {"XSalsa20" => "xsalsa20", "Salsa20" => "salsa20", "XChaCha20" => "xchacha20", "ChaCha20Ietf" => "chacha20_ietf", "ChaCha20" => "chacha20"} %}
{% for key, valtup in {"XSalsa20" => {"xsalsa20", false}, "Salsa20" => {"salsa20", false}, "XChaCha20" => {"xchacha20", false}, "ChaCha20Ietf" => {"chacha20_ietf", true}, "ChaCha20" => {"chacha20", false}} %}
{% val = valtup[0] %}
{% ietf = valtup[1] %}
# These classes can be used to generate pseudo-random data from a key,
# or as building blocks for implementing custom constructions, but they
# are not alternatives to `SecretBox`.
# are not alternatives to secretbox.
#
# See [https://libsodium.gitbook.io/doc/advanced/stream_ciphers](https://libsodium.gitbook.io/doc/advanced/stream_ciphers) for further information.
#
# This class mimicks the `OpenSSL::Cipher` interface with minor differences.
#
# Also provides a `::Random` interface.
# * Lacks forward secrecy.
# * ~3x faster than `::Random::Secure`
#
# Use with caution. When in doubt use `::Random::Secure`
#
# Possibly safe uses:
# * Test data
# * Overwriting storage with random data
# * Single player video games (maybe)
# This class mimicks the OpenSSL::Cipher interface with minor differences.
#
# See `spec/sodium/cipher/chalsa_spec.cr` for examples on how to use this class.
#
# WARNING: Not validated against test vectors. You should probably write some before using this class.
class {{ key.id }} < Chalsa
KEY_SIZE = LibSodium.crypto_stream_{{ val.id }}_keybytes.to_i32
NONCE_SIZE = LibSodium.crypto_stream_{{ val.id }}_noncebytes.to_i32
KEY_SIZE = LibSodium.crypto_stream_chacha20_{{ ietf ? "ietf_".id : "".id }}keybytes.to_i32
NONCE_SIZE = LibSodium.crypto_stream_chacha20_{{ ietf ? "ietf_".id : "".id }}noncebytes.to_i32
def self.random
new key: Sodium::SecureBuffer.random(KEY_SIZE), nonce: ::Random::Secure.random_bytes(NONCE_SIZE)
new key: Sodium::SecureBuffer.random(KEY_SIZE), nonce: Random::Secure.random_bytes(NONCE_SIZE)
end
# Xor's src with the cipher output and places in dst.
@ -136,14 +128,6 @@ module Sodium::Cipher
end
end
def self.key_size : Int32
KEY_SIZE
end
def self.nonce_size : Int32
NONCE_SIZE
end
def key_size : Int32
KEY_SIZE
end

View File

@ -42,6 +42,9 @@ class Sodium::CryptoBox
getter key : Crypto::Secret
getter public_key : PublicKey
# Returns key
delegate_to_slice to: @key
@seed : Crypto::Secret?
# Generate a new random secret/public key pair.
@ -160,12 +163,9 @@ class Sodium::CryptoBox
# For authenticated messages use `secret_key.box(recipient_public_key).decrypt`.
#
# Optionally supply a destination buffer.
def decrypt_string(src) : String
dsize = src.bytesize - SEAL_SIZE
String.new(dsize) do |dst|
decrypt src.to_slice, dst.to_slice(dsize)
{dsize, dsize}
end
def decrypt_string(src, dst : Bytes? = nil) : String
msg = decrypt src.to_slice, dst
String.new msg
end
# :nodoc:

View File

@ -7,8 +7,7 @@ module Sodium
#
# Usage:
# ```
# kdf = KDF.random
# kdf = KDF.move_key_from bytes
# kdf = KDF.new
# subkey_id = 0
# output_size = 16
# subkey = kdf.derive "8bytectx", subkey_id, output_size
@ -19,7 +18,7 @@ module Sodium
#
# It's recommended to use a #wipe block to erase the master key when no longer needed
# ```
# kdf = Kdf.random
# kdf = Kdf.new
# ...
# kdf.wipe do
# ### Warning: abnormal exit may not wipe
@ -42,29 +41,16 @@ module Sodium
getter key : Crypto::Secret
def self.random
new(SecureBuffer.random(KEY_SIZE))
end
# Use an existing KDF key.
#
# * Copies key to a new SecureBuffer
def self.copy_key_from(bytes : Bytes)
new(SecureBuffer.copy_from(bytes))
end
# Use an existing KDF key.
#
# * Copies key to a new SecureBuffer
# * Erases bytes after copying
def self.move_key_from(bytes : Bytes)
new(SecureBuffer.move_from(bytes))
end
@[Deprecated("use .copy_key_from or .move_key_from")]
# * Optionally erases bytes after copying if erase is set
def initialize(bytes : Bytes, erase = false)
@key = SecureBuffer.new(1)
raise NotImplementedError.new("use .copy_key_from or .move_key_from")
if bytes.bytesize != KEY_SIZE
raise ArgumentError.new("bytes must be #{KEY_SIZE}, got #{bytes.bytesize}")
end
@key = SecureBuffer.new(bytes, erase).noaccess
end
# Use an existing KDF Crypto::Secret key.
@ -75,7 +61,9 @@ module Sodium
@key.noaccess
end
@[Deprecated("use .random")]
# Generate a new random KDF key.
#
# Make sure to save kdf.to_slice before kdf goes out of scope.
def initialize
@key = SecureBuffer.random(KEY_SIZE).noaccess
end

View File

@ -4,5 +4,7 @@ require "./wipe"
module Sodium
abstract class Key
include Sodium::Wipe
abstract def to_slice : Bytes
end
end

View File

@ -7,20 +7,19 @@ module Sodium
#
# #initialize returns readonly or readwrite for thread safety
# When state changes are required (such as using #noaccess) and the buffer is accessed from multiple threads wrap each #readonly/#readwrite block in a lock.
class SecureBuffer < Crypto::Secret
class SecureBuffer
include Crypto::Secret::Stateful
getter buffer_bytesize : Int32
getter bytesize : Int32
def initialize(@buffer_bytesize : Int32)
@ptr = LibSodium.sodium_malloc @buffer_bytesize
raise Error::OutOfMemory.new("allocating #{@buffer_bytesize}") if @ptr.null?
def initialize(@bytesize : Int32)
@ptr = LibSodium.sodium_malloc @bytesize
raise Error::OutOfMemory.new if @ptr.null?
end
# Copies bytes to a **readonly** SecureBuffer.
# Optionally erases bytes after copying if erase is set
# Returns a **readonly** SecureBuffer.
@[Deprecated("Use .copy_from or .move_from")]
def initialize(bytes : Bytes, erase = false)
initialize bytes.bytesize
readwrite do |slice|
@ -33,7 +32,7 @@ module Sodium
# :nodoc:
# For .dup
def initialize(sbuf : Crypto::Secret)
initialize sbuf.buffer_bytesize
initialize sbuf.bytesize
# Maybe not thread safe
sbuf.readonly do |sslice|
@ -57,12 +56,18 @@ module Sodium
#
@[Deprecated("Use the Slice provided within a `readonly` or `readwrite` block")]
def to_slice : Bytes
raise NotImplementedError.new
case @state
when State::Noaccess, State::Wiped
readonly
else
# Ok
end
Slice(UInt8).new @ptr, @bytesize
end
protected def to_slice(& : Bytes -> Nil)
ro = @state < State::Readonly
yield Bytes.new(@ptr, @buffer_bytesize, read_only: ro)
yield Bytes.new(@ptr, @bytesize, read_only: ro)
end
# :nodoc: