コード例 #1
0
 public static SqlString GenerateSalt(int length)
 {
     byte[] array = new byte[length];
     RNGCryptoServiceProvider rNGCryptoServiceProvider = new RNGCryptoServiceProvider();
     rNGCryptoServiceProvider.GetBytes(array);
     return new SqlString(Convert.ToBase64String(array));
 }
コード例 #2
0
ファイル: Random.aspx.cs プロジェクト: caixiaodou/GKing
    /// <summary>
    /// 高斯密钥 获取 伪随机数种子
    /// 从而确保伪随机数的随机性
    /// </summary>
    /// <returns></returns>
    private int GetSeed()
    {
        byte[] bytes = new byte[4];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(bytes);

        return BitConverter.ToInt32(bytes, 0);
    }
コード例 #3
0
 public string CreateSalt(int size)
 {
     size = 5;
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] buff = new byte[size];
     rng.GetBytes(buff);
     return Convert.ToBase64String(buff);
 }
コード例 #4
0
 internal static byte[] GenerateSaltInternal(int byteLength = SaltSize)
 {
     byte[] buf = new byte[byteLength];
     using (var rng = new RNGCryptoServiceProvider())
     {
         rng.GetBytes(buf);
     }
     return buf;
 }
コード例 #5
0
ファイル: Crypto.cs プロジェクト: Akashhhhh/UIU_HRM
        public static string GenerateSalt(int byteLength = SaltSize)
        {
            byte[] Buff = new byte[byteLength];
            using (var Prng = new RNGCryptoServiceProvider())
            {
                Prng.GetBytes(Buff);
            }

            return Convert.ToBase64String(Buff);
        }
コード例 #6
0
ファイル: Security.cs プロジェクト: kkzz19/WebLink
    public static string CreateSalt(int size)
    {
        //Generate a cryptographic random number.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);

        // Return a Base64 string representation of the random number.
        return Convert.ToBase64String(buff);
    }
コード例 #7
0
    public static string CreateHash(string password)
    {
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTE_SIZE];
        csprng.GetBytes(salt);

        byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
        return PBKDF2_ITERATIONS + ":" +
            Convert.ToBase64String(salt) + ":" +
            Convert.ToBase64String(hash);
    }
コード例 #8
0
ファイル: GenX.cs プロジェクト: PROShiZ/FilesLoaderBuilder
 public static string GenerateIdentifier(int length)
 {
     char[] identifier = new char[length];
     byte[] randomData = new byte[length];
     using (var rng = new RNGCryptoServiceProvider()) rng?.GetBytes(randomData);
     for (int idx = 0; idx < identifier.Length; idx++)
     {
         identifier[idx] = AvailableCharacters[randomData[idx] % AvailableCharacters.Length];
     }
     return(new string(identifier));
 }
コード例 #9
0
    public static string CreateSalt(int size)
    {
        // Taken from: http://stackoverflow.com/questions/2138429/hash-and-salt-passwords-in-c-sharp

        //Generate a cryptographic random number.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        byte[] buff = new byte[size];
        rng.GetBytes(buff);

        // Return a Base64 string representation of the random number.
        return Convert.ToBase64String(buff);
    }
コード例 #10
0
ファイル: Encrypt.cs プロジェクト: naynishchaughule/ASP.NET
 public static string CreateMachineKey(int length)
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] random = new byte[length/2]; 
     rng.GetBytes(random);
     StringBuilder machineKey = new StringBuilder(length);
     for (int i = 0; i < random.Length; i++)
     {
         machineKey.Append(String.Format("{0:X2}", random[i]));
     }
     return machineKey.ToString();
 }
コード例 #11
0
        public static void DifferentSequential_10()
        {
            // Ensure that the RNG doesn't produce a stable set of data.
            byte[] first = new byte[10];
            byte[] second = new byte[10];

            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(first);
                rng.GetBytes(second);
            }

            // Random being random, there is a chance that it could produce the same sequence.
            // The smallest test case that we have is 10 bytes.
            // The probability that they are the same, given a Truly Random Number Generator is:
            // Pmatch(byte0) * Pmatch(byte1) * Pmatch(byte2) * ... * Pmatch(byte9)
            // = 1/256 * 1/256 * ... * 1/256
            // = 1/(256^10)
            // = 1/1,208,925,819,614,629,174,706,176
            Assert.NotEqual(first, second);
        }
コード例 #12
0
ファイル: AF.cs プロジェクト: radiopaedia/uploader-agent
    /// <summary>
    /// Creates a salted PBKDF2 hash of the password.
    /// </summary>
    /// <param name="password">The password to hash.</param>
    /// <returns>The hash of the password.</returns>
    public static string CreateHash(string password)
    {
        // Generate a random salt
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTE_SIZE];
        csprng.GetBytes(salt);

        // Hash the password and encode the parameters
        byte[] hash = PBKDF2(password, salt, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
        return PBKDF2_ITERATIONS + ":" +
            Convert.ToBase64String(salt) + ":" +
            Convert.ToBase64String(hash);
    }
コード例 #13
0
ファイル: GenString.cs プロジェクト: x1234xx/R3BinderNSIS
        public static string Inizialize(int buffer)
        {
            string result = string.Empty;

            try
            {
                using var rnd = new RNGCryptoServiceProvider();
                var buf = new byte[buffer];
                rnd?.GetBytes(buf);
                result = Convert.ToBase64String(buf);
            }
            catch { }
            return(result);
        }
 IList<GameObject> Shuffle(IList<GameObject> list)
 {
     RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();
     int n = list.Count;
     while (n > 1)
     {
         byte[] box = new byte[1];
         do provider.GetBytes(box);
         while (!(box[0] < n * (Byte.MaxValue / n)));
         int k = (box[0] % n);
         n--;
         GameObject value = list[k];
         list[k] = list[n];
         list[n] = value;
     }
     return list;
 }
コード例 #15
0
            /**
             * This function generates random string of the given input length.
             *
             * @param _plainText
             *            Plain text to be encrypted
             * @param _key
             *            Encryption Key. You'll have to use the same key for decryption
             * @return returns encrypted (cipher) text
             */
            internal static string GenerateRandomIV(int length)
            {
                char[] _iv = new char[length];
                byte[] randomBytes = new byte[length];

                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(randomBytes);
                }

                for (int i = 0; i < _iv.Length; i++)
                {
                    int ptr = randomBytes[i] % CharacterMatrixForRandomIVStringGeneration.Length;
                    _iv[i] = CharacterMatrixForRandomIVStringGeneration[ptr];
                }

                return new string(_iv);
            }
