From: Sergey Date: 2006-04-18T06:19:07+09:00 Subject: Re: a simple RSA ------=_NextPart_000_0177_01C66243.0669DD90 Content-Type: text/plain; format=flowed; charset="Windows-1252"; reply-type=response Content-Transfer-Encoding: 7bit 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 ----- On Monday, April 17, 2006 2:03 PM, Shannon Fang wrote: > 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 ------=_NextPart_000_0177_01C66243.0669DD90 Content-Type: application/octet-stream; name="tStrToNum.rb" Content-Transfer-Encoding: quoted-printable Content-Disposition: attachment; filename="tStrToNum.rb" #!/bin/ruby -w=0A= =0A= def str_to_num str=0A= num =3D 0=0A= str.each_byte{ |b| num =3D (num<<8)|b }=0A= num=0A= end=0A= =0A= def str_u2_num str=0A= str.unpack( "C*" ).inject(0){ |v,c| (v<<8)|c }=0A= end=0A= =0A= def num_to_str num=0A= res =3D ''=0A= while num>0=0A= res << (num&0xFF).chr=0A= num >>=3D 8=0A= end=0A= res.reverse!=0A= end=0A= =0A= if $0 =3D=3D __FILE__=0A= require 'test/unit'=0A= SL128 =3D (0..127).inject(''){ |v,e| v< ruby -w ./tStrToNum.rb=0A= Loaded suite TC=0A= Started=0A= ....=0A= Finished in 7.218 seconds.=0A= =0A= 4 tests, 131083 assertions, 0 failures, 0 errors=0A= =3D=3D=3D Benchmark string_to_num=0A= user system total real=0A= * |String|=3D3, repeat: 1000000=0A= unpack: 3.750000 0.000000 3.750000 ( 3.797000)=0A= str_to_num: 3.797000 0.000000 3.797000 ( 3.828000)=0A= num_to_str: 1.547000 0.000000 1.547000 ( 1.594000)=0A= * |String|=3D10, repeat: 100000=0A= unpack: 3.797000 0.000000 3.797000 ( 3.844000)=0A= str_to_num: 3.812000 0.000000 3.812000 ( 3.890000)=0A= num_to_str: 0.172000 0.000000 0.172000 ( 0.204000)=0A= * |String|=3D512, repeat: 1000=0A= unpack: 3.109000 0.000000 3.109000 ( 3.171000)=0A= str_to_num: 3.078000 0.000000 3.078000 ( 3.172000)=0A= num_to_str: 0.016000 0.000000 0.016000 ( 0.016000)=0A= * |String|=3D51200, repeat: 1=0A= unpack: 4.656000 0.031000 4.687000 ( 4.734000)=0A= str_to_num: 4.407000 0.016000 4.423000 ( 4.500000)=0A= num_to_str: 0.000000 0.000000 0.000000 ( 0.000000)=0A= =3Dend=0A= ------=_NextPart_000_0177_01C66243.0669DD90--