A simple RSA

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

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 -----

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

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