C# random alphanumeric strings ?

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

    C# random alphanumeric strings ?

    Anyone got an example ?


  • Tom Spink

    #2
    Re: C# random alphanumeric strings ?

    bitshift wrote:
    Anyone got an example ?
    asdxcgfd

    --
    Tom Spink
    University of Edinburgh

    Comment

    • Jon Skeet [C# MVP]

      #3
      Re: C# random alphanumeric strings ?

      On Jul 2, 3:12 pm, "bitshift" <j...@aol.comwr ote:
      Anyone got an example ?
      1) Hard-code a string with all the characters you want to include
      2) Use a single instance of Random (with appropriate locking if you're
      going to use it from many threads)
      3) Create a StringBuilder of the right length
      4) In a for loop, append the next random character by using
      Random.Next, passing in the string's length, and using string's
      indexer
      5) Call ToString on the StringBuilder

      Jon

      Comment

      • Tom Spink

        #4
        Re: C# random alphanumeric strings ?

        Jon Skeet [C# MVP] wrote:
        On Jul 2, 3:12 pm, "bitshift" <j...@aol.comwr ote:
        >Anyone got an example ?
        >
        1) Hard-code a string with all the characters you want to include
        2) Use a single instance of Random (with appropriate locking if you're
        going to use it from many threads)
        3) Create a StringBuilder of the right length
        4) In a for loop, append the next random character by using
        Random.Next, passing in the string's length, and using string's
        indexer
        5) Call ToString on the StringBuilder
        >
        Jon
        Hi Jon,

        Great minds think alike.

        --
        Tom Spink
        University of Edinburgh

        Comment

        • Tom Spink

          #5
          Re: C# random alphanumeric strings ?

          bitshift wrote:
          Anyone got an example ?
          Also,

          ///
          using System;
          using System.Text;

          ....

          public string GetRandomString (Random rnd, int length)
          {
          string charPool
          = "ABCDEFGHIJKLMN OPQRSTUVWXYZabc defghijklmnopqr stuvwxyz1234567 890";
          StringBuilder rs = new StringBuilder() ;

          while (length-- 0)
          rs.Append(charP ool[(int)(rnd.NextD ouble() * charPool.Length )]);

          return rs.ToString();
          }
          ///

          Watch out for wrapping on the charPool line! Note, the method takes an
          instance of the Random class, which you can instantiate with new Random().

          The reason it doesn't do this itself is that (I think) the Random class uses
          a timer as it's entropy source, and if you try to generate a large sequence
          of random numbers quickly, the seeds will match and you'll get matching
          random sequences.

          So the way I tested this was:

          ///
          public static void Main ()
          {
          int i = 50;
          Random rnd = new Random();
          while (i-- 0)
          Console.WriteLi ne(GetRandomStr ing(rnd, 10));
          }
          ///

          --
          Tom Spink
          University of Edinburgh

          Comment

          • tomk148@gmail.com

            #6
            Re: C# random alphanumeric strings ?

            Great minds think alike.

            similar ones at least

            Comment

            • =?Utf-8?B?UGV0ZXIgQnJvbWJlcmcgW0MjIE1WUF0=?=

              #7
              RE: C# random alphanumeric strings ?

              Here is some code that will generate a cryptograhicall y random unique string
              of any length you want:

              using System.Security .Cryptography;
              using System.Text;

              namespace UniqueKey
              {
              public class KeyGenerator
              {
              public static string GetUniqueKey(in t maxSize)
              {
              char[] chars = new char[62];
              chars =
              "abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
              byte[] data = new byte[1];
              RNGCryptoServic eProvider crypto = new RNGCryptoServic eProvider();
              crypto.GetNonZe roBytes(data);
              data = new byte[maxSize];
              crypto.GetNonZe roBytes(data);
              StringBuilder result = new StringBuilder(m axSize);
              foreach (byte b in data)
              {
              result.Append(c hars[b%(chars.Length - 1)]);
              }
              return result.ToString ();
              }
              }
              }

              -- Peter
              Site: http://www.eggheadcafe.com
              UnBlog: http://petesbloggerama.blogspot.com
              BlogMetaFinder( BETA): http://www.blogmetafinder.com



              "bitshift" wrote:
              Anyone got an example ?
              >
              >
              >

              Comment

              • rossum

                #8
                Re: C# random alphanumeric strings ?

                On Mon, 2 Jul 2007 09:12:40 -0500, "bitshift" <jobob@aol.comw rote:
                >Anyone got an example ?
                >
                Two questions:

                - do you want characters in the string to repeat or not?
                - is the output going to be used for cryptographic/security purposes?

                rossum

                Comment

                • =?ISO-8859-1?Q?Arne_Vajh=F8j?=

                  #9
                  Re: C# random alphanumeric strings ?

                  bitshift wrote:
                  Anyone got an example ?
                  private static Random rng = new Random();
                  public static string newPassword(int l)
                  {
                  char[] valid = { 'A', 'B', 'C', '2', '3', '4' };
                  StringBuilder sb = new StringBuilder(" ");
                  for(int i = 0; i < l; i++)
                  {
                  sb.Append(valid[rng.Next(valid. Length)]);
                  }
                  return sb.ToString();
                  }

                  Arne

                  Comment

                  • =?UTF-8?B?QXJuZSBWYWpow7hq?=

                    #10
                    Re: C# random alphanumeric strings ?

                    Peter Bromberg [C# MVP] wrote:
                    char[] chars = new char[62];
                    chars =
                    "abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
                    Why the new char[62] ?

                    Arne

                    Comment

                    • =?Utf-8?B?TWlsb3N6IFNrYWxlY2tpIFtNQ0FEXQ==?=

                      #11
                      Re: C# random alphanumeric strings ?

                      :-)
                      --
                      Milosz


                      "Tom Spink" wrote:
                      bitshift wrote:
                      >
                      Anyone got an example ?
                      >
                      asdxcgfd
                      >
                      --
                      Tom Spink
                      University of Edinburgh
                      >

                      Comment

                      • =?Utf-8?B?UGV0ZXIgQnJvbWJlcmcgW0MjIE1WUF0=?=

                        #12
                        Re: C# random alphanumeric strings ?

                        I suppose you could do it this way if you prefer:
                        char[] chars =
                        "abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();

                        Actually, there are 64 characters in the string. Good catch.

                        -- Peter
                        Site: http://www.eggheadcafe.com
                        UnBlog: http://petesbloggerama.blogspot.com
                        BlogMetaFinder( BETA): http://www.blogmetafinder.com



                        "Arne Vajhøj" wrote:
                        Peter Bromberg [C# MVP] wrote:
                        char[] chars = new char[62];
                        chars =
                        "abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
                        >
                        Why the new char[62] ?
                        >
                        Arne
                        >

                        Comment

                        • =?Utf-8?B?UGV0ZXIgQnJvbWJlcmcgW0MjIE1WUF0=?=

                          #13
                          Re: C# random alphanumeric strings ?

                          whoops, my bad. There are indeed 62 characters in the string.
                          -- Peter
                          Site: http://www.eggheadcafe.com
                          UnBlog: http://petesbloggerama.blogspot.com
                          BlogMetaFinder( BETA): http://www.blogmetafinder.com



                          "Arne Vajhøj" wrote:
                          Peter Bromberg [C# MVP] wrote:
                          char[] chars = new char[62];
                          chars =
                          "abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
                          >
                          Why the new char[62] ?
                          >
                          Arne
                          >

                          Comment

                          • Peter Duniho

                            #14
                            Re: C# random alphanumeric strings ?

                            On Tue, 03 Jul 2007 06:26:01 -0700, Peter Bromberg [C# MVP]
                            <pbromberg@yaho o.yabbadabbadoo .comwrote:
                            I suppose you could do it this way if you prefer:
                            char[] chars =
                            "abcdefghijklmn opqrstuvwxyzABC DEFGHIJKLMNOPQR STUVWXYZ1234567 890".ToCharArra y();
                            I think the point is, why _wouldn't_ you prefer to do it that way?

                            Creating an empty 62-element array doesn't seem useful. That char[]
                            instance just gets thrown away when the subsequent assignment is made. So
                            why do it at all?

                            I could be missing something, but it seems to me that that line of code is
                            just superfluous.

                            Pete

                            Comment

                            • =?UTF-8?B?QXJuZSBWYWpow7hq?=

                              #15
                              Re: C# random alphanumeric strings ?

                              Peter Bromberg [C# MVP] wrote:
                              "Arne Vajhøj" wrote:
                              >Peter Bromberg [C# MVP] wrote:
                              >> char[] chars = new char[62];
                              >> chars =
                              >>"abcdefghijkl mnopqrstuvwxyzA BCDEFGHIJKLMNOP QRSTUVWXYZ12345 67890".ToCharAr ray();
                              >Why the new char[62] ?
                              whoops, my bad. There are indeed 62 characters in the string.
                              It does not matter. The only difference is whether 62 or
                              64 chars get GC'ed.

                              Arne

                              Comment

                              Working...