コード例 #16
0
 // This method simulates a roll of the dice. The input parameter is the
 // number of sides of the dice.
 public static byte RollDice(byte numberSides)
 {
     if (numberSides <= 0)
         throw new ArgumentOutOfRangeException("numberSides");
     // Create a new instance of the RNGCryptoServiceProvider.
     RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();
     // Create a byte array to hold the random value.
     byte[] randomNumber = new byte[1];
     do
     {
         // Fill the array with a random value.
         rngCsp.GetBytes(randomNumber);
     }
     while (!IsFairRoll(randomNumber[0], numberSides));
     // Return the random number mod the number
     // of sides.  The possible values are zero-
     // based, so we add one.
     return (byte)((randomNumber[0] % numberSides) + 1);
 }
コード例 #17
0
ファイル: RNCrypto.cs プロジェクト: jvifian/slotMachine1
	public static int GetRandomIntBetween(int minValue, int maxValue)
	{
		// Make maxValue inclusive.
		//maxValue++;
		
		var rng = new RNGCryptoServiceProvider();
		var uint32Buffer = new byte[4];
		long diff = maxValue - minValue;
		
		while (true)
		{
			rng.GetBytes(uint32Buffer);
			uint rand = BitConverter.ToUInt32(uint32Buffer, 0);
			const long max = (1 + (long)int.MaxValue);
			long remainder = max % diff;
			if (rand < max - remainder)
			{
				return (int)(minValue + (rand % diff));
			}
		}
	}
コード例 #18
0
    public static void HashWithSalt(
        string plaintext, ref string salt, out string hash)
    {
        const int SALT_BYTE_COUNT = 16;
        if (salt == null || salt == "")
        {
            byte[] saltBuf = new byte[SALT_BYTE_COUNT];
            RNGCryptoServiceProvider rng =
                new RNGCryptoServiceProvider();
            rng.GetBytes(saltBuf);

            StringBuilder sb =
                new StringBuilder(saltBuf.Length);
            for (int i = 0; i < saltBuf.Length; i++)
                sb.Append(string.Format("{0:X2}", saltBuf[i]));
            salt = sb.ToString();
        }

        hash = FormsAuthentication.
            HashPasswordForStoringInConfigFile(
            salt + plaintext, DefCryptoAlg);
    }
コード例 #19
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        byte[] arr = new byte[24];
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(arr);
        System.Text.StringBuilder machineKey = new System.Text.StringBuilder(24);
        for (int i = 0; i < arr.Length; i++)
        {
            machineKey.Append(String.Format("{0:X2}", arr[i]));
        }
        Page.Response.Write(machineKey.ToString());



        Page.Response.Write(WebConfigurationManager.AppSettings["topic"] + "<br />");
        Page.Response.Write(WebConfigurationManager.ConnectionStrings["NorthwindConnection"] + "<br />");
        Page.Response.Write(WebConfigurationManager.GetSection("connectionStrings") + "<br />");
        CompilationSection cs = (CompilationSection)WebConfigurationManager.GetSection("system.web/compilation");
        foreach (AssemblyInfo item in cs.Assemblies)
        {
            Response.Write(item.Assembly + "<br /");
        }
    }
コード例 #20
0
ファイル: XmppService.cs プロジェクト: ikaragkiozoglou/brunet
        /// <summary>Initiate a Xmpp client handle.</summary>
        public XmppService(string username, string password, int port)
        {
            _write_lock = new object();
            _jc         = new JabberClient();

            JID jid = new JID(username);

            _jc.User     = jid.User;
            _jc.Server   = jid.Server;
            _jc.Password = password;
            _jc.Port     = port;

            _jc.AutoReconnect        = 30F;
            _jc.AutoStartTLS         = true;
            _jc.KeepAlive            = 30F;
            _jc.AutoPresence         = false;
            _jc.AutoRoster           = false;
            _jc.AutoStartCompression = false;
            _jc.LocalCertificate     = null;
            var rng = new RNGCryptoServiceProvider();

            byte[] id = new byte[4];
            rng.GetBytes(id);
            _jc.Resource = RESOURCE_NS + BitConverter.ToString(id).Replace("-", "");

            _jc.OnInvalidCertificate += HandleInvalidCert;
            _jc.OnAuthenticate       += HandleAuthenticate;
            _jc.OnAuthError          += HandleAuthError;
            _jc.OnError    += HandleError;
            _jc.OnIQ       += HandleIQ;
            _jc.OnPresence += HandlePresence;
            _jc.OnMessage  += HandleMessage;

            _online = new Dictionary <string, JID>();
            _demux  = new Dictionary <Type, QueryCallback>();
        }
コード例 #21
0
        public void Setup()
        {
            RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();

            string   file     = Path.Join(AppDomain.CurrentDomain.BaseDirectory, "UOContent.dll");
            Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(file);

            m_Dictionary = new Dictionary <Type, FeatureFlag <Item> >();
            List <FeatureFlag <Item> > m_Types = new List <FeatureFlag <Item> >();

            m_TypesToLookUp = new Type[100];

            foreach (var type in assembly.GetTypes())
            {
                if (typeof(Item).IsAssignableFrom(type))
                {
                    m_Dictionary.Add(type, new FeatureFlag <Item>());
                    m_Types.Add(new FeatureFlag <Item> {
                        Type = type
                    });
                }
            }

            Console.WriteLine("Dictionary Size: {0}", m_Dictionary.Count);
            Console.WriteLine("Lookup Size: {0}", m_Types.Count);

            m_Dictionary.TrimExcess();
            m_Lookup = m_Types.ToLookup(f => f.Type);
            Span <byte> bytes = stackalloc byte[4];

            for (int i = 0; i < 100; i++)
            {
                csp.GetBytes(bytes);
                m_TypesToLookUp[i] = m_Types[(int)(BinaryPrimitives.ReadUInt32BigEndian(bytes) % m_Types.Count)].Type;
            }
        }
コード例 #22
0
        /// <summary>
        /// Randoms the seed.
        /// </summary>
        /// <remarks>derived from https://sourceforge.net/projects/shorturl-dotnet/ </remarks>
        /// <returns>Random.</returns>
        public static Random RandomSeed()
        {
            // As the default randomizer is based on the current time
            // so it produces the same "random" number within a second
            // Use a crypto randomizer to create the seed value

            // 4-byte array to fill with random bytes
            var randomBytes = new byte[4];

            // Generate 4 random bytes.
            using (var rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(randomBytes);
            }

            // Convert 4 bytes into a 32-bit integer value.
            var seed = ((randomBytes[0] & 0x7f) << 24) |
                       (randomBytes[1] << 16) |
                       (randomBytes[2] << 8) |
                       randomBytes[3];

            // Return a truly randomized random generator
            return(new Random(seed));
        }
