summaryrefslogtreecommitdiff
path: root/ext/openssl/ossl_bn.c
blob: 8d0f63a986f3b20a46ac926c7fd4cf7586fee6bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
/*
 * 'OpenSSL for Ruby' project
 * Copyright (C) 2001-2002  Technorama team <oss-ruby@technorama.net>
 * All rights reserved.
 */
/*
 * This program is licensed under the same licence as Ruby.
 * (See the file 'LICENCE'.)
 */
/* modified by Michal Rokos <m.rokos@sh.cvut.cz> */
#include "ossl.h"

#ifdef HAVE_RB_EXT_RACTOR_SAFE
#include <ruby/ractor.h>
#endif

#define NewBN(klass) \
  TypedData_Wrap_Struct((klass), &ossl_bn_type, 0)
#define SetBN(obj, bn) do { \
  if (!(bn)) { \
    ossl_raise(rb_eRuntimeError, "BN wasn't initialized!"); \
  } \
  RTYPEDDATA_DATA(obj) = (bn); \
} while (0)

#define GetBN(obj, bn) do { \
  TypedData_Get_Struct((obj), BIGNUM, &ossl_bn_type, (bn)); \
  if (!(bn)) { \
    ossl_raise(rb_eRuntimeError, "BN wasn't initialized!"); \
  } \
} while (0)

static void
ossl_bn_free(void *ptr)
{
    BN_clear_free(ptr);
}

static const rb_data_type_t ossl_bn_type = {
    "OpenSSL/BN",
    {
	0, ossl_bn_free,
    },
    0, 0, RUBY_TYPED_FREE_IMMEDIATELY,
};

/*
 * Classes
 */
VALUE cBN;

/* Document-class: OpenSSL::BNError
 *
 * Generic Error for all of OpenSSL::BN (big num)
 */
VALUE eBNError;

/*
 * Public
 */
VALUE
ossl_bn_new(const BIGNUM *bn)
{
    BIGNUM *newbn;
    VALUE obj;

    obj = NewBN(cBN);
    newbn = bn ? BN_dup(bn) : BN_new();
    if (!newbn) {
	ossl_raise(eBNError, NULL);
    }
    SetBN(obj, newbn);

    return obj;
}

static BIGNUM *
integer_to_bnptr(VALUE obj, BIGNUM *orig)
{
    BIGNUM *bn;

    if (FIXNUM_P(obj)) {
	long i;
	unsigned char bin[sizeof(long)];
	long n = FIX2LONG(obj);
	unsigned long un = labs(n);

	for (i = sizeof(long) - 1; 0 <= i; i--) {
	    bin[i] = un & 0xff;
	    un >>= 8;
	}

	bn = BN_bin2bn(bin, sizeof(bin), orig);
	if (!bn)
	    ossl_raise(eBNError, "BN_bin2bn");
	if (n < 0)
	    BN_set_negative(bn, 1);
    }
    else { /* assuming Bignum */
	size_t len = rb_absint_size(obj, NULL);
	unsigned char *bin;
	VALUE buf;
	int sign;

	if (INT_MAX < len) {
	    rb_raise(eBNError, "bignum too long");
	}
	bin = (unsigned char*)ALLOCV_N(unsigned char, buf, len);
	sign = rb_integer_pack(obj, bin, len, 1, 0, INTEGER_PACK_BIG_ENDIAN);

	bn = BN_bin2bn(bin, (int)len, orig);
	ALLOCV_END(buf);
	if (!bn)
	    ossl_raise(eBNError, "BN_bin2bn");
	if (sign < 0)
	    BN_set_negative(bn, 1);
    }

    return bn;
}

static VALUE
try_convert_to_bn(VALUE obj)
{
    BIGNUM *bn;
    VALUE newobj = Qnil;

    if (rb_obj_is_kind_of(obj, cBN))
	return obj;
    if (RB_INTEGER_TYPE_P(obj)) {
	newobj = NewBN(cBN); /* Handle potential mem leaks */
	bn = integer_to_bnptr(obj, NULL);
	SetBN(newobj, bn);
    }

    return newobj;
}

BIGNUM *
ossl_bn_value_ptr(volatile VALUE *ptr)
{
    VALUE tmp;
    BIGNUM *bn;

    tmp = try_convert_to_bn(*ptr);
    if (NIL_P(tmp))
	ossl_raise(rb_eTypeError, "Cannot convert into OpenSSL::BN");
    GetBN(tmp, bn);
    *ptr = tmp;

    return bn;
}

/*
 * Private
 */

#ifdef HAVE_RB_EXT_RACTOR_SAFE
void
ossl_bn_ctx_free(void *ptr)
{
    BN_CTX *ctx = (BN_CTX *)ptr;
    BN_CTX_free(ctx);
}

struct rb_ractor_local_storage_type ossl_bn_ctx_key_type = {
    NULL, // mark
    ossl_bn_ctx_free,
};

rb_ractor_local_key_t ossl_bn_ctx_key;

BN_CTX *
ossl_bn_ctx_get(void)
{
    // stored in ractor local storage

    BN_CTX *ctx = rb_ractor_local_storage_ptr(ossl_bn_ctx_key);
    if (!ctx) {
        if (!(ctx = BN_CTX_new())) {
            ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX");
        }
        rb_ractor_local_storage_ptr_set(ossl_bn_ctx_key, ctx);
    }
    return ctx;
}
#else
// for ruby 2.x
static BN_CTX *gv_ossl_bn_ctx;

