Class: Blake2

Inherits:
Object
  • Object
show all
Defined in:
lib/blake2/key.rb,
ext/blake2_ext/rbext.c

Defined Under Namespace

Classes: Key

Instance Method Summary collapse

Instance Method Details

#digest(_input, _representation) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# File 'ext/blake2_ext/rbext.c', line 41

VALUE m_blake2_digest(VALUE self, VALUE _input, VALUE _representation) {
  Blake2 *blake2;

  VALUE to_hex   = ID2SYM(rb_intern("to_hex"));
  VALUE to_bytes = ID2SYM(rb_intern("to_bytes"));

  char * input = RSTRING_PTR(_input);
  int input_length = RSTRING_LEN(_input);
  int i;

  Data_Get_Struct(self, Blake2, blake2);

  ID bytes_method = rb_intern("bytes");
  VALUE bytes_ary = rb_funcall(blake2->key, bytes_method, 0);
  int key_len = RARRAY_LEN(bytes_ary);

  uint8_t * key_bytes = (uint8_t*)ruby_xmalloc(key_len * sizeof(uint8_t));

  for(i = 0; i < key_len; i++) {
    VALUE byte = rb_ary_entry(bytes_ary, i);
    key_bytes[i] = NUM2INT(byte);
  }

  blake2s(blake2->output, input, key_bytes,
      blake2->output_length, input_length, key_len);

  if(_representation == to_bytes) {
    VALUE result = rb_ary_new2(blake2->output_length);

    for(i = 0; i < blake2->output_length; i++) {
      rb_ary_push(result, INT2NUM(blake2->output[i]));
    }

    return result;
  } else if(_representation == to_hex) {
    char * c_str = (char*)ruby_xmalloc(blake2->output_length * sizeof(char) * 2);

    for(i = 0; i < blake2->output_length; i++) {
      sprintf(c_str + (i * 2), "%02x", blake2->output[i]);
    }
    return rb_str_new2(c_str);
  } else {
    rb_raise(rb_eArgError, "Unknown representation", _representation);
  }
}