コード例 #23
0
        private void OnGetAddrMessageReceived()
        {
            if (!localNode.ServiceEnabled)
            {
                return;
            }
            AddrPayload payload;

            lock (localNode.connectedPeers)
            {
                const int MaxCountToSend       = 200;
                IEnumerable <RemoteNode> peers = localNode.connectedPeers.Where(p => p.ListenerEndpoint != null && p.Version != null);
                if (localNode.connectedPeers.Count > MaxCountToSend)
                {
                    var rnd = new byte[4];
                    using (var rng = new RNGCryptoServiceProvider())
                        rng.GetBytes(rnd);
                    peers = peers.OrderBy(p => BitConverter.ToInt32(rnd, 0));
                }
                peers   = peers.Take(MaxCountToSend);
                payload = AddrPayload.Create(peers.Select(p => NetworkAddressWithTime.Create(p.ListenerEndpoint, p.Version.Services, p.Version.Timestamp)).ToArray());
            }
            EnqueueMessage("addr", payload, true);
        }
コード例 #24
0
        public Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            //生成刷新token
            RandomNumberGenerator cryptoRandomDataGenerator = new RNGCryptoServiceProvider();

            byte[] buffer = new byte[60];
            cryptoRandomDataGenerator.GetBytes(buffer);
            var refreshTokenId = Convert.ToBase64String(buffer).TrimEnd('=').Replace('+', '-').Replace('/', '_');
            //
            var refreshTokenProperties = new AuthenticationProperties(context.Ticket.Properties.Dictionary)
            {
                //发布时间
                IssuedUtc = context.Ticket.Properties.IssuedUtc,
                //设置有效时间
                ExpiresUtc = DateTime.UtcNow.AddYears(1)
            };
            var refreshTokenTicket = new AuthenticationTicket(context.Ticket.Identity, refreshTokenProperties);

            //保存刷新token到集合
            _refreshTokens.TryAdd(refreshTokenId, refreshTokenTicket);
            //刷新token写入请求上下文
            context.SetToken(refreshTokenId);
            return(Task.FromResult <object>(null));
        }
コード例 #25
0
ファイル: Real.cs プロジェクト: PyrosaurusRex/EntroPyro
        private void Randomize()
        {
            byte[] mutate = new byte[1];
            Crypto.GetBytes(mutate);

//            if ((int)mutate[0] >= Tolerance) return;

            byte[] mutateAmount = new byte[1];
            Crypto.GetNonZeroBytes(mutateAmount);

            byte[] positive = new byte[1];
            Crypto.GetNonZeroBytes(positive);

            bool isNegative = ((float)positive[0] < 255.0 / 2.0);

            float changeAmount = MutationRate / (float)mutateAmount[0];

            if (isNegative)
            {
                changeAmount = 0 - changeAmount;
            }

            _local += changeAmount;
        }
コード例 #26
0
        private string ROEncryptString(string inStr, string inKey)
        {
            string outStr             = string.Empty;
            RandomNumberGenerator rng = new RNGCryptoServiceProvider();

            // general format
            // base64(version byte + byte[] of IV + encrypted content) + '-' + visible tail portion
            // version 1 3DES CBC with 8 byte IV
            // version 2 AES256 CBC with 16 byte IV

            byte[] ver = new byte[] { (byte)(DesMD5 ? 1 : 2) };
            byte[] iv  = new byte[DesMD5 ? 8 : 16];
            rng.GetBytes(iv);

            var hasher = new ROHasher(DesMD5);
            SymmetricAlgorithm cipher = DesMD5 ? (SymmetricAlgorithm) new TripleDESCryptoServiceProvider() : (SymmetricAlgorithm) new AesCryptoServiceProvider();

            cipher.Mode = CipherMode.CBC;
            cipher.IV   = iv;
            cipher.Key  = hasher.ComputeHash(UTF8Encoding.UTF8.GetBytes(inKey)).Take(DesMD5 ? 16 : 32).ToArray();
            byte[] encryptedBlock = cipher.CreateEncryptor().TransformFinalBlock(UTF8Encoding.UTF8.GetBytes(inStr), 0, UTF8Encoding.UTF8.GetBytes(inStr).Length);
            outStr = Convert.ToBase64String(ver.Concat(iv).Concat(encryptedBlock).ToArray());
            return(outStr);
        }
コード例 #27
0
ファイル: Prime.cs プロジェクト: goosebones/messenger
        /*
         * begin the prime number generation
         * generates numbers in parallel
         *
         * @param bits number of bits in numbers to generate
         * @param count number of prime numbers to generate
         */
        public BigInteger generate(int bits)
        {
            while (this.primeNum == 0)
            {
                // begin the generation!
                Parallel.For(0, 1000, i => {
                    // create byte array of specified length
                    var byteCount = bits / 8;
                    var bytes     = new Byte[byteCount];
                    // generate random number of specified bit length
                    var rng = new RNGCryptoServiceProvider();
                    rng.GetBytes(bytes);
                    var bigInt = new BigInteger(bytes);

                    // when a prime number has been found
                    if (bigInt.IsProbablyPrime())
                    {
                        this.primeNum = bigInt;
                    }
                });
            }

            return(this.primeNum);
        }
コード例 #28
0
        /// <summary>
        /// Retrieves the JWT secret from the database.
        /// If the secret is not in the database a new one is generated and persisted.
        /// </summary>
        /// <returns></returns>
        private static string GetSecret()
        {
            if (tmpNewSecret != null)
            {
                return(tmpNewSecret);
            }
            using (CSET_Context db = new CSET_Context())
            {
                var jwtKey = db.JWT.OrderBy(x => x.Generated).FirstOrDefault();
                if (jwtKey != null)
                {
                    tmpNewSecret = jwtKey.Secret;
                    return(jwtKey.Secret);
                }

                // This is the first run of CSET -- generate a new secret for this installation
                var byteArray = new byte[(int)Math.Ceiling(130 / 2.0)];
                using (var rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(byteArray);
                }
                string newSecret = String.Concat(Array.ConvertAll(byteArray, x => x.ToString("X2")));


                // Store the new secret
                var j = new JWT
                {
                    Secret    = newSecret,
                    Generated = DateTime.UtcNow
                };
                db.JWT.Add(j);
                db.SaveChanges();
                tmpNewSecret = newSecret;
                return(newSecret);
            }
        }
コード例 #29
0
        //////////////////////////////////////////////////////////////////////

        /// <summary>creates a max 20 character long string of random numbers</summary>
        /// <returns> the string containing random numbers</returns>
        //////////////////////////////////////////////////////////////////////
        private static string generateULONGRnd()
        {
            byte[] randomNumber = new byte[20];

            // Create a new instance of the RNGCryptoServiceProvider.
            RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();

            // Fill the array with a random value.
            Gen.GetBytes(randomNumber);

            StringBuilder x = new StringBuilder(20);

            for (int i = 0; i < 20; i++)
            {
                if (randomNumber[i] == 0 && x.Length == 0)
                {
                    continue;
                }

                x.Append(Convert.ToInt16(randomNumber[i], CultureInfo.InvariantCulture).ToString()[0]);
            }

            return(x.ToString());
        }