BN_CTX *
ossl_bn_ctx_get(void)
{
    if (gv_ossl_bn_ctx == NULL) {
        if (!(gv_ossl_bn_ctx = BN_CTX_new())) {
            ossl_raise(rb_eRuntimeError, "Cannot init BN_CTX");
        }
    }
    return gv_ossl_bn_ctx;
}

void
ossl_bn_ctx_free(void)
{
    BN_CTX_free(gv_ossl_bn_ctx);
    gv_ossl_bn_ctx = NULL;
}
#endif

static VALUE
ossl_bn_alloc(VALUE klass)
{
    BIGNUM *bn;
    VALUE obj = NewBN(klass);

    if (!(bn = BN_new())) {
	ossl_raise(eBNError, NULL);
    }
    SetBN(obj, bn);

    return obj;
}

/*
 * call-seq:
 *    OpenSSL::BN.new(bn) -> aBN
 *    OpenSSL::BN.new(integer) -> aBN
 *    OpenSSL::BN.new(string, base = 10) -> aBN
 *
 * Construct a new \OpenSSL BIGNUM object.
 *
 * If +bn+ is an Integer or OpenSSL::BN, a new instance of OpenSSL::BN
 * representing the same value is returned. See also Integer#to_bn for the
 * short-hand.
 *
 * If a String is given, the content will be parsed according to +base+.
 *
 * +string+::
 *   The string to be parsed.
 * +base+::
 *   The format. Must be one of the following:
 *   - +0+  - MPI format. See the man page BN_mpi2bn(3) for details.
 *   - +2+  - Variable-length and big-endian binary encoding of a positive
 *     number.
 *   - +10+ - Decimal number representation, with a leading '-' for a negative
 *     number.
 *   - +16+ - Hexadeciaml number representation, with a leading '-' for a
 *     negative number.
 */
static VALUE
ossl_bn_initialize(int argc, VALUE *argv, VALUE self)
{
    BIGNUM *bn;
    VALUE str, bs;
    int base = 10;
    char *ptr;

    if (rb_scan_args(argc, argv, "11", &str, &bs) == 2) {
	base = NUM2INT(bs);
    }

    if (NIL_P(str)) {
        ossl_raise(rb_eArgError, "invalid argument");
    }

    if (RB_INTEGER_TYPE_P(str)) {
	GetBN(self, bn);
	integer_to_bnptr(str, bn);

	return self;
    }

    if (RTEST(rb_obj_is_kind_of(str, cBN))) {
	BIGNUM *other;

	GetBN(self, bn);
	GetBN(str, other); /* Safe - we checked kind_of? above */
	if (!BN_copy(bn, other)) {
	    ossl_raise(eBNError, NULL);
	}
	return self;
    }

    GetBN(self, bn);
    switch (base) {
    case 0:
        ptr = StringValuePtr(str);
        if (!BN_mpi2bn((unsigned char *)ptr, RSTRING_LENINT(str), bn)) {
	    ossl_raise(eBNError, NULL);
	}
	break;
    case 2:
        ptr = StringValuePtr(str);
        if (!BN_bin2bn((unsigned char *)ptr, RSTRING_LENINT(str), bn)) {
	    ossl_raise(eBNError, NULL);
	}
	break;
    case 10:
	if (!BN_dec2bn(&bn, StringValueCStr(str))) {
	    ossl_raise(eBNError, NULL);
	}
	break;
    case 16:
	if (!BN_hex2bn(&bn, StringValueCStr(str))) {
	    ossl_raise(eBNError, NULL);
	}
	break;
    default:
	ossl_raise(rb_eArgError, "invalid radix %d", base);
    }
    return self;
}

/*
 * call-seq:
 *    bn.to_s(base = 10) -> string
 *
 * Returns the string representation of the bignum.
 *
 * BN.new can parse the encoded string to convert back into an OpenSSL::BN.
 *
 * +base+::
 *   The format. Must be one of the following:
 *   - +0+  - MPI format. See the man page BN_bn2mpi(3) for details.
 *   - +2+  - Variable-length and big-endian binary encoding. The sign of
 *     the bignum is ignored.
 *   - +10+ - Decimal number representation, with a leading '-' for a negative
 *     bignum.
 *   - +16+ - Hexadeciaml number representation, with a leading '-' for a
 *     negative bignum.
 */
static VALUE
ossl_bn_to_s(int argc, VALUE *argv, VALUE self)
{
    BIGNUM *bn;
    VALUE str, bs;
    int base = 10, len;
    char *buf;

    if (rb_scan_args(argc, argv, "01", &bs) == 1) {
	base = NUM2INT(bs);
    }
    GetBN(self, bn);
    switch (base) {
    case 0:
	len = BN_bn2mpi(bn, NULL);
        str = rb_str_new(0, len);
	if (BN_bn2mpi(bn, (unsigned char *)RSTRING_PTR(str)) != len)
	    ossl_raise(eBNError, NULL);
	break;
    case 2:
	len = BN_num_bytes(bn);
        str = rb_str_new(0, len);
	if (BN_bn2bin(bn, (unsigned char *)RSTRING_PTR(str)) != len)
	    ossl_raise(eBNError, NULL);
	break;
    case 10:
	if (!(buf = BN_bn2dec(bn))) ossl_raise(eBNError, NULL);
	str = ossl_buf2str(buf, rb_long2int(strlen(buf)));
	break;
    case 16:
	if (!(buf = BN_bn2hex(bn))) ossl_raise(eBNError, NULL);
	str = ossl_buf2str(buf, rb_long2int(strlen(buf)));
	break;
    default:
	ossl_raise(rb_eArgError, "invalid radix %d", base);
    }

    return str;
}

