git ssb

0+

dangerousbeans / %aPBe2k3ugtjBr4rrsU1…



Tree: ae87ba58f416c1874af79af3b07e26073441c010

Files: ae87ba58f416c1874af79af3b07e26073441c010 / ext / mri / bcrypt_ext.c

2162 bytesRaw
1#include <ruby.h>
2#include <ow-crypt.h>
3
4static VALUE mBCrypt;
5static VALUE cBCryptEngine;
6
7#ifdef RUBY_VM
8# define RUBY_1_9
9#endif
10
11#ifdef RUBY_1_9
12
13/* When on Ruby 1.9+, we will want to unlock the GIL while performing
14 * expensive calculations, for greater concurrency. Do not do this for
15 * cheap calculations because locking/unlocking the GIL incurs some overhead as well.
16 */
17#define GIL_UNLOCK_COST_THRESHOLD 9
18
19typedef struct {
20 char *output;
21 const char *key;
22 const char *salt;
23} BCryptArguments;
24
25static VALUE bcrypt_wrapper(void *_args) {
26 BCryptArguments *args = (BCryptArguments *)_args;
27 return (VALUE)ruby_bcrypt(args->output, args->key, args->salt);
28}
29
30#endif /* RUBY_1_9 */
31
32/* Given a logarithmic cost parameter, generates a salt for use with +bc_crypt+.
33*/
34static VALUE bc_salt(VALUE self, VALUE prefix, VALUE count, VALUE input) {
35 char * salt;
36 VALUE str_salt;
37
38 salt = crypt_gensalt_ra(
39 StringValuePtr(prefix),
40 NUM2ULONG(count),
41 NIL_P(input) ? NULL : StringValuePtr(input),
42 NIL_P(input) ? 0 : rb_str_strlen(input));
43
44 if(!salt) return Qnil;
45
46 str_salt = rb_str_new2(salt);
47 free(salt);
48
49 return str_salt;
50}
51
52/* Given a secret and a salt, generates a salted hash (which you can then store safely).
53*/
54static VALUE bc_crypt(VALUE self, VALUE key, VALUE setting) {
55 char * value;
56 void * data;
57 int size;
58 VALUE out;
59
60 data = NULL;
61 size = 0xDEADBEEF;
62
63 if(NIL_P(key) || NIL_P(setting)) return Qnil;
64
65 value = crypt_ra(
66 NIL_P(key) ? NULL : StringValuePtr(key),
67 NIL_P(setting) ? NULL : StringValuePtr(setting),
68 &data,
69 &size);
70
71 if(!value) return Qnil;
72
73 out = rb_str_new(data, size - 1);
74
75 free(data);
76
77 return out;
78}
79
80/* Create the BCrypt and BCrypt::Engine modules, and populate them with methods. */
81void Init_bcrypt_ext(){
82 mBCrypt = rb_define_module("BCrypt");
83 cBCryptEngine = rb_define_class_under(mBCrypt, "Engine", rb_cObject);
84
85 rb_define_singleton_method(cBCryptEngine, "__bc_salt", bc_salt, 3);
86 rb_define_singleton_method(cBCryptEngine, "__bc_crypt", bc_crypt, 2);
87}
88
89/* vim: set noet sws=4 sw=4: */
90

Built with git-ssb-web