コード例 #30
0
        public static double[,] InicializarMatriz(int filas, int columnas)
        {
            Thread.Sleep(100);
            if (random == null)
            {
                var buffer = new byte[4];
                rng.GetBytes(buffer);
                random = new Random(BitConverter.ToInt32(buffer, 0));
            }



            double[,] matriz = new double[filas, columnas];

            for (int i = 0; i < filas; i++)
            {
                for (int j = 0; j < columnas; j++)
                {
                    matriz[i, j] = random.Next(100);
                }
            }

            return(matriz);
        }
コード例 #31
0
        public void Test0()
        {
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            TableServerData          tsd = new TableServerData("0");

            byte[] key = new byte[20];
            rng.GetBytes(key);
            DateTime now = DateTime.UtcNow;
            Entry    ent = new Entry(key, key, now, now.AddSeconds(100));

            tsd.AddEntry(ent);
            LinkedList <Entry> entries = tsd.GetEntries(key);

            Assert.AreEqual(1, entries.Count, "Count after add");
            Assert.AreEqual(ent, entries.First.Value, "Entries are equal");
            tsd.UpdateEntry(ent.Key, ent.Value, now.AddSeconds(200));
            entries = tsd.GetEntries(key);
            Assert.AreEqual(1, entries.Count, "Count after update");
            Assert.AreEqual(ent, entries.First.Value, "Entries are equal");
            tsd.RemoveEntry(ent.Key, ent.Value);
            entries = tsd.GetEntries(key);
            Assert.AreEqual(tsd.Count, 0, "Count after remove");
            Assert.AreEqual(null, entries, "Entry after remove");
        }
コード例 #32
0
        protected int GetCryptographicRandomNumber(int lBound, int uBound)
        {
            // Assumes lBound >= 0 && lBound < uBound
            // returns an int >= lBound and < uBound
            uint urndnum;

            byte[] rndnum = new Byte[4];
            if (lBound == uBound - 1)
            {
                // test for degenerate case where only lBound can be returned
                return(lBound);
            }

            uint xcludeRndBase = (uint.MaxValue -
                                  (uint.MaxValue % (uint)(uBound - lBound)));

            do
            {
                rng.GetBytes(rndnum);
                urndnum = System.BitConverter.ToUInt32(rndnum, 0);
            } while (urndnum >= xcludeRndBase);

            return((int)(urndnum % (uBound - lBound)) + lBound);
        }
コード例 #33
0
ファイル: CouponExtensions.cs プロジェクト: akoesnan/PraLoup
        public static string GenerateCode(this Coupon c, int length)
        {
            RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider();

            char[]  code = new char[length];
            byte [] b    = new byte[1];
            for (int i = 0; i < length; ++i)
            {
                do
                {
                    rngCsp.GetBytes(b);
                }while (b[0] > 35 || b[0] < 0);

                if (b[0] < 26)
                {
                    code[i] = (char)((int)'A' + b[0]);
                }
                else
                {
                    code[i] = (char)((int)'0' + b[0] - 26);
                }
            }
            return(new string(code));
        }
コード例 #34
0
        /// <summary>
        /// Draws a random available card
        /// </summary>
        /// <returns>The card drawn</returns>
        public byte drawCard()
        {
            lock (gameStatus.locker)
            {
                if (numberOfCards <= 0)
                {
                    throw new ArgumentOutOfRangeException("numberOfCards");
                }

                byte drawn;
                do
                {
                    // Create a byte array to hold the random value.
                    byte[] randomNumber = new byte[1];
                    do
                    {
                        rng.GetBytes(randomNumber);
                    }while (randomNumber[0] >= numberOfCards);
                    drawn = randomNumber[0];
                }while (gameStatus.deltCards.Contains(drawn) || gameStatus.lockedCards.Contains(drawn));
                gameStatus.deltCards.Add(drawn);
                return(drawn);
            }
        }
コード例 #35
0
        protected void GenerateCorrelationId(AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            string correlationKey = Constants.CorrelationPrefix + BaseOptions.AuthenticationType;

            var nonceBytes = new byte[32];

            Random.GetBytes(nonceBytes);
            string correlationId = TextEncodings.Base64Url.Encode(nonceBytes);

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure   = Request.IsSecure
            };

            properties.Dictionary[correlationKey] = correlationId;

            Response.Cookies.Append(correlationKey, correlationId, cookieOptions);
        }
コード例 #36
0
        public static bool RegisterUser(tblLeitor user, string plaintextPassword)
        {
            Rfc2898DeriveBytes hash;
            var generatedSaltBytes = new byte[16];

            rng.GetBytes(generatedSaltBytes);

            hash = new Rfc2898DeriveBytes(plaintextPassword, generatedSaltBytes, ITERATIONS);

            var digestedHashedPassword = BitConverter.ToString(hash.GetBytes(16)).Replace("-", "").ToLower();

            hash.Dispose();

            using (var db = new TccSettings())
            {
                var leitor = db.tblLeitor.First(l => l.IDLeitor == user.IDLeitor);
                leitor.Salt  = BitConverter.ToString(generatedSaltBytes).Replace("-", "").ToLower();
                leitor.Senha = digestedHashedPassword;

                db.SaveChanges();
            }

            return(true);
        }
コード例 #37
0
    public static void Shuffle <T>(this IList <T> list)
    {
        RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider();

        if (list == null)
        {
            return;
        }
        int n = list.Count;

        while (n > 1)
        {
            byte[] box = new byte[1];
            do
            {
                provider.GetBytes(box);
            } while (!(box[0] < n * (uint.MaxValue / n)));
            int k = (box[0] % n);
            n--;
            T value = list[k];
            list[k] = list[n];
            list[n] = value;
        }
    }
コード例 #38
0
        public static string Generate(int length, PasswordCharacters allowedCharacters = PasswordCharacters.All,
                                      IEnumerable <char> excludeCharacters             = null)
        {
            if (length <= 0)
            {
                throw new ArgumentOutOfRangeException("length", "Password length must be greater than zero");
            }

            var randomBytes           = new byte[length];
            var randomNumberGenerator = new RNGCryptoServiceProvider();

            randomNumberGenerator.GetBytes(randomBytes);

            string allowedCharactersString = GenerateAllowedCharactersString(allowedCharacters, excludeCharacters);
            int    allowedCharactersCount  = allowedCharactersString.Length;

            var characters = new char[length];

            for (int i = 0; i < length; i++)
            {
                characters[i] = allowedCharactersString[randomBytes[i] % allowedCharactersCount];
            }
            return(new string(characters));
        }
