Gets an Alphanumeric Key of the provided length. - CSharp System

CSharp examples for System:Math Number

Description

Gets an Alphanumeric Key of the provided length.

Demo Code

/* *******************************************************************************
 * Copyright (c) 2005-2012 Zibler S de RL MI.
 * /*w w w  . j a va2 s  .c o  m*/
 * This file is part of Zibler.
 * 
 * Zibler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Zibler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Zibler.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * *******************************************************************************/
using System.Threading;
using System.Text;
using System.Security.Cryptography;
using System;

public class Main{
        /// <summary>
        /// Gets an Alphanumeric Key of the provided length.
        /// This key is almost unique. You can get 2,000,000 
        /// keys without one being repeated. This is using 9 characters.
        /// </summary>        
        /// <returns>Key</returns>
        public static string GetDigitAlphaNumericKey (int length)
        {            
            int maxSize = length;
            char[] chars = new char[36];
            string a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            chars = a.ToCharArray ();
            int size = maxSize;
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider ();
            crypto.GetNonZeroBytes (data);
            size = maxSize;
            data = new byte[size];
            crypto.GetNonZeroBytes (data);
            StringBuilder result = new StringBuilder (size);
            foreach (byte b in data)
            {
                result.Append (chars[b % (chars.Length - 1)]);
            }

            /* This wait is just to try to minimize the chances of 
            * getting to identical values */
            Thread.Sleep (1);

            return result.ToString ();
        }
}

Related Tutorials