Forum: Ruby a simple RSA

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Shannon F. (Guest)
on 2006-04-17 22:05
(Received via mailing list)
Hi All,

I tried to implement a simple RSA crypto for my work. It seems all works
fine, except that I am not satisfied with the code I wrote below:

def str_to_num(s)
  h = '0x'
  (0...s.length).each do |i|
    h += "%02x" % s[i]
  end
  eval(h)
end

def num_to_str(n)
  s = ''
  while n > 0 do
    s = "%c" % (n & 0xFF) + s
    n = n >> 8
  end
  s
end

These 2 functions convert string to bignum and vise-versa. It works, but
I
feel there should be better (faster) way to do this.

Could anyone point the way out?

Thanks!
Shannon
Sergey (Guest)
on 2006-04-18 01:20
(Received via mailing list)
Please see attached:
- samples with unpack/inject and each_byte use in str_to_num;
  each_byte is faster;
- num_to_str without use of formatting;
- unit test stuff and
- benchmark code

hope these help
regards
Sergey

----- Original Message -----
Shannon F. (Guest)
on 2006-04-18 07:21
(Received via mailing list)
Thanks a lot, this works fine.

BTW, another related question: while I ruby code, I can write a long
string
like: (without using heredoc)

str = "this is very long line 1" +
        "this is line 2"

but if I write a number:

num = 0x1234132410987094750245.....

And the number is very long (an RSA key), how can I wrap the line? it
seems
that I cannot use a "\" by the end of line...

Thanks!
Shannon

>- unit test stuff and
>>I tried to implement a simple RSA crypto for my work. It seems all works
>>def num_to_str(n)
>>
>>Could anyone point the way out?
>>
>>Thanks!
>>Shannon
unknown (Guest)
on 2006-04-18 07:39
(Received via mailing list)
On Tue, 18 Apr 2006, Shannon F. wrote:

> num = 0x1234132410987094750245.....
>
> And the number is very long (an RSA key), how can I wrap the line? it seems
> that I cannot use a "\" by the end of line...
>
> Thanks!
> Shannon

   harp:~ > cat a.rb
   num = %w(
     1234132410987094750245
     1234132410987094750245
     1234132410987094750245
   ).join.to_i

   p num


   harp:~ > ruby a.rb
   123413241098709475024512341324109870947502451234132410987094750245


-a
This topic is locked and can not be replied to.