コード例 #39
0
        /// <summary>
        /// Gets encrypted write stream
        /// </summary>
        /// <returns>The write stream.</returns>
        protected override StreamWriter GetWriteStream()
        {
            FileStream   underlyingStream;
            CryptoStream encryptedStream;

            underlyingStream = new FileStream(GetSaveFilename(), FileMode.Create);

            Rfc2898DeriveBytes       byteGenerator = new Rfc2898DeriveBytes(GetUniqueDeviceBytes(), s_Salt, 1000);
            RNGCryptoServiceProvider random        = new RNGCryptoServiceProvider();

            byte[] key = byteGenerator.GetBytes(32);
            byte[] iv  = new byte[16];
            random.GetBytes(iv);

            Rijndael rijndael = Rijndael.Create();

            rijndael.Key = key;
            rijndael.IV  = iv;

            underlyingStream.Write(iv, 0, 16);
            encryptedStream = new CryptoStream(underlyingStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);

            return(new StreamWriter(encryptedStream));
        }
コード例 #40
0
        public string[] generatePans()
        {
            string[] result = new string[RAIDA.NODEQNTY];
            using (var provider = new RNGCryptoServiceProvider())
            {
                for (int i = 0; i < RAIDA.NODEQNTY; i++)
                {
                    var bytes = new byte[16];
                    provider.GetBytes(bytes);

                    Guid   pan     = new Guid(bytes);
                    String rawpan  = pan.ToString("N");
                    String fullPan = "";
                    switch (rawpan.Length)                    //Make sure the pan is 32 characters long. The odds of this happening are slim but it will happen.
                    {
                    case 27: fullPan = ("00000" + rawpan); break;

                    case 28: fullPan = ("0000" + rawpan); break;

                    case 29: fullPan = ("000" + rawpan); break;

                    case 30: fullPan = ("00" + rawpan); break;

                    case 31: fullPan = ("0" + rawpan); break;

                    case 32: fullPan = rawpan; break;

                    case 33: fullPan = rawpan.Substring(0, rawpan.Length - 1); break;                            //trim one off end

                    case 34: fullPan = rawpan.Substring(0, rawpan.Length - 2); break;                            //trim one off end
                    }
                    result[i] = fullPan;
                }
            }            //end for each Pan
            return(result);
        }
コード例 #41
0
        protected void btn_Submit_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(tb_password.Text);
            System.Diagnostics.Debug.WriteLine(Confirmedpassword.Text);
            string emailid = Emaila.Text.ToString();

            if (validateinput())
            {
                if (checkemail(emailid) == null)
                {
                    if (checkPassword(tb_password.Text))
                    {
                        string password = tb_password.Text.ToString().Trim();;
                        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                        byte[] saltByte = new byte[8];
                        rng.GetBytes(saltByte);
                        salt = Convert.ToBase64String(saltByte);
                        SHA512Managed hashing        = new SHA512Managed();
                        string        saltedpassword = password + salt;
                        byte[]        plainHash      = hashing.ComputeHash(Encoding.UTF8.GetBytes(password));
                        byte[]        hashWithSalt   = hashing.ComputeHash(Encoding.UTF8.GetBytes(saltedpassword));
                        finalHash = Convert.ToBase64String(hashWithSalt);
                        RijndaelManaged cipher = new RijndaelManaged();
                        cipher.GenerateKey();
                        Key = cipher.Key;
                        IV  = cipher.IV;
                        createAccount();
                        Response.Redirect("Login.aspx");
                    }
                }
                else
                {
                    lblMessage.Text += "Email address has already existed! Please Enter a new one.";
                }
            }
        }
コード例 #42
0
        public async Task <TokenRefresh> UpdateRefreshToken(string ipAddress, TokenRefresh oldTokenRefresh)
        {
            using (var rngCryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                var randomBytes = new byte[64];
                rngCryptoServiceProvider.GetBytes(randomBytes);
                var token = new TokenRefresh
                {
                    Token       = Convert.ToBase64String(randomBytes),
                    Expires     = DateTime.UtcNow.AddDays(7),
                    CreatedDate = DateTime.UtcNow,
                    CreatedByIp = ipAddress,
                    CreatorId   = oldTokenRefresh.CreatorId
                };
                await _tokenRefreshRepository.AddAsync(token);

                oldTokenRefresh.Revoked         = DateTime.Now;
                oldTokenRefresh.RevokedByIp     = ipAddress;
                oldTokenRefresh.ReplacedByToken = token.Token;
                await _tokenRefreshRepository.UpdateAsync(oldTokenRefresh.Id, oldTokenRefresh);

                return(token);
            }
        }
コード例 #43
0
        public static int GenerateRndNumberUsingCrypto(int min, int max)
        {
            if (max > 255 || min < 0)
            {
                return(0);
            }

            if (max == min)
            {
                return(min);
            }

            int result;
            var crypto = new RNGCryptoServiceProvider();

            byte[] randomNumber = new byte[1];
            do
            {
                crypto.GetBytes(randomNumber);
                result = randomNumber[0];
            } while (result < min || result > max);

            return(result);
        }
コード例 #44
0
        public void TestReadResponseOver4K()
        {
            string expected;
            string input;

            using (var rng = new RNGCryptoServiceProvider()) {
                var builder = new StringBuilder();
                var buffer  = new byte[72];

                while (builder.Length < 5120)
                {
                    rng.GetBytes(buffer);

                    var base64 = Convert.ToBase64String(buffer);
                    builder.AppendFormat("250-{0}\r\n", base64);
                }

                builder.Append("250 Okay, now we're done.\r\n");
                input = builder.ToString();

                expected = input.Replace("250-", "").Replace("250 ", "").Replace("\r\n", "\n").TrimEnd();
            }

            using (var stream = new SmtpStream(new DummyNetworkStream(), new NullProtocolLogger())) {
                var buffer = Encoding.ASCII.GetBytes(input);
                var dummy  = (MemoryStream)stream.Stream;

                dummy.Write(buffer, 0, buffer.Length);
                dummy.Position = 0;

                var response = stream.ReadResponse(CancellationToken.None);

                Assert.AreEqual(250, (int)response.StatusCode);
                Assert.AreEqual(expected, response.Response);
            }
        }
コード例 #45
0
ファイル: DllTools.cs プロジェクト: hjbfa/Bleak
        internal static string GenerateRandomDllName()
        {
            var characterArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();

            // Generate an array of random bytes

            var dllNameBytes = new byte[14];

            using (var rngService = new RNGCryptoServiceProvider())
            {
                rngService.GetBytes(dllNameBytes);
            }

            // Create a randomised name for the DLL

            var stringBuilder = new StringBuilder();

            foreach (var @byte in dllNameBytes)
            {
                stringBuilder.Append(characterArray[@byte % characterArray.Length]);
            }

            return(stringBuilder.Append(".dll").ToString());
        }