/*
 * call-seq:
 *    bn.to_i => integer
 */
static VALUE
ossl_bn_to_i(VALUE self)
{
    BIGNUM *bn;
    char *txt;
    VALUE num;

    GetBN(self, bn);

    if (!(txt = BN_bn2hex(bn))) {
	ossl_raise(eBNError, NULL);
    }
    num = rb_cstr_to_inum(txt, 16, Qtrue);
    OPENSSL_free(txt);

    return num;
}

static VALUE
ossl_bn_to_bn(VALUE self)
{
    return self;
}

static VALUE
ossl_bn_coerce(VALUE self, VALUE other)
{
    switch(TYPE(other)) {
    case T_STRING:
	self = ossl_bn_to_s(0, NULL, self);
	break;
    case T_FIXNUM:
    case T_BIGNUM:
	self = ossl_bn_to_i(self);
	break;
    default:
	if (!RTEST(rb_obj_is_kind_of(other, cBN))) {
	    ossl_raise(rb_eTypeError, "Don't know how to coerce");
	}
    }
    return rb_assoc_new(other, self);
}

#define BIGNUM_BOOL1(func)				\
    static VALUE					\
    ossl_bn_##func(VALUE self)				\
    {							\
	BIGNUM *bn;					\
	GetBN(self, bn);				\
	if (BN_##func(bn)) {				\
	    return Qtrue;				\
	}						\
	return Qfalse;					\
    }

/*
 * Document-method: OpenSSL::BN#zero?
 * call-seq:
 *   bn.zero? => true | false
 */
BIGNUM_BOOL1(is_zero)

/*
 * Document-method: OpenSSL::BN#one?
 * call-seq:
 *   bn.one? => true | false
 */
BIGNUM_BOOL1(is_one)

/*
 * Document-method: OpenSSL::BN#odd?
 * call-seq:
 *   bn.odd? => true | false
 */
BIGNUM_BOOL1(is_odd)

/*
 * call-seq:
 *   bn.negative? => true | false
 */
static VALUE
ossl_bn_is_negative(VALUE self)
{
    BIGNUM *bn;

    GetBN(self, bn);
    if (BN_is_zero(bn))
	return Qfalse;
    return BN_is_negative(bn) ? Qtrue : Qfalse;
}

#define BIGNUM_1c(func)					\
    static VALUE					\
    ossl_bn_##func(VALUE self)				\
    {							\
	BIGNUM *bn, *result;				\
	VALUE obj;					\
	GetBN(self, bn);				\
	obj = NewBN(rb_obj_class(self));		\
	if (!(result = BN_new())) {			\
	    ossl_raise(eBNError, NULL);			\
	}						\
	if (BN_##func(result, bn, ossl_bn_ctx) <= 0) {	\
	    BN_free(result);				\
	    ossl_raise(eBNError, NULL);			\
	}						\
	SetBN(obj, result);				\
	return obj;					\
    }

/*
 * Document-method: OpenSSL::BN#sqr
 * call-seq:
 *   bn.sqr => aBN
 */
BIGNUM_1c(sqr)

#define BIGNUM_2(func)					\
    static VALUE					\
    ossl_bn_##func(VALUE self, VALUE other)		\
    {							\
	BIGNUM *bn1, *bn2 = GetBNPtr(other), *result;	\
	VALUE obj;					\
	GetBN(self, bn1);				\
	obj = NewBN(rb_obj_class(self));		\
	if (!(result = BN_new())) {			\
	    ossl_raise(eBNError, NULL);			\
	}						\
	if (BN_##func(result, bn1, bn2) <= 0) {		\
	    BN_free(result);				\
	    ossl_raise(eBNError, NULL);			\
	}						\
	SetBN(obj, result);				\
	return obj;					\
    }

/*
 * Document-method: OpenSSL::BN#+
 * call-seq:
 *   bn + bn2 => aBN
 */
BIGNUM_2(add)

/*
 * Document-method: OpenSSL::BN#-
 * call-seq:
 *   bn - bn2 => aBN
 */
BIGNUM_2(sub)

#define BIGNUM_2c(func)						\
    static VALUE						\
    ossl_bn_##func(VALUE self, VALUE other)			\
    {								\
	BIGNUM *bn1, *bn2 = GetBNPtr(other), *result;		\
	VALUE obj;						\
	GetBN(self, bn1);					\
	obj = NewBN(rb_obj_class(self));			\
	if (!(result = BN_new())) {				\
	    ossl_raise(eBNError, NULL);				\
	}							\
	if (BN_##func(result, bn1, bn2, ossl_bn_ctx) <= 0) {	\
	    BN_free(result);					\
	    ossl_raise(eBNError, NULL);				\
	}							\
	SetBN(obj, result);					\
	return obj;						\
    }

