class Discordrb::Voice::SecretBox

Utility class for interacting with required ‘xsalsa20poly1305` functions for voice transmission @!visibility private

Constants

BOX_ZERO_BYTES

Zero byte padding for decryption

KEY_LENGTH

Required key length

NONCE_BYTES

Required nonce length

ZERO_BYTES

Zero byte padding for encryption

Public Class Methods

new(key) click to toggle source

@param key [String] Crypto key of length {KEY_LENGTH}

# File lib/discordrb/voice/sodium.rb, line 47
def initialize(key)
  raise(LengthError, 'Key length') if key.bytesize != KEY_LENGTH

  @key = key
end

Public Instance Methods

box(nonce, message) click to toggle source

Encrypts a message using this box’s key @param nonce [String] encryption nonce for this message @param message [String] message to be encrypted

# File lib/discordrb/voice/sodium.rb, line 56
def box(nonce, message)
  raise(LengthError, 'Nonce length') if nonce.bytesize != NONCE_BYTES

  message_padded = prepend_zeroes(ZERO_BYTES, message)
  buffer = zero_string(message_padded.bytesize)

  success = Sodium.crypto_secretbox_xsalsa20poly1305(buffer, message_padded, message_padded.bytesize, nonce, @key)
  raise(CryptoError, "Encryption failed (#{success})") unless success.zero?

  remove_zeroes(BOX_ZERO_BYTES, buffer)
end
open(nonce, ciphertext) click to toggle source

Decrypts the given ciphertext using this box’s key @param nonce [String] encryption nonce for this ciphertext @param ciphertext [String] ciphertext to decrypt

# File lib/discordrb/voice/sodium.rb, line 71
def open(nonce, ciphertext)
  raise(LengthError, 'Nonce length') if nonce.bytesize != NONCE_BYTES

  ct_padded = prepend_zeroes(BOX_ZERO_BYTES, ciphertext)
  buffer = zero_string(ct_padded.bytesize)

  success = Sodium.crypto_secretbox_xsalsa20poly1305_open(buffer, ct_padded, ct_padded.bytesize, nonce, @key)
  raise(CryptoError, "Decryption failed (#{success})") unless success.zero?

  remove_zeroes(ZERO_BYTES, buffer)
end

Private Instance Methods

prepend_zeroes(size, string) click to toggle source
# File lib/discordrb/voice/sodium.rb, line 90
def prepend_zeroes(size, string)
  zero_string(size) + string
end
remove_zeroes(size, string) click to toggle source
# File lib/discordrb/voice/sodium.rb, line 94
def remove_zeroes(size, string)
  string.slice!(size, string.bytesize - size)
end
zero_string(size) click to toggle source
# File lib/discordrb/voice/sodium.rb, line 85
def zero_string(size)
  str = "\0" * size
  str.force_encoding('ASCII-8BIT') if str.respond_to?(:force_encoding)
end