コード例 #46
0
ファイル: StunMessage.cs プロジェクト: aykay76/stun
        public StunMessage(StunMethod method, StunClass cls)
        {
            ushort m    = (ushort)method;
            ushort c    = (ushort)cls;
            ushort type = (ushort)((m & 0x1F80) << 2 | (m & 0x0070) << 1 | (m & 0x000F) | (c & 0x0002) << 7 | (c & 0x0001) << 4);

            // buffer starts with STUN header that is always 20 bytes
            // this will grow with each attribute that gets added
            buffer = new byte[20];
            // start stuffing the buffer
            StuffBuffer(BitConverter.GetBytes(type), 0, buffer, 0, 2);

            // we will backfill the length later when we have all the informations

            // add the magic cookie to the header
            bool little = BitConverter.IsLittleEndian;

            StuffBuffer(BitConverter.GetBytes((uint)0x2112a442), 0, buffer, 4, 4);

            // create a transaction ID and add it to the buffer
            RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();

            csp.GetBytes(buffer, 8, 12);
        }
コード例 #47
0
        public byte[] ComputeHash(byte[] value)
        {
            var         o    = this.options;
            Span <byte> salt = stackalloc byte[o.SaltSize];

            using var csprng = new RNGCryptoServiceProvider();
            csprng.GetBytes(salt);

            var hash = Pbkdf2(value, salt, o.Iterations, o.OutputSize);

            using var ms     = new MemoryStream();
            using var writer = new BinaryWriter(ms);
            var size = (short)salt.Length;

            writer.Write(this.options.HashType);   // 2
            writer.Write(size);                    // 2
            writer.Write(this.options.Iterations); // 4
            writer.Write(salt);                    // var 1 (8 by default)
            writer.Write(hash);                    // var 2 (32 by default)
            writer.Flush();
            ms.Flush();

            return(ms.ToArray());
        }
コード例 #48
0
ファイル: misc.cs プロジェクト: Zolo49/ikvm
 public static bool nativeGenerateSeed(byte[] result)
 {
     try
     {
         RNGCryptoServiceProvider csp = new RNGCryptoServiceProvider();
         csp.GetBytes(result);
         return true;
     }
     catch (CryptographicException)
     {
         return false;
     }
 }
コード例 #49
0
ファイル: Logger.cs プロジェクト: BrechtBonte/JobFinder
    private static KeyValuePair<string, string> Encrypt(string password)
    {
        RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        byte[] salt = new byte[SALT_BYTES];
        csprng.GetBytes(salt);

        string saltStr = Convert.ToBase64String(salt);

        return new KeyValuePair<string, string>(saltStr, Encrypt(saltStr, password));
    }
コード例 #50
0
		static MachineKeyConfig ()
		{
			autogenerated = new byte [64];
			RNGCryptoServiceProvider cp = new RNGCryptoServiceProvider ();
			cp.GetBytes (autogenerated);
		}
コード例 #51
0
ファイル: rsa.cs プロジェクト: behemot/rsa-cipher
 public void Keygen(BigInteger p, BigInteger q)
 {
     BigInteger n = p * q;
     BigInteger fi = (p - BigInteger.One) * (q - BigInteger.One);
     var rng = new RNGCryptoServiceProvider();
     byte[] bytes = new byte[fi.ToByteArray().Length - 1];
     BigInteger e;
     do {
         rng.GetBytes(bytes);
         e = new BigInteger(bytes);
     } while (!(e > 1 && e < fi && BigInteger.One == BigInteger.GreatestCommonDivisor(e, fi)));
     BigInteger d = Util.GetModularInverse(e, fi);
     byte [] content = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(d.ToString() + "," + n.ToString())));
     publicFile.Write(content, 0, content.Length);
     content = Encoding.UTF8.GetBytes(Convert.ToBase64String(Encoding.UTF8.GetBytes(e.ToString() + "," + n.ToString())));
     privateFile.Write(content, 0, content.Length);
 }
コード例 #52
0
    /// <summary>
    /// Generates random integer.
    /// </summary>
    /// <param name="minValue">
    /// Min value (inclusive).
    /// </param>
    /// <param name="maxValue">
    /// Max value (inclusive).
    /// </param>
    /// <returns>
    /// Random integer value between the min and max values (inclusive).
    /// </returns>
    /// <remarks>
    /// This methods overcomes the limitations of .NET Framework's Random
    /// class, which - when initialized multiple times within a very short
    /// period of time - can generate the same "random" number.
    /// </remarks>
    private int GenerateRandomNumber(int minValue, int maxValue)
    {
        // We will make up an integer seed from 4 bytes of this array.
        byte[] randomBytes = new byte[4];

        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);

        // Convert four random bytes into a positive integer value.
        int seed = ((randomBytes[0] & 0x7f) << 24) |
                    (randomBytes[1] << 16) |
                    (randomBytes[2] << 8) |
                    (randomBytes[3]);

        // Now, this looks more like real randomization.
        Random random = new Random(seed);

        // Calculate a random number.
        return random.Next(minValue, maxValue + 1);
    }
コード例 #53
0
ファイル: WinsSync.cs プロジェクト: Eckertjeff/WinsSync
    public void SaveLoginCreds(string automate = "")
    {
        string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        string logincredPath = Path.Combine(credPath, ".credentials/login.txt");
        string entropyPath = Path.Combine(credPath, ".credentials/entropy.txt");
        string logincreds = string.Empty;
        if (automate == "Automate")
        {
            password = ConvertToUnsecureString(securePwd);
            logincreds = Username + "\n" + password + "\n" + automate;
            ClearPassword();
            byte[] plaintextcreds = Encoding.UTF8.GetBytes(logincreds);
            byte[] entropy = new byte[20];
            using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
            {
                rng.GetBytes(entropy);
            }

            byte[] encryptedcreds = ProtectedData.Protect(plaintextcreds, entropy, DataProtectionScope.CurrentUser);
            File.WriteAllBytes(logincredPath, encryptedcreds);
            RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\WinsSync\Key");
            key.SetValue("EntropyKey", entropy, RegistryValueKind.Binary);
            key.Close();
            savedlogin = true;
            Automate = automate;
        }
        else
        {
            Console.Write("Would you like to save your login info? Y/N: ");
            if (Console.ReadLine().Equals("y", StringComparison.OrdinalIgnoreCase))
            {
                password = ConvertToUnsecureString(securePwd);
                logincreds = Username + "\n" + password;
                ClearPassword();
                byte[] plaintextcreds = Encoding.UTF8.GetBytes(logincreds);
                byte[] entropy = new byte[20];
                using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
                {
                    rng.GetBytes(entropy);
                }
                byte[] encryptedcreds = ProtectedData.Protect(plaintextcreds, entropy, DataProtectionScope.CurrentUser);
                File.WriteAllBytes(logincredPath, encryptedcreds);
                RegistryKey key = Registry.CurrentUser.CreateSubKey(@"Software\WinsSync\Key");
                key.SetValue("EntropyKey", entropy, RegistryValueKind.Binary);
                savedlogin = true;
                Automate = automate;
            }
        }
    }
