Class: Digest::Base32

Inherits:
Object
  • Object
show all
Defined in:
lib/digest/base32.rb,
lib/digest/base32/version.rb,
ext/digest/base32_ext/digest-base32.c

Defined Under Namespace

Classes: DecodeError

Constant Summary collapse

CHARS =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
VERSION =
'0.0.2'

Class Method Summary collapse

Class Method Details

.decode(*args) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'ext/digest/base32_ext/digest-base32.c', line 32

static VALUE
digest_base32_decode(int argc, VALUE *argv, VALUE self)
{
  VALUE input;
  const unsigned char* src;
  size_t input_len, estimate_len;

  rb_scan_args(argc, argv, "1", &input);

  if (TYPE(input) != T_STRING) {
    rb_raise(rb_eTypeError, "expected a String");
  }

  src = (unsigned char*) StringValuePtr(input);
  input_len = RSTRING_LEN(input);
  estimate_len = UNBASE32_LEN(input_len);
  unsigned char out[estimate_len];

  base32_decode(src, out);

  return rb_str_new_cstr((const char*) out);
}

.encode(*args) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'ext/digest/base32_ext/digest-base32.c', line 11

static VALUE
digest_base32_encode(int argc, VALUE* argv, VALUE self)
{
  VALUE input;
  const unsigned char* src;
  size_t srclen;
  rb_scan_args(argc, argv, "1", &input);

  if (TYPE(input) != T_STRING) {
    rb_raise(rb_eTypeError, "expected a String");
  }

  src = (unsigned char*) StringValuePtr(input);
  srclen = BASE32_LEN(RSTRING_LEN(input));

  unsigned char dest[srclen];
  base32_encode(src, RSTRING_LEN(input), dest);

  return rb_str_new((const char*) dest, srclen);
}

.random(length: 16, padding: true) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/digest/base32.rb', line 13

def self.random(length: 16, padding: true)
  unless length.is_a? Integer
    raise TypeError, "Expected #{Integer}, got #{length.class}"
  end

  unless [true, false].include? padding
    raise TypeError, "Expected bool, got #{padding.class}"
  end

  random = +''
  SecureRandom.random_bytes(length).each_byte do |b|
    random << CHARS[b % 32]
  end
  padding ? random.ljust((length / 8.0).ceil * 8, '=') : random
end