Module: Obfuskey::Utils
- Defined in:
- lib/obfuskey/utils.rb
Class Method Summary collapse
- .decode(value, alphabet) ⇒ Object
- .encode(value, alphabet) ⇒ Object
- .generate_prime(alphabet, key_length, prime_multiplier = PRIME_MULTIPLIER) ⇒ Object
Class Method Details
.decode(value, alphabet) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/obfuskey/utils.rb', line 7 def decode(value, alphabet) chars = value.chars unless chars.all? { |c| alphabet.include?(c) } raise UnknownKeyError, "The value contains characters not found in the current alphabet." end return alphabet.index(value) if chars.length == 1 base = alphabet.length result = 0 chars.each do |c| result = result * base + alphabet.index(c) end result end |
.encode(value, alphabet) ⇒ Object
24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/obfuskey/utils.rb', line 24 def encode(value, alphabet) raise NegativeValueError, "The value must be greater than or equal to zero." if value < 0 return alphabet[value] if value < alphabet.length base = alphabet.length key = +"" while value > 0 value, i = value.divmod(base) key << alphabet[i] end key.reverse end |
.generate_prime(alphabet, key_length, prime_multiplier = PRIME_MULTIPLIER) ⇒ Object
38 39 40 41 42 43 44 |
# File 'lib/obfuskey/utils.rb', line 38 def generate_prime(alphabet, key_length, prime_multiplier = PRIME_MULTIPLIER) # Mirror Python's Decimal(float) conversion: Rational(float) preserves # the exact binary representation of a Float, matching Python's behavior. factor = prime_multiplier.is_a?(Float) ? Rational(prime_multiplier) : prime_multiplier target = ((alphabet.length**key_length - 1) * factor).to_i Math.next_prime(target) end |