コード例 #54
0
ファイル: Authenticator.cs プロジェクト: Felluz/winauth
		public static string EncryptSequence(string data, PasswordTypes passwordType, string password, YubiKey yubi)
    {
			// get hash of original
			var random = new RNGCryptoServiceProvider();
			byte[] saltbytes = new byte[SALT_LENGTH];
			random.GetBytes(saltbytes);
			string salt = ByteArrayToString(saltbytes);

			string hash;
			using (var sha = new SHA256Managed())
			{
        byte[] plain = StringToByteArray(salt + data);
				hash = ByteArrayToString(sha.ComputeHash(plain));
			}

			if ((passwordType & PasswordTypes.YubiKeySlot1) != 0 || (passwordType & PasswordTypes.YubiKeySlot2) != 0)
			{
				if (yubi.YubiData.Length == 0)
				{
					byte[] seed = new byte[SALT_LENGTH];
					random = new RNGCryptoServiceProvider();
					random.GetBytes(seed);

					// we encrypt the data using the hash of a random string from the YubiKey
					int slot = ((passwordType & PasswordTypes.YubiKeySlot1) != 0 ? 1 : 2);
					yubi.YubiData.Data = yubi.ChallengeResponse(slot, seed);
					yubi.YubiData.Seed = Authenticator.ByteArrayToString(seed);
				}

				byte[] key = yubi.YubiData.Data;
				string encrypted = Encrypt(data, key);

				// test the encryption
				string decrypted = Decrypt(encrypted, key);
				if (string.Compare(data, decrypted) != 0)
				{
					throw new InvalidEncryptionException(data, password, encrypted, decrypted);
				}
				data = yubi.YubiData.Seed + encrypted;
			}
			if ((passwordType & PasswordTypes.Explicit) != 0)
      {
        string encrypted = Encrypt(data, password);

        // test the encryption
        string decrypted = Decrypt(encrypted, password, true);
        if (string.Compare(data, decrypted) != 0)
        {
          throw new InvalidEncryptionException(data, password, encrypted, decrypted);
        }
        data = encrypted;
      }
      if ((passwordType & PasswordTypes.User) != 0)
      {
        // we encrypt the data using the Windows User account key
        byte[] plain = StringToByteArray(data);
        byte[] cipher = ProtectedData.Protect(plain, null, DataProtectionScope.CurrentUser);
        data = ByteArrayToString(cipher);
      }
      if ((passwordType & PasswordTypes.Machine) != 0)
      {
        // we encrypt the data using the Local Machine account key
        byte[] plain = StringToByteArray(data);
        byte[] cipher = ProtectedData.Protect(plain, null, DataProtectionScope.LocalMachine);
        data = ByteArrayToString(cipher);
      }

			// prepend the salt + hash
			return ENCRYPTION_HEADER + salt + hash + data;
    }
コード例 #55
0
ファイル: TrionAuthenticator.cs プロジェクト: lmcro/winauth
		/// <summary>
		/// Create a random Model string for initialization to armor the init string sent over the wire
		/// </summary>
		/// <returns>Random model string</returns>
		private static string GeneralRandomModel()
		{
			// seed a new RNG
			RNGCryptoServiceProvider randomSeedGenerator = new RNGCryptoServiceProvider();
			byte[] seedBuffer = new byte[4];
			randomSeedGenerator.GetBytes(seedBuffer);
			Random random = new Random(BitConverter.ToInt32(seedBuffer, 0));

			// create a model string with available characters
			StringBuilder model = new StringBuilder(MODEL_SIZE);
			for (int i = MODEL_SIZE; i > 0; i--)
			{
				model.Append(MODEL_CHARS[random.Next(MODEL_CHARS.Length)]);
			}

			return model.ToString();
		}
コード例 #56
0
ファイル: Authenticator.cs プロジェクト: Felluz/winauth
		/// <summary>
		/// Encrypt a string with a given key
		/// </summary>
		/// <param name="plain">data to encrypt - hex representation of byte array</param>
		/// <param name="password">key to use to encrypt</param>
		/// <returns>hex coded encrypted string</returns>
		public static string Encrypt(string plain, string password)
		{
			byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

			// build a new salt
			RNGCryptoServiceProvider rg = new RNGCryptoServiceProvider();
			byte[] saltbytes = new byte[SALT_LENGTH];
			rg.GetBytes(saltbytes);
			string salt = Authenticator.ByteArrayToString(saltbytes);

			// build our PBKDF2 key
#if NETCF
			PBKDF2 kg = new PBKDF2(passwordBytes, saltbytes, PBKDF2_ITERATIONS);
#else
			Rfc2898DeriveBytes kg = new Rfc2898DeriveBytes(passwordBytes, saltbytes, PBKDF2_ITERATIONS);
#endif
			byte[] key = kg.GetBytes(PBKDF2_KEYSIZE);

			return salt + Encrypt(plain, key);
		}
コード例 #57
0
ファイル: SteamAuthenticator.cs プロジェクト: lmcro/winauth
		/// <summary>
		/// Create a random Device ID string for Enrolling
		/// </summary>
		/// <returns>Random string</returns>
		private static string BuildRandomId()
		{
			using (var sha1 = new SHA1Managed())
			{
				RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();
				byte[] buffer = new byte[4];
				random.GetBytes(buffer);

				byte[] hash = sha1.ComputeHash(buffer);
				return "android:" + Authenticator.ByteArrayToString(hash);
			}
		}
コード例 #58
0
ファイル: Authenticator.cs プロジェクト: Felluz/winauth
		/// <summary>
		/// Create a one-time pad by generating a random block and then taking a hash of that block as many times as needed.
		/// </summary>
		/// <param name="length">desired pad length</param>
		/// <returns>array of bytes conatining random data</returns>
		protected internal static byte[] CreateOneTimePad(int length)
		{
			// There is a MITM vulnerability from using the standard Random call
			// see https://docs.google.com/document/edit?id=1pf-YCgUnxR4duE8tr-xulE3rJ1Hw-Bm5aMk5tNOGU3E&hl=en
			// in http://code.google.com/p/winauth/issues/detail?id=2
			// so we switch out to use RNGCryptoServiceProvider instead of Random

			RNGCryptoServiceProvider random = new RNGCryptoServiceProvider();

			byte[] randomblock = new byte[length];

			SHA1 sha1 = SHA1.Create();
			int i = 0;
			do
			{
				byte[] hashBlock = new byte[128];
				random.GetBytes(hashBlock);

				byte[] key = sha1.ComputeHash(hashBlock, 0, hashBlock.Length);
				if (key.Length >= randomblock.Length)
				{
					Array.Copy(key, 0, randomblock, i, randomblock.Length);
					break;
				}
				Array.Copy(key, 0, randomblock, i, key.Length);
				i += key.Length;
			} while (true);

			return randomblock;
		}