/*
 * Document-method: OpenSSL::BN#*
 * call-seq:
 *   bn * bn2 => aBN
 */
BIGNUM_2c(mul)

/*
 * Document-method: OpenSSL::BN#%
 * call-seq:
 *   bn % bn2 => aBN
 */
BIGNUM_2c(mod)

/*
 * Document-method: OpenSSL::BN#**
 * call-seq:
 *   bn ** bn2 => aBN
 */
BIGNUM_2c(exp)

/*
 * Document-method: OpenSSL::BN#gcd
 * call-seq:
 *   bn.gcd(bn2) => aBN
 */
BIGNUM_2c(gcd)

/*
 * Document-method: OpenSSL::BN#mod_sqr
 * call-seq:
 *   bn.mod_sqr(bn2) => aBN
 */
BIGNUM_2c(mod_sqr)

/*
 * call-seq:
 *    bn.mod_inverse(bn2) => aBN
 */
static VALUE
ossl_bn_mod_inverse(VALUE self, VALUE other)
{
    BIGNUM *bn1, *bn2 = GetBNPtr(other), *result;
    VALUE obj;
    GetBN(self, bn1);
    obj = NewBN(rb_obj_class(self));
    if (!(result = BN_mod_inverse(NULL, bn1, bn2, ossl_bn_ctx)))
        ossl_raise(eBNError, "BN_mod_inverse");
    SetBN(obj, result);
    return obj;
}

/*
 * call-seq:
 *    bn1 / bn2 => [result, remainder]
 *
 * Division of OpenSSL::BN instances
 */
static VALUE
ossl_bn_div(VALUE self, VALUE other)
{
    BIGNUM *bn1, *bn2 = GetBNPtr(other), *r1, *r2;
    VALUE klass, obj1, obj2;

    GetBN(self, bn1);

    klass = rb_obj_class(self);
    obj1 = NewBN(klass);
    obj2 = NewBN(klass);
    if (!(r1 = BN_new())) {
	ossl_raise(eBNError, NULL);
    }
    if (!(r2 = BN_new())) {
	BN_free(r1);
	ossl_raise(eBNError, NULL);
    }
    if (!BN_div(r1, r2, bn1, bn2, ossl_bn_ctx)) {
	BN_free(r1);
	BN_free(r2);
	ossl_raise(eBNError, NULL);
    }
    SetBN(obj1, r1);
    SetBN(obj2, r2);

    return rb_ary_new3(2, obj1, obj2);
}

#define BIGNUM_3c(func)						\
    static VALUE						\
    ossl_bn_##func(VALUE self, VALUE other1, VALUE other2)	\
    {								\
	BIGNUM *bn1, *bn2 = GetBNPtr(other1);			\
	BIGNUM *bn3 = GetBNPtr(other2), *result;		\
	VALUE obj;						\
	GetBN(self, bn1);					\
	obj = NewBN(rb_obj_class(self));			\
	if (!(result = BN_new())) {				\
	    ossl_raise(eBNError, NULL);				\
	}							\
	if (BN_##func(result, bn1, bn2, bn3, ossl_bn_ctx) <= 0) { \
	    BN_free(result);					\
	    ossl_raise(eBNError, NULL);				\
	}							\
	SetBN(obj, result);					\
	return obj;						\
    }

/*
 * Document-method: OpenSSL::BN#mod_add
 * call-seq:
 *   bn.mod_add(bn1, bn2) -> aBN
 */
BIGNUM_3c(mod_add)

/*
 * Document-method: OpenSSL::BN#mod_sub
 * call-seq:
 *   bn.mod_sub(bn1, bn2) -> aBN
 */
BIGNUM_3c(mod_sub)

/*
 * Document-method: OpenSSL::BN#mod_mul
 * call-seq:
 *   bn.mod_mul(bn1, bn2) -> aBN
 */
BIGNUM_3c(mod_mul)

/*
 * Document-method: OpenSSL::BN#mod_exp
 * call-seq:
 *   bn.mod_exp(bn1, bn2) -> aBN
 */
BIGNUM_3c(mod_exp)

#define BIGNUM_BIT(func)				\
    static VALUE					\
    ossl_bn_##func(VALUE self, VALUE bit)		\
    {							\
	BIGNUM *bn;					\
	GetBN(self, bn);				\
	if (BN_##func(bn, NUM2INT(bit)) <= 0) {		\
	    ossl_raise(eBNError, NULL);			\
	}						\
	return self;					\
    }

/*
 * Document-method: OpenSSL::BN#set_bit!
 * call-seq:
 *   bn.set_bit!(bit) -> self
 */
BIGNUM_BIT(set_bit)

/*
 * Document-method: OpenSSL::BN#clear_bit!
 * call-seq:
 *   bn.clear_bit!(bit) -> self
 */
BIGNUM_BIT(clear_bit)

/*
 * Document-method: OpenSSL::BN#mask_bit!
 * call-seq:
 *   bn.mask_bit!(bit) -> self
 */
BIGNUM_BIT(mask_bits)

/*
 * call-seq:
 *   bn.bit_set?(bit) => true | false
 *
 * Tests bit _bit_ in _bn_ and returns +true+ if set, +false+ if not set.
 */
static VALUE
ossl_bn_is_bit_set(VALUE self, VALUE bit)
{
    int b;
    BIGNUM *bn;

    b = NUM2INT(bit);
    GetBN(self, bn);
    if (BN_is_bit_set(bn, b)) {
	return Qtrue;
    }
    return Qfalse;
}

