Cryptographically random numbers

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Tuvas

    Cryptographically random numbers

    Okay, I'm working on devoloping a simple, cryptographical ly secure
    number, from a range of numbers (As one might do for finding large
    numbers, to test if they are prime). My function looks like this:

    def cran_rand(min,m ax):
    if(min>max):
    x=max
    max=min
    min=x
    range=round(log (max-min)/log(256))
    if range==0:
    range=1
    num=max+1
    while(num>max):
    num=min+s2num(u random(range))
    return num

    Any comments on this? I think it should hold up to a test, it seems to
    work alright. Thanks!

  • Emile van Sebille

    #2
    Re: Cryptographical ly random numbers

    > def cran_rand(min,m ax):

    You're shadowing built-ins here. Not a problem, but something I'd generally
    avoid.

    [color=blue]
    > if(min>max):
    > x=max
    > max=min
    > min=x[/color]

    If the args were a,b you could say:

    maxarg,minarg = min(a,b),max(a, b)

    [color=blue]
    > range=round(log (max-min)/log(256))[/color]

    more builtin shadowing...
    [color=blue]
    > if range==0:
    > range=1[/color]

    or as alt_name_for_ra nge=... or 1
    [color=blue]
    > num=max+1
    > while(num>max):
    > num=min+s2num(u random(range))[/color]

    I'll assume os.urandom is urandom. What's s2num?
    [color=blue]
    > return num
    >
    > Any comments on this? I think it should hold up to a test, it seems to
    > work alright. Thanks!
    >[/color]


    If this does what you want, that's good. But someday when you look again
    and see

    while(num>max): num=min+s2num(u random(range))

    you'll wonder...

    Thankfully-python-uses-int-and-not-num-ly y'rs,

    Emile van Sebille
    emile@fenx.com







    Comment

    • Tuvas

      #3
      Re: Cryptographical ly random numbers

      Good idea about the max and min values. Yes, urandom is os.urandom.
      s2num('blah') will convert the phrase blah to ascii, and treat them as
      if they were a big function.

      Anyone else whose still interested, I found another small bug, but it
      was in the modular (Again). It won't do much, but...

      I did test out the RSA from end to end, found another small bug (I
      imputed the text luke, and it decrypted to ekul), but it works good
      now. Hopefully there's nothing left gaping, thanks for the help!

      Comment

      • Bryan Olson

        #4
        Re: Cryptographical ly random numbers

        Tuvas wrote:[color=blue]
        > Okay, I'm working on devoloping a simple, cryptographical ly secure
        > number, from a range of numbers (As one might do for finding large
        > numbers, to test if they are prime). My function looks like this:
        >
        > def cran_rand(min,m ax):
        > if(min>max):
        > x=max
        > max=min
        > min=x
        > range=round(log (max-min)/log(256))
        > if range==0:
        > range=1
        > num=max+1
        > while(num>max):
        > num=min+s2num(u random(range))
        > return num
        >
        > Any comments on this? I think it should hold up to a test, it seems to
        > work alright.[/color]

        Have to disagree. Try:

        for _ in range(100):
        print cran_rand(0, 500)

        How many numbers greater than 255 do you get?


        I have more comments, but that's the biggest issue.


        --
        --Bryan

        Comment

        • Tuvas

          #5
          Re: Cryptographical ly random numbers

          Ahh, you are correct, that is a large bug... How about this one?

          def s2num(text):
          if(len(text)==1 ):
          return ord(text)
          else:
          return ord(text[0])+256*s2num(tex t[1:])

          def cran_rand(min,m ax):
          range=int(log(a bs(max-min))/log(2))+1
          num=max+1
          if range%8==0:
          crange=range/8
          else:
          crange=range/8+1
          while(num>max):
          num=min+s2num(u random(crange)) %(2**range)
          return num

          Comment

          • Paul Rubin

            #6
            Re: Cryptographical ly random numbers

            "Tuvas" <tuvas21@gmail. com> writes:[color=blue]
            > def s2num(text):
            > if(len(text)==1 ):
            > return ord(text)
            > else:
            > return ord(text[0])+256*s2num(tex t[1:])[/color]

            My favorite way to convert strings to numbers is with binascii:
            from binascii import hexlify
            def s2num(text):
            return int(hexlify(tex t), 16)
            [color=blue]
            > def cran_rand(min,m ax):
            > range=int(log(a bs(max-min))/log(2))+1[/color]

            This is kind of ugly and I wonder if it's possible for roundoff error
            in the log function to make the answer off by 1, if max-min is very
            close to a power of 2.

            Comment

            • Bryan Olson

              #7
              Re: Cryptographical ly random numbers

              Paul Rubin wrote:[color=blue]
              > My favorite way to convert strings to numbers is with binascii:
              >
              > from binascii import hexlify
              > def s2num(text):
              > return int(hexlify(tex t), 16)[/color]


              Neat. I use the empty string as a binary representation of zero,
              which you can accommodate with:

              def s2num(text):
              return int(hexlify(tex t) or '0', 16)


              --
              --Bryan

              Comment

              • Tuvas

                #8
                Re: Cryptographical ly random numbers

                Wait, I now see that there is a native base 2 log in python, so I will
                just do that rather than my adhoc way. The reason for adding one is to
                make sure there isn't any problems if the log is, for instance, 2.2. It
                will always round up. It's better to have to try twice to make sure the
                number can have the max range than never use the top half, as the first
                version did... That changes the function to:

                def cran_rand(min,m ax):
                range=int(log(a bs(max-min),2))+1
                num=max+1
                if range%8==0:
                crange=range/8
                else:
                crange=range/8+1
                while(num>max):
                num=min+s2num(u random(crange)) %(2**range)
                return num

                As to the s2num(text), well, that looks really neat. Is there an easy
                way to do the reverse of that? Thanks!

                Comment

                • Paul Rubin

                  #9
                  Re: Cryptographical ly random numbers

                  "Tuvas" <tuvas21@gmail. com> writes:[color=blue]
                  > Wait, I now see that there is a native base 2 log in python, so I will
                  > just do that rather than my adhoc way. The reason for adding one is to
                  > make sure there isn't any problems if the log is, for instance, 2.2. It
                  > will always round up. It's better to have to try twice to make sure the
                  > number can have the max range than never use the top half, as the first
                  > version did... That changes the function to:[/color]

                  OK, if the log is one too high, you just have to do a few additional
                  retries.
                  [color=blue]
                  > As to the s2num(text), well, that looks really neat. Is there an easy
                  > way to do the reverse of that? Thanks![/color]

                  from binascii import unhexlify
                  def num2s(n):
                  s = '%X' % n
                  if len(s) % 2 == 1:
                  s = '0' + s # make sure length of hex string is even
                  return unhexlify(s)

                  Comment

                  • Bryan Olson

                    #10
                    Re: Cryptographical ly random numbers

                    Tuvas wrote:[color=blue]
                    > Ahh, you are correct, that is a large bug... How about this one?[/color]

                    Much better. Do note the comments from Emile van Sebille and Paul
                    Rubin. There are some minor style and efficiency points, but it
                    looks reasonable.

                    Incidentally, as of Python 2.4, the standard library offers
                    random.SystemRa ndom, which will generate integers in any desired
                    range using os.urandom as the entropy source.


                    --
                    --Bryan

                    Comment

                    • Tuvas

                      #11
                      Re: Cryptographical ly random numbers

                      Wow, that would have been nice to know... Oh well, I've already got the
                      function, might as well use it... I'm starting to learn alot more of
                      the standard libraries that exist for alot of the little functions. It
                      seems like every project I have I build a misc.py file that contains
                      several small, but useful functions, and quite often I discover there
                      is a system library function to do just that. Oh well. Still, I've gone
                      a long ways in my Python skills since I started 6 months ago:-)

                      Comment

                      • Bryan Olson

                        #12
                        Re: Cryptographical ly random numbers

                        Tuvas wrote:
                        [...][color=blue]
                        > As to the s2num(text), well, that looks really neat. Is there an easy
                        > way to do the reverse of that? Thanks![/color]

                        Easy? Well, you be the judge:

                        def num2string(n):
                        """ Pass a non-negative int or long n.
                        Returns a string with bytes holding the big-endian base-256
                        representation of n. Zero is represented by the empty string.
                        """
                        h = hex(n).lstrip(' 0x').rstrip('Ll ')
                        if len(h) % 2:
                        h = '0' + h
                        return unhexlify(h)



                        I did a little testing:

                        for i in xrange(300):
                        assert s2num(num2strin g(i)) == i
                        for i in xrange(1, 20):
                        for _ in xrange(100):
                        r = os.urandom(i)
                        assert num2string(s2nu m(r)) == r.lstrip(chr(0) )



                        --
                        --Bryan

                        Comment

                        • Tuvas

                          #13
                          Re: Cryptographical ly random numbers

                          Thanks for the function Paul, it works alot nicer than the one I had in
                          my program... Now, with all of this knowledge, I'm going to be brave
                          and try out everything with AES. It seems to be working alright, I'll
                          debug this more on my own than I did with my RSA code, which turned out
                          to be full of bugs... I know the program sends the blocks in the
                          reverse order that would be expected, but, well, I'll get there.
                          Cryptology is fun:-)

                          Comment

                          • Gervasio Bernal

                            #14
                            Re: Cryptographical ly random numbers

                            Bryan Olson wrote:[color=blue]
                            > Tuvas wrote:
                            >[color=green]
                            >>Ahh, you are correct, that is a large bug... How about this one?[/color]
                            >
                            >
                            > Much better. Do note the comments from Emile van Sebille and Paul
                            > Rubin. There are some minor style and efficiency points, but it
                            > looks reasonable.
                            >
                            > Incidentally, as of Python 2.4, the standard library offers
                            > random.SystemRa ndom, which will generate integers in any desired
                            > range using os.urandom as the entropy source.
                            >
                            >[/color]

                            How can I generate a random string containing digits, symbols and
                            letters? I will use this random string for the key of a cryptographic
                            algorithm.
                            Thanks

                            Comment

                            • Tuvas

                              #15
                              Re: Cryptographical ly random numbers

                              from os import urandom
                              def cstring(bytes):
                              ret=''
                              while(len(ret)< bytes):
                              c=os.urandom(1)
                              if c>'0' and c<'z':
                              ret=ret+c
                              return ret

                              That should do it, though I bet there might be a more efficient way. I
                              don't know if that's the set of characters you want to use, but... If
                              you want a better answer, you'd have to be more specific.

                              Comment

                              Working...