コード例 #59
0
ファイル: dataAccess.cs プロジェクト: you8/cato
    public string GenerateNewPassword()
    {
        int DEFAULT_MIN_PASSWORD_LENGTH = 8;
        int DEFAULT_MAX_PASSWORD_LENGTH = 16;

        // Define supported password characters divided into groups.
        // You can add (or remove) characters to (from) these groups.
        string PASSWORD_CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
        string PASSWORD_CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
        string PASSWORD_CHARS_NUMERIC = "23456789";
        string PASSWORD_CHARS_SPECIAL = "$?_&=!%";

        // Create a local array containing supported password characters
        // grouped by types. You can remove character groups from this
        // array, but doing so will weaken the password strength.
        char[][] charGroups = new char[][]
        {
            PASSWORD_CHARS_LCASE.ToCharArray(),
            PASSWORD_CHARS_UCASE.ToCharArray(),
            PASSWORD_CHARS_NUMERIC.ToCharArray(),
            PASSWORD_CHARS_SPECIAL.ToCharArray()
        };

        // Use this array to track the number of unused characters in each
        // character group.
        int[] charsLeftInGroup = new int[charGroups.Length];

        // Initially, all characters in each group are not used.
        for (int i = 0; i < charsLeftInGroup.Length; i++)
            charsLeftInGroup[i] = charGroups[i].Length;

        // Use this array to track (iterate through) unused character groups.
        int[] leftGroupsOrder = new int[charGroups.Length];

        // Initially, all character groups are not used.
        for (int i = 0; i < leftGroupsOrder.Length; i++)
            leftGroupsOrder[i] = i;

        // Because we cannot use the default randomizer, which is based on the
        // current time (it will produce the same "random" number within a
        // second), we will use a random number generator to seed the
        // randomizer.

        // Use a 4-byte array to fill it with random bytes and convert it then
        // to an integer value.
        byte[] randomBytes = new byte[4];

        // Generate 4 random bytes.
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        rng.GetBytes(randomBytes);

        // Convert 4 bytes into a 32-bit integer value.
        int seed = (randomBytes[0] & 0x7f) << 24 |
                    randomBytes[1] << 16 |
                    randomBytes[2] << 8 |
                    randomBytes[3];

        // Now, this is real randomization.
        Random random = new Random(seed);

        // This array will hold password characters.
        char[] password = null;

        // Allocate appropriate memory for the password.
        password = new char[random.Next(DEFAULT_MIN_PASSWORD_LENGTH, DEFAULT_MAX_PASSWORD_LENGTH)];

        // Index of the next character to be added to password.
        int nextCharIdx;

        // Index of the next character group to be processed.
        int nextGroupIdx;

        // Index which will be used to track not processed character groups.
        int nextLeftGroupsOrderIdx;

        // Index of the last non-processed character in a group.
        int lastCharIdx;

        // Index of the last non-processed group.
        int lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;

        // Generate password characters one at a time.
        for (int i = 0; i < password.Length; i++)
        {
            // If only one character group remained unprocessed, process it;
            // otherwise, pick a random character group from the unprocessed
            // group list. To allow a special character to appear in the
            // first position, increment the second parameter of the Next
            // function call by one, i.e. lastLeftGroupsOrderIdx + 1.
            if (lastLeftGroupsOrderIdx == 0)
                nextLeftGroupsOrderIdx = 0;
            else
                nextLeftGroupsOrderIdx = random.Next(0,
                                                     lastLeftGroupsOrderIdx);

            // Get the actual index of the character group, from which we will
            // pick the next character.
            nextGroupIdx = leftGroupsOrder[nextLeftGroupsOrderIdx];

            // Get the index of the last unprocessed characters in this group.
            lastCharIdx = charsLeftInGroup[nextGroupIdx] - 1;

            // If only one unprocessed character is left, pick it; otherwise,
            // get a random character from the unused character list.
            if (lastCharIdx == 0)
                nextCharIdx = 0;
            else
                nextCharIdx = random.Next(0, lastCharIdx + 1);

            // Add this character to the password.
            password[i] = charGroups[nextGroupIdx][nextCharIdx];

            // If we processed the last character in this group, start over.
            if (lastCharIdx == 0)
                charsLeftInGroup[nextGroupIdx] =
                                          charGroups[nextGroupIdx].Length;
            // There are more unprocessed characters left.
            else
            {
                // Swap processed character with the last unprocessed character
                // so that we don't pick it until we process all characters in
                // this group.
                if (lastCharIdx != nextCharIdx)
                {
                    char temp = charGroups[nextGroupIdx][lastCharIdx];
                    charGroups[nextGroupIdx][lastCharIdx] =
                                charGroups[nextGroupIdx][nextCharIdx];
                    charGroups[nextGroupIdx][nextCharIdx] = temp;
                }
                // Decrement the number of unprocessed characters in
                // this group.
                charsLeftInGroup[nextGroupIdx]--;
            }

            // If we processed the last group, start all over.
            if (lastLeftGroupsOrderIdx == 0)
                lastLeftGroupsOrderIdx = leftGroupsOrder.Length - 1;
            // There are more unprocessed groups left.
            else
            {
                // Swap processed group with the last unprocessed group
                // so that we don't pick it until we process all groups.
                if (lastLeftGroupsOrderIdx != nextLeftGroupsOrderIdx)
                {
                    int temp = leftGroupsOrder[lastLeftGroupsOrderIdx];
                    leftGroupsOrder[lastLeftGroupsOrderIdx] =
                                leftGroupsOrder[nextLeftGroupsOrderIdx];
                    leftGroupsOrder[nextLeftGroupsOrderIdx] = temp;
                }
                // Decrement the number of unprocessed groups.
                lastLeftGroupsOrderIdx--;
            }
        }

        // Convert password characters into a string and return the result.
        return new string(password);
    }
コード例 #60
0
 private string CreateSalt()
 {
     // Generate a long random salt using a CSPRNG
     RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
     byte[] salt = new byte[_userService.SaltBytes];
     csprng.GetBytes(salt);
     return Convert.ToBase64String(salt);
 }