Skip to content

Commit

Permalink
Merge pull request #553 from btoews/ossl_bn_mod_sqrt
Browse files Browse the repository at this point in the history
Add BN#mod_sqrt
  • Loading branch information
rhenium committed Oct 17, 2022
2 parents e25de6b + 5befde7 commit 1ddbf28
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 12 deletions.
36 changes: 24 additions & 12 deletions ext/openssl/ossl_bn.c
Expand Up @@ -577,22 +577,33 @@ BIGNUM_2c(gcd)
*/
BIGNUM_2c(mod_sqr)

#define BIGNUM_2cr(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_##func(NULL, bn1, bn2, ossl_bn_ctx))) \
ossl_raise(eBNError, NULL); \
SetBN(obj, result); \
return obj; \
}

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

/*
* Document-method: OpenSSL::BN#mod_inverse
* 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;
}
BIGNUM_2cr(mod_inverse)

/*
* call-seq:
Expand Down Expand Up @@ -1234,6 +1245,7 @@ Init_ossl_bn(void)
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, "mod_sqrt", ossl_bn_mod_sqrt, 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);
Expand Down
6 changes: 6 additions & 0 deletions test/openssl/test_bn.rb
Expand Up @@ -174,6 +174,12 @@ def test_mod_sqr
assert_equal(0, 59.to_bn.mod_sqr(59))
end

def test_mod_sqrt
assert_equal(3, 4.to_bn.mod_sqrt(5))
assert_equal(0, 5.to_bn.mod_sqrt(5))
assert_raise(OpenSSL::BNError) { 3.to_bn.mod_sqrt(5) }
end

def test_mod_inverse
assert_equal(2, 3.to_bn.mod_inverse(5))
assert_raise(OpenSSL::BNError) { 3.to_bn.mod_inverse(6) }
Expand Down

0 comments on commit 1ddbf28

Please sign in to comment.