2019-07-01 15:24:26 +02:00
|
|
|
require "./lib_sodium"
|
|
|
|
require "./wipe"
|
|
|
|
require "./crypto_box/secret_key"
|
2019-07-01 19:37:45 +02:00
|
|
|
require "./nonce"
|
2019-06-28 13:32:16 +02:00
|
|
|
|
2019-07-01 15:24:26 +02:00
|
|
|
module Sodium
|
|
|
|
class CryptoBox
|
2019-06-28 14:20:56 +02:00
|
|
|
include Wipe
|
|
|
|
|
2019-07-04 02:56:02 +02:00
|
|
|
MAC_SIZE = LibSodium.crypto_box_macbytes.to_i
|
2019-06-30 03:19:01 +02:00
|
|
|
|
2019-06-28 14:20:56 +02:00
|
|
|
# BUG: precompute size
|
2019-06-30 02:21:00 +02:00
|
|
|
@[Wipe::Var]
|
2019-06-28 14:20:56 +02:00
|
|
|
@bytes = Bytes.new(1)
|
|
|
|
|
2019-06-28 13:32:16 +02:00
|
|
|
def initialize(@secret_key : SecretKey, @public_key : PublicKey)
|
2019-06-28 14:20:56 +02:00
|
|
|
# TODO: precompute using crypto_box_beforenm
|
2019-06-28 13:32:16 +02:00
|
|
|
end
|
|
|
|
|
2019-08-06 12:30:16 +02:00
|
|
|
def encrypt(src)
|
|
|
|
encrypt src.to_slice
|
2019-06-28 13:32:16 +02:00
|
|
|
end
|
|
|
|
|
2019-08-06 12:30:16 +02:00
|
|
|
def encrypt(src : Bytes, dst = Bytes.new(src.bytesize + MAC_SIZE), nonce = Nonce.new)
|
2019-06-28 13:32:16 +02:00
|
|
|
if LibSodium.crypto_box_easy(dst, src, src.bytesize, nonce.to_slice, @public_key.to_slice, @secret_key.to_slice) != 0
|
|
|
|
raise Error.new("crypto_box_easy")
|
|
|
|
end
|
2019-07-01 19:37:45 +02:00
|
|
|
{dst, nonce}
|
2019-06-28 13:32:16 +02:00
|
|
|
end
|
|
|
|
|
2019-08-06 12:30:16 +02:00
|
|
|
def decrypt(src)
|
|
|
|
decrypt src.to_slice
|
2019-07-01 15:24:26 +02:00
|
|
|
end
|
|
|
|
|
2019-08-06 12:30:16 +02:00
|
|
|
def decrypt(src : Bytes, dst = Bytes.new(src.bytesize - MAC_SIZE), nonce = Nonce.new) : Bytes
|
2019-06-28 13:32:16 +02:00
|
|
|
if LibSodium.crypto_box_open_easy(dst, src, src.bytesize, nonce.to_slice, @public_key.to_slice, @secret_key.to_slice) != 0
|
|
|
|
raise Error::DecryptionFailed.new("crypto_box_open_easy")
|
|
|
|
end
|
|
|
|
dst
|
|
|
|
end
|
|
|
|
|
|
|
|
# TODO detached
|
|
|
|
end
|
|
|
|
end
|