Sodium::CryptoBox::PublicKey make #encrypt identical to SecretBox#encrypt.

master
Didactic Drunk 2019-09-14 06:34:50 -07:00
parent 8aea82b296
commit fbb7e9434a
3 changed files with 25 additions and 15 deletions

View File

@ -22,12 +22,20 @@ class Sodium::CryptoBox
end
# Anonymously send messages to a recipient given its public key.
#
# Optionally supply a destination buffer.
#
# For authenticated message use `secret_key.box(recipient_public_key).encrypt`.
def encrypt(src)
encrypt src.to_slice
def encrypt(src, dst : Bytes? = nil)
encrypt src.to_slice, dst
end
def encrypt(src : Bytes, dst : Bytes = Bytes.new(src.bytesize + SEAL_SIZE)) : Bytes
# :nodoc:
def encrypt(src : Bytes, dst : Bytes? = nil) : Bytes
dst_size = src.bytesize + SEAL_SIZE
dst ||= Bytes.new dst_size
raise ArgumentError.new("dst must be #{dst_size} bytes, got #{dst.bytesize}") unless dst.bytesize == dst_size
if LibSodium.crypto_box_seal(dst, src, src.bytesize, @bytes) != 0
raise Sodium::Error.new("crypto_box_seal")
end

View File

@ -8,7 +8,7 @@ class Sodium::CryptoBox
#
# For signing without encryption see `Sodium::Sign::SecretKey`.
#
# # Authenticated encryption
# ## Authenticated encryption
# [https://libsodium.gitbook.io/doc/public-key_cryptography/authenticated_encryption](https://libsodium.gitbook.io/doc/public-key_cryptography/authenticated_encryption#purpose)
#
# Usage:
@ -23,7 +23,7 @@ class Sodium::CryptoBox
# end
# ```
#
# # Sealed Boxes
# ## Sealed Boxes
# [https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes](https://libsodium.gitbook.io/doc/public-key_cryptography/sealed_boxes#purpose)
#
# Usage:

View File

@ -45,18 +45,20 @@ module Sodium
@key = SecureBuffer.new bytes, erase: erase
end
# Encrypts data and returns {ciphertext, nonce}
def encrypt(data)
encrypt data.to_slice
end
# Encrypts data and returns {ciphertext, nonce}
#
# Optionally supply a destination buffer.
def encrypt(src : Bytes, dst : Bytes = Bytes.new(src.bytesize + MAC_SIZE), nonce : Nonce = Nonce.random) : {Bytes, Nonce}
if dst.bytesize != (src.bytesize + MAC_SIZE)
raise ArgumentError.new("dst.bytesize must be src.bytesize + MAC_SIZE, got #{dst.bytesize}")
def encrypt(src, dst : Bytes? = nil, *, nonce : Nonce? = nil)
encrypt src.to_slice, dst, nonce: nonce
end
# :nodoc:
def encrypt(src : Bytes, dst : Bytes? = nil, *, nonce : Nonce? = nil) : {Bytes, Nonce}
dst_size = src.bytesize + MAC_SIZE
dst ||= Bytes.new dst_size
raise ArgumentError.new("dst.bytesize must be src.bytesize + MAC_SIZE, got #{dst.bytesize}") if dst.bytesize != (src.bytesize + MAC_SIZE)
nonce ||= Nonce.random
nonce.used!
r = @key.readonly do
LibSodium.crypto_secretbox_easy(dst, src, src.bytesize, nonce.to_slice, @key)
@ -72,7 +74,7 @@ module Sodium
decrypt src.to_slice, dst, nonce: nonce
end
# Returns decrypted message.
# Returns decrypted message as a `String`.
#
# Optionally supply a destination buffer.
def decrypt_string(src, dst : Bytes? = nil, *, nonce : Nonce) : String