#define BIGNUM_SHIFT(func)				\
    static VALUE					\
    ossl_bn_##func(VALUE self, VALUE bits)		\
    {							\
	BIGNUM *bn, *result;				\
	int b;						\
	VALUE obj;					\
	b = NUM2INT(bits);				\
	GetBN(self, bn);				\
	obj = NewBN(rb_obj_class(self));		\
	if (!(result = BN_new())) {			\
		ossl_raise(eBNError, NULL);		\
	}						\
	if (BN_##func(result, bn, b) <= 0) {		\
		BN_free(result);			\
		ossl_raise(eBNError, NULL);		\
	}						\
	SetBN(obj, result);				\
	return obj;					\
    }

/*
 * Document-method: OpenSSL::BN#<<
 * call-seq:
 *   bn << bits -> aBN
 */
BIGNUM_SHIFT(lshift)

/*
 * Document-method: OpenSSL::BN#>>
 * call-seq:
 *   bn >> bits -> aBN
 */
BIGNUM_SHIFT(rshift)

#define BIGNUM_SELF_SHIFT(func)				\
    static VALUE					\
    ossl_bn_self_##func(VALUE self, VALUE bits)		\
    {							\
	BIGNUM *bn;					\
	int b;						\
	b = NUM2INT(bits);				\
	GetBN(self, bn);				\
	if (BN_##func(bn, bn, b) <= 0)			\
		ossl_raise(eBNError, NULL);		\
	return self;					\
    }

/*
 * Document-method: OpenSSL::BN#lshift!
 * call-seq:
 *   bn.lshift!(bits) -> self
 */
BIGNUM_SELF_SHIFT(lshift)

/*
 * Document-method: OpenSSL::BN#rshift!
 * call-seq:
 *   bn.rshift!(bits) -> self
 */
BIGNUM_SELF_SHIFT(rshift)

#define BIGNUM_RAND(func)					\
    static VALUE						\
    ossl_bn_s_##func(int argc, VALUE *argv, VALUE klass)	\
    {								\
	BIGNUM *result;						\
	int bottom = 0, top = 0, b;				\
	VALUE bits, fill, odd, obj;				\
								\
	switch (rb_scan_args(argc, argv, "12", &bits, &fill, &odd)) {	\
	case 3:							\
	    bottom = (odd == Qtrue) ? 1 : 0;			\
	    /* FALLTHROUGH */					\
	case 2:							\
	    top = NUM2INT(fill);				\
	}							\
	b = NUM2INT(bits);					\
	obj = NewBN(klass);					\
	if (!(result = BN_new())) {				\
	    ossl_raise(eBNError, NULL);				\
	}							\
	if (BN_##func(result, b, top, bottom) <= 0) {		\
	    BN_free(result);					\
	    ossl_raise(eBNError, NULL);				\
	}							\
	SetBN(obj, result);					\
	return obj;						\
    }

/*
 * Document-method: OpenSSL::BN.rand
 *   BN.rand(bits [, fill [, odd]]) -> aBN
 */
BIGNUM_RAND(rand)

/*
 * Document-method: OpenSSL::BN.pseudo_rand
 *   BN.pseudo_rand(bits [, fill [, odd]]) -> aBN
 */
BIGNUM_RAND(pseudo_rand)

#define BIGNUM_RAND_RANGE(func)					\
    static VALUE						\
    ossl_bn_s_##func##_range(VALUE klass, VALUE range)		\
    {								\
	BIGNUM *bn = GetBNPtr(range), *result;			\
	VALUE obj = NewBN(klass);				\
	if (!(result = BN_new())) {				\
	    ossl_raise(eBNError, NULL);				\
	}							\
	if (BN_##func##_range(result, bn) <= 0) {		\
	    BN_free(result);					\
	    ossl_raise(eBNError, NULL);				\
	}							\
	SetBN(obj, result);					\
	return obj;						\
    }

/*
 * Document-method: OpenSSL::BN.rand_range
 * call-seq:
 *   BN.rand_range(range) -> aBN
 *
 */
BIGNUM_RAND_RANGE(rand)

/*
 * Document-method: OpenSSL::BN.pseudo_rand_range
 * call-seq:
 *   BN.pseudo_rand_range(range) -> aBN
 *
 */
BIGNUM_RAND_RANGE(pseudo_rand)

/*
 * call-seq:
 *    BN.generate_prime(bits, [, safe [, add [, rem]]]) => bn
 *
 * Generates a random prime number of bit length _bits_. If _safe_ is set to
 * +true+, generates a safe prime. If _add_ is specified, generates a prime that
 * fulfills condition <tt>p % add = rem</tt>.
 *
 * === Parameters
 * * _bits_ - integer
 * * _safe_ - boolean
 * * _add_ - BN
 * * _rem_ - BN
 */
static VALUE
ossl_bn_s_generate_prime(int argc, VALUE *argv, VALUE klass)
{
    BIGNUM *add = NULL, *rem = NULL, *result;
    int safe = 1, num;
    VALUE vnum, vsafe, vadd, vrem, obj;

    rb_scan_args(argc, argv, "13", &vnum, &vsafe, &vadd, &vrem);

    num = NUM2INT(vnum);

    if (vsafe == Qfalse) {
	safe = 0;
    }
    if (!NIL_P(vadd)) {
	add = GetBNPtr(vadd);
	rem = NIL_P(vrem) ? NULL : GetBNPtr(vrem);
    }
    obj = NewBN(klass);
    if (!(result = BN_new())) {
	ossl_raise(eBNError, NULL);
    }
    if (!BN_generate_prime_ex(result, num, safe, add, rem, NULL)) {
	BN_free(result);
	ossl_raise(eBNError, NULL);
    }
    SetBN(obj, result);

    return obj;
}

#define BIGNUM_NUM(func)			\
    static VALUE 				\
    ossl_bn_##func(VALUE self)			\
    {						\
	BIGNUM *bn;				\
	GetBN(self, bn);			\
	return INT2NUM(BN_##func(bn));		\
    }

/*
 * Document-method: OpenSSL::BN#num_bytes
 * call-seq:
 *   bn.num_bytes => integer
 */
BIGNUM_NUM(num_bytes)

/*
 * Document-method: OpenSSL::BN#num_bits
 * call-seq:
 *   bn.num_bits => integer
 */
BIGNUM_NUM(num_bits)

static VALUE
ossl_bn_copy(VALUE self, VALUE other)
{
    BIGNUM *bn1, *bn2;

    rb_check_frozen(self);

    if (self == other) return self;

    GetBN(self, bn1);
    bn2 = GetBNPtr(other);

    if (!BN_copy(bn1, bn2)) {
	ossl_raise(eBNError, NULL);
    }
    return self;
}

/*
 * call-seq:
 *   +bn -> aBN
 */
static VALUE
ossl_bn_uplus(VALUE self)
{
    VALUE obj;
    BIGNUM *bn1, *bn2;

    GetBN(self, bn1);
    obj = NewBN(cBN);
    bn2 = BN_dup(bn1);
    if (!bn2)
	ossl_raise(eBNError, "BN_dup");
    SetBN(obj, bn2);

    return obj;
}

/*
 * call-seq:
 *   -bn -> aBN
 */
static VALUE
ossl_bn_uminus(VALUE self)
{
    VALUE obj;
    BIGNUM *bn1, *bn2;

    GetBN(self, bn1);
    obj = NewBN(cBN);
    bn2 = BN_dup(bn1);
    if (!bn2)
	ossl_raise(eBNError, "BN_dup");
    SetBN(obj, bn2);
    BN_set_negative(bn2, !BN_is_negative(bn2));

    return obj;
}

/*
 * call-seq:
 *   bn.abs -> aBN
 */
static VALUE
ossl_bn_abs(VALUE self)
{
    BIGNUM *bn1;

    GetBN(self, bn1);
    if (BN_is_negative(bn1)) {
        return ossl_bn_uminus(self);
    }
    else {
        return ossl_bn_uplus(self);
    }
}

#define BIGNUM_CMP(func)				\
    static VALUE					\
    ossl_bn_##func(VALUE self, VALUE other)		\
    {							\
	BIGNUM *bn1, *bn2 = GetBNPtr(other);		\
	GetBN(self, bn1);				\
	return INT2NUM(BN_##func(bn1, bn2));		\
    }

/*
 * Document-method: OpenSSL::BN#cmp
 * call-seq:
 *   bn.cmp(bn2) => integer
 */
/*
 * Document-method: OpenSSL::BN#<=>
 * call-seq:
 *   bn <=> bn2 => integer
 */
BIGNUM_CMP(cmp)

/*
 * Document-method: OpenSSL::BN#ucmp
 * call-seq:
 *   bn.ucmp(bn2) => integer
 */
BIGNUM_CMP(ucmp)

/*
 *  call-seq:
 *     bn == obj => true or false
 *
 *  Returns +true+ only if _obj_ has the same value as _bn_. Contrast this
 *  with OpenSSL::BN#eql?, which requires obj to be OpenSSL::BN.
 */
static VALUE
ossl_bn_eq(VALUE self, VALUE other)
{
    BIGNUM *bn1, *bn2;

    GetBN(self, bn1);
    other = try_convert_to_bn(other);
    if (NIL_P(other))
	return Qfalse;
    GetBN(other, bn2);

    if (!BN_cmp(bn1, bn2)) {
	return Qtrue;
    }
    return Qfalse;
}

/*
 *  call-seq:
 *     bn.eql?(obj) => true or false
 *
 *  Returns <code>true</code> only if <i>obj</i> is a
 *  <code>OpenSSL::BN</code> with the same value as <i>bn</i>. Contrast this
 *  with OpenSSL::BN#==, which performs type conversions.
 */
static VALUE
ossl_bn_eql(VALUE self, VALUE other)
{
    BIGNUM *bn1, *bn2;

    if (!rb_obj_is_kind_of(other, cBN))
	return Qfalse;
    GetBN(self, bn1);
    GetBN(other, bn2);

    return BN_cmp(bn1, bn2) ? Qfalse : Qtrue;
}

/*
 *  call-seq:
 *     bn.hash => Integer
 *
 *  Returns a hash code for this object.
 *
 *  See also Object#hash.
 */
static VALUE
ossl_bn_hash(VALUE self)
{
    BIGNUM *bn;
    VALUE tmp, hash;
    unsigned char *buf;
    int len;

    GetBN(self, bn);
    len = BN_num_bytes(bn);
    buf = ALLOCV(tmp, len);
    if (BN_bn2bin(bn, buf) != len) {
	ALLOCV_END(tmp);
	ossl_raise(eBNError, "BN_bn2bin");
    }

    hash = ST2FIX(rb_memhash(buf, len));
    ALLOCV_END(tmp);

    return hash;
}

/*
 * call-seq:
 *    bn.prime? => true | false
 *    bn.prime?(checks) => true | false
 *
 * Performs a Miller-Rabin probabilistic primality test with _checks_
 * iterations. If _checks_ is not specified, a number of iterations is used
 * that yields a false positive rate of at most 2^-80 for random input.
 *
 * === Parameters
 * * _checks_ - integer
 */
static VALUE
ossl_bn_is_prime(int argc, VALUE *argv, VALUE self)
{
    BIGNUM *bn;
    VALUE vchecks;
    int checks = BN_prime_checks;

    if (rb_scan_args(argc, argv, "01", &vchecks) == 1) {
	checks = NUM2INT(vchecks);
    }
    GetBN(self, bn);
    switch (BN_is_prime_ex(bn, checks, ossl_bn_ctx, NULL)) {
    case 1:
	return Qtrue;
    case 0:
	return Qfalse;
    default:
	ossl_raise(eBNError, NULL);
    }
    /* not reachable */
    return Qnil;
}

/*
 * call-seq:
 *    bn.prime_fasttest? => true | false
 *    bn.prime_fasttest?(checks) => true | false
 *    bn.prime_fasttest?(checks, trial_div) => true | false
 *
 * Performs a Miller-Rabin primality test. This is same as #prime? except this
 * first attempts trial divisions with some small primes.
 *
 * === Parameters
 * * _checks_ - integer
 * * _trial_div_ - boolean
 */
static VALUE
ossl_bn_is_prime_fasttest(int argc, VALUE *argv, VALUE self)
{
    BIGNUM *bn;
    VALUE vchecks, vtrivdiv;
    int checks = BN_prime_checks, do_trial_division = 1;

    rb_scan_args(argc, argv, "02", &vchecks, &vtrivdiv);

    if (!NIL_P(vchecks)) {
	checks = NUM2INT(vchecks);
    }
    GetBN(self, bn);
    /* handle true/false */
    if (vtrivdiv == Qfalse) {
	do_trial_division = 0;
    }
    switch (BN_is_prime_fasttest_ex(bn, checks, ossl_bn_ctx, do_trial_division, NULL)) {
    case 1:
	return Qtrue;
    case 0:
	return Qfalse;
    default:
	ossl_raise(eBNError, NULL);
    }
    /* not reachable */
    return Qnil;
}

/*
 * call-seq:
 *    bn.get_flags(flags) => flags
 *
 * Returns the flags on the BN object.
 * The argument is used as a bit mask.
 *
 * === Parameters
 * * _flags_ - integer
 */
static VALUE
ossl_bn_get_flags(VALUE self, VALUE arg)
{
    BIGNUM *bn;
    GetBN(self, bn);

    return INT2NUM(BN_get_flags(bn, NUM2INT(arg)));
}

/*
 * call-seq:
 *    bn.set_flags(flags) => nil
 *
 * Enables the flags on the BN object.
 * Currently, the flags argument can contain zero of OpenSSL::BN::CONSTTIME.
 */
static VALUE
ossl_bn_set_flags(VALUE self, VALUE arg)
{
    BIGNUM *bn;
    GetBN(self, bn);

    BN_set_flags(bn, NUM2INT(arg));
    return Qnil;
}

/*
 * INIT
 * (NOTE: ordering of methods is the same as in 'man bn')
 */
void
Init_ossl_bn(void)
{
#if 0
    mOSSL = rb_define_module("OpenSSL");
    eOSSLError = rb_define_class_under(mOSSL, "OpenSSLError", rb_eStandardError);
#endif

#ifdef HAVE_RB_EXT_RACTOR_SAFE
    ossl_bn_ctx_key = rb_ractor_local_storage_ptr_newkey(&ossl_bn_ctx_key_type);
#else
    ossl_bn_ctx_get();
#endif

    eBNError = rb_define_class_under(mOSSL, "BNError", eOSSLError);

    cBN = rb_define_class_under(mOSSL, "BN", rb_cObject);

    rb_define_alloc_func(cBN, ossl_bn_alloc);
    rb_define_method(cBN, "initialize", ossl_bn_initialize, -1);

    rb_define_method(cBN, "initialize_copy", ossl_bn_copy, 1);
    rb_define_method(cBN, "copy", ossl_bn_copy, 1);

    /* swap (=coerce?) */

    rb_define_method(cBN, "num_bytes", ossl_bn_num_bytes, 0);
    rb_define_method(cBN, "num_bits", ossl_bn_num_bits, 0);
    /* num_bits_word */

    rb_define_method(cBN, "+@", ossl_bn_uplus, 0);
    rb_define_method(cBN, "-@", ossl_bn_uminus, 0);
    rb_define_method(cBN, "abs", ossl_bn_abs, 0);

    rb_define_method(cBN, "+", ossl_bn_add, 1);
    rb_define_method(cBN, "-", ossl_bn_sub, 1);
    rb_define_method(cBN, "*", ossl_bn_mul, 1);
    rb_define_method(cBN, "sqr", ossl_bn_sqr, 0);
    rb_define_method(cBN, "/", ossl_bn_div, 1);
    rb_define_method(cBN, "%", ossl_bn_mod, 1);
    /* nnmod */

    rb_define_method(cBN, "mod_add", ossl_bn_mod_add, 2);
    rb_define_method(cBN, "mod_sub", ossl_bn_mod_sub, 2);
    rb_define_method(cBN, "mod_mul", ossl_bn_mod_mul, 2);
    rb_define_method(cBN, "mod_sqr", ossl_bn_mod_sqr, 1);
    rb_define_method(cBN, "**", ossl_bn_exp, 1);
    rb_define_method(cBN, "mod_exp", ossl_bn_mod_exp, 2);
    rb_define_method(cBN, "gcd", ossl_bn_gcd, 1);

    /* add_word
     * sub_word
     * mul_word
     * div_word
     * mod_word */

    rb_define_method(cBN, "cmp", ossl_bn_cmp, 1);
    rb_define_alias(cBN, "<=>", "cmp");
    rb_define_method(cBN, "ucmp", ossl_bn_ucmp, 1);
    rb_define_method(cBN, "eql?", ossl_bn_eql, 1);
    rb_define_method(cBN, "hash", ossl_bn_hash, 0);
    rb_define_method(cBN, "==", ossl_bn_eq, 1);
    rb_define_alias(cBN, "===", "==");
    rb_define_method(cBN, "zero?", ossl_bn_is_zero, 0);
    rb_define_method(cBN, "one?", ossl_bn_is_one, 0);
    /* is_word */
    rb_define_method(cBN, "odd?", ossl_bn_is_odd, 0);
    rb_define_method(cBN, "negative?", ossl_bn_is_negative, 0);

    /* zero
     * one
     * value_one - DON'T IMPL.
     * set_word
     * get_word */

    rb_define_singleton_method(cBN, "rand", ossl_bn_s_rand, -1);
    rb_define_singleton_method(cBN, "pseudo_rand", ossl_bn_s_pseudo_rand, -1);
    rb_define_singleton_method(cBN, "rand_range", ossl_bn_s_rand_range, 1);
    rb_define_singleton_method(cBN, "pseudo_rand_range", ossl_bn_s_pseudo_rand_range, 1);

    rb_define_singleton_method(cBN, "generate_prime", ossl_bn_s_generate_prime, -1);
    rb_define_method(cBN, "prime?", ossl_bn_is_prime, -1);
    rb_define_method(cBN, "prime_fasttest?", ossl_bn_is_prime_fasttest, -1);

    rb_define_method(cBN, "set_bit!", ossl_bn_set_bit, 1);
    rb_define_method(cBN, "clear_bit!", ossl_bn_clear_bit, 1);
    rb_define_method(cBN, "bit_set?", ossl_bn_is_bit_set, 1);
    rb_define_method(cBN, "mask_bits!", ossl_bn_mask_bits, 1);
    rb_define_method(cBN, "<<", ossl_bn_lshift, 1);
    rb_define_method(cBN, ">>", ossl_bn_rshift, 1);
    rb_define_method(cBN, "lshift!", ossl_bn_self_lshift, 1);
    rb_define_method(cBN, "rshift!", ossl_bn_self_rshift, 1);
    /* lshift1 - DON'T IMPL. */
    /* rshift1 - DON'T IMPL. */

    rb_define_method(cBN, "get_flags", ossl_bn_get_flags, 1);
    rb_define_method(cBN, "set_flags", ossl_bn_set_flags, 1);

#ifdef BN_FLG_CONSTTIME
    rb_define_const(cBN, "CONSTTIME", INT2NUM(BN_FLG_CONSTTIME));
#endif
    /* BN_FLG_MALLOCED and BN_FLG_STATIC_DATA seems for C programming.
     * Allowing them leads to memory leak.
     * So, for now, they are not exported
#ifdef BN_FLG_MALLOCED
    rb_define_const(cBN, "MALLOCED", INT2NUM(BN_FLG_MALLOCED));
#endif
#ifdef BN_FLG_STATIC_DATA
    rb_define_const(cBN, "STATIC_DATA", INT2NUM(BN_FLG_STATIC_DATA));
#endif
    */

    /*
     * bn2bin
     * bin2bn
     * bn2hex
     * bn2dec
     * hex2bn
     * dec2bn - all these are implemented in ossl_bn_initialize, and ossl_bn_to_s
     * print - NOT IMPL.
     * print_fp - NOT IMPL.
     * bn2mpi
     * mpi2bn
     */
    rb_define_method(cBN, "to_s", ossl_bn_to_s, -1);
    rb_define_method(cBN, "to_i", ossl_bn_to_i, 0);
    rb_define_alias(cBN, "to_int", "to_i");
    rb_define_method(cBN, "to_bn", ossl_bn_to_bn, 0);
    rb_define_method(cBN, "coerce", ossl_bn_coerce, 1);

    /*
     * TODO:
     * But how to: from_bin, from_mpi? PACK?
     * to_bin
     * to_mpi
     */

    rb_define_method(cBN, "mod_inverse", ossl_bn_mod_inverse, 1);

    /* RECiProcal
     * MONTgomery */
}