2019-05-25 17:40:28 -07:00
|
|
|
require "random/secure"
|
|
|
|
|
|
|
|
|
|
module Cox
|
|
|
|
|
class Error < ::Exception
|
2019-06-28 03:30:33 -07:00
|
|
|
class VerificationFailed < Error
|
|
|
|
|
end
|
2019-06-27 17:20:02 -07:00
|
|
|
|
2019-06-28 03:30:33 -07:00
|
|
|
class DecryptionFailed < Error
|
|
|
|
|
end
|
2019-05-25 17:40:28 -07:00
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2019-06-27 17:35:31 -07:00
|
|
|
require "./cox/**"
|
2017-07-11 22:13:52 -05:00
|
|
|
|
|
|
|
|
module Cox
|
2019-06-28 04:32:16 -07:00
|
|
|
def self.encrypt(data, nonce : Nonce, recipient_public_key : CryptoBox::PublicKey, sender_secret_key : CryptoBox::SecretKey)
|
2017-07-11 22:13:52 -05:00
|
|
|
data_buffer = data.to_slice
|
|
|
|
|
data_size = data_buffer.bytesize
|
2019-06-25 09:29:16 -07:00
|
|
|
output_buffer = Bytes.new(data_buffer.bytesize + LibSodium::MAC_SIZE)
|
2019-06-27 17:35:31 -07:00
|
|
|
if LibSodium.crypto_box_easy(output_buffer.to_slice, data_buffer, data_size, nonce.to_slice, recipient_public_key.to_slice, sender_secret_key.to_slice) != 0
|
2019-05-25 17:40:28 -07:00
|
|
|
raise Error.new("crypto_box_easy")
|
|
|
|
|
end
|
2017-07-11 22:13:52 -05:00
|
|
|
output_buffer
|
|
|
|
|
end
|
|
|
|
|
|
2019-06-28 04:32:16 -07:00
|
|
|
def self.encrypt(data, recipient_public_key : CryptoBox::PublicKey, sender_secret_key : CryptoBox::SecretKey)
|
2017-07-11 22:13:52 -05:00
|
|
|
nonce = Nonce.new
|
|
|
|
|
{nonce, encrypt(data, nonce, recipient_public_key, sender_secret_key)}
|
|
|
|
|
end
|
|
|
|
|
|
2019-06-28 04:32:16 -07:00
|
|
|
def self.decrypt(data, nonce : Nonce, sender_public_key : CryptoBox::PublicKey, recipient_secret_key : CryptoBox::SecretKey)
|
2017-07-11 22:13:52 -05:00
|
|
|
data_buffer = data.to_slice
|
|
|
|
|
data_size = data_buffer.bytesize
|
2019-06-25 09:29:16 -07:00
|
|
|
output_buffer = Bytes.new(data_buffer.bytesize - LibSodium::MAC_SIZE)
|
2019-06-27 17:35:31 -07:00
|
|
|
if LibSodium.crypto_box_open_easy(output_buffer.to_slice, data_buffer.to_slice, data_size, nonce.to_slice, sender_public_key.to_slice, recipient_secret_key.to_slice) != 0
|
2019-06-28 03:30:33 -07:00
|
|
|
raise Error::DecryptionFailed.new("crypto_box_open_easy")
|
2019-05-25 17:40:28 -07:00
|
|
|
end
|
2017-07-11 22:13:52 -05:00
|
|
|
output_buffer
|
|
|
|
|
end
|
|
|
|
|
end
|
|
|
|
|
|
2019-06-27 17:20:02 -07:00
|
|
|
if Cox::LibSodium.sodium_init == -1
|
2019-06-27 17:35:31 -07:00
|
|
|
abort "Failed to init libsodium"
|
2017-07-11 22:13:52 -05:00
|
|
|
end
|