Feature #8217

OpenSSL::BN.new with integers

Added by Yui NARUSE about 1 year ago. Updated 12 months ago.

[ruby-core:53986]
Status:Closed
Priority:Normal
Assignee:Martin Bosslet
Category:-
Target version:next minor

Description

Current OpenSSL::BN.new gets only strings, so users must do integer.to_s, it costs extra resource.
Therefore I propose OpenSSL::BN.new to allow Fixnu/Bignum.

diff --git a/ext/openssl/osslbn.c b/ext/openssl/osslbn.c
index 1038135..1f1ebba 100644
--- a/ext/openssl/osslbn.c
+++ b/ext/openssl/ossl
bn.c
@@ -120,6 +120,44 @@ osslbninitialize(int argc, VALUE *argv, VALUE self)
base = NUM2INT(bs);
}

  • if (RBTYPEP(str, T_FIXNUM)) {
  • long i;
  • unsigned char bin = (unsigned char)ALLOC_N(long, 1);
  • long n = FIX2LONG(str);
  • unsigned long un = abs(n); +
  • for (i = sizeof(VALUE) - 1; 0 <= i; i--) {
  • bin[i] = un&0xff;
  • un >>= 8;
  • } +
  • GetBN(self, bn);
  • if (!BN_bin2bn(bin, sizeof(long), bn)) {
  • ossl_raise(eBNError, NULL);
  • }
  • if (n < 0) BNsetnegative(bn, 1);
  • return self;
  • }
  • else if (RBTYPEP(str, T_BIGNUM)) {
  • long i, j;
  • BDIGIT *ds = RBIGNUM_DIGITS(str);
  • unsigned char bin = (unsigned char)ALLOCN(BDIGIT, RBIGNUMLEN(str)); +
  • for (i = 0; RBIGNUM_LEN(str) > i; i++) {
  • BDIGIT v = ds[i];
  • for (j = sizeof(BDIGIT) - 1; 0 <= j; j--) {
  • bin[(RBIGNUM_LEN(str)-1-i)*sizeof(BDIGIT)+j] = v&0xff;
  • v >>= 8;
  • }
  • } +
  • GetBN(self, bn);
  • if (!BNbin2bn(bin, sizeof(BDIGIT)*RBIGNUMLEN(str), bn)) {
  • ossl_raise(eBNError, NULL);
  • }
  • if (!RBIGNUMSIGN(str)) BNset_negative(bn, 1);
  • return self;
  • } if (RTEST(rbobjiskindof(str, cBN))) { BIGNUM *other;

diff --git a/test/openssl/testbn.rb b/test/openssl/testbn.rb
index af1c72c..758cc54 100644
--- a/test/openssl/testbn.rb
+++ b/test/openssl/test
bn.rb
@@ -8,6 +8,13 @@ class OpenSSL::TestBN < Test::Unit::TestCase
end

def testintegertobn
+ assert
equal(999.tobn, OpenSSL::BN.new(999))
+ assert
equal((2 ** 107 - 1).tobn, OpenSSL::BN.new(2 ** 107 - 1))
+ assert
equal(-999.tobn, OpenSSL::BN.new(-999))
+ assert
equal((-(2 ** 107 - 1)).tobn, OpenSSL::BN.new(-(2 ** 107 - 1)))
+ end
+
+ def test
integerstrtobn
assert
equal(999.tobn, OpenSSL::BN.new(999.tos(16), 16))
assertequal((2 ** 107 - 1).tobn, OpenSSL::BN.new((2 ** 107 - 1).to_s(16), 16))
end

Associated revisions

Revision 40461
Added by Yui NARUSE 12 months ago

  • ext/openssl/osslbn.c (osslbn_initialize): allow Fixnum and Bignum. [Feature #8217]

History

#1 Updated by Yui NARUSE 12 months ago

  • Status changed from Assigned to Closed
  • % Done changed from 0 to 100

This issue was solved with changeset r40461.
Yui, thank you for reporting this issue.
Your contribution to Ruby is greatly appreciated.
May Ruby be with you.


  • ext/openssl/osslbn.c (osslbn_initialize): allow Fixnum and Bignum. [Feature #8217]

Also available in: Atom PDF