public static int GetInt()
 {
     lock (Int32Buffer)
     {
         Generator.GetBytes(Int32Buffer);
         return(BitConverter.ToInt32(Int32Buffer, 0));
     }
 }
Esempio n. 2
0
        public static byte[] Generate(int length)
        {
            if (length < 1)
            {
                throw new ArgumentOutOfRangeException("length");
            }

            var bytes = new byte[length];

            _random.GetBytes(bytes);
            return(bytes);
        }
Esempio n. 3
0
        public Guid NewGuid()
        {
            var seqNumber = Interlocked.Increment(ref _seqNumber);
            var ticks     = DateTime.UtcNow.Ticks;

            byte[] d8 = new byte[8];

            if (seqNumber >> 16 > 0)
            {
                while (seqNumber != Interlocked.CompareExchange(ref _seqNumber, seqNumber >> 16, seqNumber))
                {
                    seqNumber = Interlocked.Increment(ref _seqNumber);
                }
            }

            RandomProvider.GetBytes(d8);

            d8[0] = (byte)((1 << 6) | ((byte)(seqNumber >> 11)));
            d8[1] = (byte)seqNumber;

            return(new Guid(
                       (Int32)(ticks >> 40),
                       (Int16)(ticks >> 16),
                       (Int16)((Int16)(TypeCode << 8) | (Int16)(ticks >> 8)),
                       d8
                       ));
        }
Esempio n. 4
0
        public async Task <PasswordResetToken> CreateAsync(Guid userId, int expiryMinutes)
        {
            if (userId == Guid.Empty)
            {
                throw new ArgumentNullException("userId");
            }

            string _token = "";

            System.Security.Cryptography.RandomNumberGenerator cryptoRNG = System.Security.Cryptography.RandomNumberGenerator.Create();
            Byte[] randomBytes = new Byte[40];
            while ((_token == "") || (await IsTokenUnique(_token) == false))
            {
                cryptoRNG.GetBytes(randomBytes);
                _token = Convert.ToBase64String(randomBytes);
            }

            PasswordResetToken _resetToken = new PasswordResetToken();

            _resetToken.Id      = Guid.NewGuid();
            _resetToken.UserId  = userId;
            _resetToken.Token   = _token;
            _resetToken.Expires = DateTime.Now.AddMinutes(expiryMinutes);
            using (IDbConnection connection = CurrentContext.OpenConnection())
                connection.Execute("insert into app_PasswordResetTokens(Id, UserId, Token, Expires, Used) values(@Id, @UserId, @Token, @Expires, @Used)", new { Id = _resetToken.Id, UserId = _resetToken.UserId, Token = _resetToken.Token, Expires = _resetToken.Expires.ToString("dd-MM-yyyy HH:mm:ss"), Used = _resetToken.Used.Value.ToString("dd-MM-yyyy HH:mm:ss") });

            return(_resetToken);
        }
Esempio n. 5
0
        /// <summary>
        /// Creates a new secret key packet. Format defaults
        /// to new packet format.
        /// </summary>
        /// <param name="bIsSubkey">Has to be true, if you want
        /// to create a secret subkey packet.</param>
        public SecretKeyPacket(bool bIsSubkey)
        {
            bBody         = new byte[0];
            bHeader       = new byte[0];
            pfFormat      = PacketFormats.New;
            bIsEncrypted  = true;
            bS2KSpecifier = new String2KeySpecifier();
            bS2KSpecifier.HashAlgorithm = HashAlgorithms.SHA1;
            bS2KSpecifier.Type          = String2KeySpecifierTypes.IteraterSaltedS2K;
            bS2KSpecifier.Count         = 96;

            byte[] bSalt = new byte[8];
            System.Security.Cryptography.RandomNumberGenerator rngRand = System.Security.Cryptography.RandomNumberGenerator.Create();
            rngRand.GetBytes(bSalt);

            S2KSpecifier.Salt = 0;
            S2KSpecifier.Salt = ((ulong)bSalt[0] << 56) ^ ((ulong)bSalt[1] << 48) ^
                                ((ulong)bSalt[2] << 40) ^ ((ulong)bSalt[3] << 32) ^
                                ((ulong)bSalt[3] << 24) ^ ((ulong)bSalt[5] << 16) ^
                                ((ulong)bSalt[6] << 8) ^ (ulong)bSalt[7];

            if (bIsSubkey)
            {
                ctContent = ContentTypes.SecretSubkey;
            }
            else
            {
                ctContent = ContentTypes.SecretKey;
            }

            this.bIsUpdated = true;
        }
Esempio n. 6
0
        public string RandomString(ulong number_of_characters = 16)
        {
            //
            // Generate a unique state string to check for forgeries
            //

            char[] chars = new char[number_of_characters];

            for (var i = 0; i < chars.Length; i++)
            {
                #if NETSTANDARD1_3
                #else
                chars[i] = (char)rand.Next((int)'a', (int)'z' + 1);
                #endif
            }

            #if NETSTANDARD1_3
            byte[] bytes_random = new byte[number_of_characters];
            rand.GetBytes(bytes_random);
            chars = System.Text.Encoding.ASCII.GetString(bytes_random).ToCharArray();
            #else
            #endif

            string state_string = new string(chars);

            return(state_string);
        }
Esempio n. 7
0
        /// <inheritdoc />
        public override void ForwardProcessDataStream(Stream inStream, Stream outStream, Dictionary <string, string> options, out long writtenBytes)
        {
            if (options == null)
            {
                throw new ArgumentException("Options dictionary was null", "options");
            }
            else if (!options.ContainsKey(paddedSizeOptionName) || !options.ContainsKey(padTypeOptionName) || !options.ContainsKey(padExceptionOptionName))
            {
                throw new ArgumentException("Options dictionary did not contain the necessary padding options", "options");
            }

            int             paddingSize;
            DataPaddingType padType;
            bool            padException;

            if (!int.TryParse(options[paddedSizeOptionName], out paddingSize) || !bool.TryParse(options[padExceptionOptionName], out padException))
            {
                throw new ArgumentException("Options dictionary contained invalid options for DataPadder", "options");
            }

            try { padType = (DataPaddingType)Enum.Parse(typeof(DataPaddingType), options[padTypeOptionName]); }
            catch (ArgumentException) { throw new ArgumentException("Options dictionary contained invalid options for DataPadder", "options"); }

            if (padException && inStream.Length > paddingSize - 4)
            {
                throw new ArgumentException("Options dictionary contained invalid options for DataPadder. Not enough data padding was allowed", "options");
            }

            paddingSize = paddingSize - 4 - (int)inStream.Length;
            if (paddingSize < 0)
            {
                paddingSize = 0;
            }

            byte[] padData;

            if (padType == DataPaddingType.Random)
            {
#if NETFX_CORE
                CryptographicBuffer.CopyToByteArray(CryptographicBuffer.GenerateRandom((uint)paddingSize), out padData);
#else
                padData = new byte[paddingSize];
                rand.GetBytes(padData);
#endif
            }
            else
            {
                padData = new byte[paddingSize];
            }

            StreamTools.Write(inStream, 0, inStream.Length, outStream, 8192, double.MaxValue, int.MaxValue);

            if (paddingSize != 0)
            {
                outStream.Write(padData, 0, padData.Length);
            }

            outStream.Write(BitConverter.GetBytes(paddingSize + 4), 0, 4);
            writtenBytes = outStream.Position;
        }
Esempio n. 8
0
        private void btnGenerate_Click(object sender, EventArgs e)
        {
            System.Security.Cryptography.RandomNumberGenerator rnd = System.Security.Cryptography.RandomNumberGenerator.Create();
            byte[] randomData = new byte[10];
            randomNumbers = new List <int>();
            int ranmdomNumber;
            int fairNumbers = byte.MaxValue / 35;
            int rndByteMax  = fairNumbers * 35;

            while (randomNumbers.Count < 7)
            {
                // Generate a random number between 1 and 35
                rnd.GetBytes(randomData);
                for (int i = 0; i < randomData.Length; i++)
                {
                    if (randomData[i] < rndByteMax)
                    {
                        ranmdomNumber = (randomData[i] % 35) + 1;
                        if (randomNumbers.Count == 7)
                        {
                            break;
                        }
                        else if (!randomNumbers.Contains(ranmdomNumber))
                        {
                            randomNumbers.Add(ranmdomNumber);
                        }
                    }
                }
            }

            pnlBoard.Refresh();
            lblGeneratedDescr.Text = "Genererade rader: " + (++generationCount);
        }
Esempio n. 9
0
        /*
         * 2017-10-21
         *
         * in .NET Standard are no classes like:
         *
         * RNGCryptoServiceProvider
         * http://packagesearch.azurewebsites.net/?q=RNGCryptoServiceProvider
         *
         * SHA256Managed
         * http://packagesearch.azurewebsites.net/?q=SHA256Managed
         *
         * https://github.com/googlesamples/oauth-apps-for-windows
         * https://github.com/googlesamples/oauth-apps-for-windows/blob/master/OAuthConsoleApp/OAuthConsoleApp/Program.cs
         */

        public string RandomDataBase64Url(uint length)
        {
            byte[] bytes = new byte[length];

            // original code
            //RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            #if NETSTANDARD1_3
            // from System.Security.Cryptography
            // designed to be used with cryptographic algorithms
            System.Security.Cryptography.RandomNumberGenerator rng = null;
            rng = System.Security.Cryptography.RandomNumberGenerator.Create();
            rng.GetBytes(bytes);
            #else
            //  insecure (albeit faster) Random class
            System.Random rng = new System.Random();
            rng.NextBytes(bytes);
            #endif

            string base64url_no_padding = null;

            Base64UrlEncoding e = new Base64UrlEncoding();
            base64url_no_padding = e.Encode(bytes, is_padded: false);

            return(base64url_no_padding);
        }
Esempio n. 10
0
        private bool AddXSRFTokenToRespone(HttpServer.IHttpResponse response)
        {
            if (m_activexsrf.Count > 500)
            {
                return(false);
            }

            var buf     = new byte[32];
            var expires = DateTime.UtcNow.AddMinutes(XSRF_TIMEOUT_MINUTES);

            m_prng.GetBytes(buf);
            var token = Convert.ToBase64String(buf);

            m_activexsrf.Add(token, expires);
            response.Cookies.Add(new HttpServer.ResponseCookie(XSRF_COOKIE_NAME, token, expires));
            return(true);
        }
Esempio n. 11
0
 /// <summary>Return a new random 64-bit UUID</summary>
 /// <returns>Uuid64 that contains 64 bits worth of randomness.</returns>
 /// <remarks>
 /// <p>This methods needs to acquire a lock. If multiple threads needs to generate ids concurrently, you may need to create an instance of this class for each threads.</p>
 /// <p>The uniqueness of the generated uuids depends on the quality of the random number generator. If you cannot tolerate collisions, you either have to check if a newly generated uid already exists, or use a different kind of generator.</p>
 /// </remarks>
 public Uuid64 NewUuid()
 {
     lock (m_rng)
     {
         // get 8 bytes of randomness (0 allowed)
         m_rng.GetBytes(m_scratch);
         return(new Uuid64(m_scratch));
     }
 }
Esempio n. 12
0
 /// <summary>
 /// Provides a seed based on an internal random number generator (crypto if available), time and unique GUIDs.
 /// WARNING: There is only medium randomness in this seed, but quick repeated
 /// calls will result in different seed values. Do not use for cryptography!
 /// </summary>
 public static int Robust()
 {
     lock (Lock)
     {
         var bytes = new byte[4];
         MasterRng.GetBytes(bytes);
         return(BitConverter.ToInt32(bytes, 0));
     }
 }
Esempio n. 13
0
 /// <summary>
 /// Generiert eine Zufallszahl und gibt das Ergebnis Base64 Codiert zurück.
 /// </summary>
 /// <param name="bits">Länge der Zufallszahl, wird auf ganze Bytes abgerundet.</param>
 /// <returns>Base64 String mit der Länge bits * 4 / 3.</returns>
 private static string GenerateSalt(int bits = 128)
 {
     // 128bit Salt erzeugen.
     byte[] salt = new byte[bits / 8];
     using (System.Security.Cryptography.RandomNumberGenerator rnd = System.Security.Cryptography.RandomNumberGenerator.Create())
     {
         rnd.GetBytes(salt);
     }
     return(Convert.ToBase64String(salt));
 }
Esempio n. 14
0
        public static KeyPair Generate()
        {
            var bytes = new byte[32];

            lock (rnd)
            {
                rnd.GetBytes(bytes);
            }
            return(new KeyPair(bytes));
        }
Esempio n. 15
0
        public static byte[] GetRandomBytes(int targetLength)
        {
            var bytes = new byte[targetLength + (securityParameter / 8) + 1];

            lock (rnd)
            {
                rnd.GetBytes(bytes);
                //rnd.NextBytes(bytes);
            }

            bytes[bytes.Length - 1] = 0;

            var maxBytes = new byte[targetLength];

            for (int i = 0; i < maxBytes.Length; i++)
            {
                maxBytes[i] = 255;
            }

            var n   = BigInteger.FromSignedArray(bytes);
            var max = BigInteger.FromSignedArray(maxBytes);

            var q = n % max;

            bytes = q.ToSignedByteArray();

            // TODO this is a fix for a bug that appears sometimes, it appears that the math before has a mistake somewhere
            var diff = targetLength - bytes.Length;

            if (diff > 0)
            {
                var pad = new byte[diff];
                lock (rnd)
                {
                    rnd.GetBytes(bytes);
                    //rnd.NextBytes(pad);
                }

                bytes = ByteArrayUtils.ConcatBytes(bytes, pad);
            }

            return(bytes);
        }
Esempio n. 16
0
        public static NeoKey Generate()
        {
            var bytes = new byte[32];

            lock (rnd)
            {
                rnd.GetBytes(bytes);
            }
            return(new NeoKey(bytes));
        }
Esempio n. 17
0
 /// <summary>
 /// Generiert eine Zufallszahl und gibt diese Base64 codiert zurück.
 /// </summary>
 /// <param name="bits">Anzahl der Bits der Zufallszahl.</param>
 /// <returns>Base64 String mit der Länge bits * 4 / 3.</returns>
 private static string GenerateSalt(int bits = 128)
 {
     byte[] salt = new byte[bits / 8];
     // Kryptografisch sichere Zufallszahlen erzeugen.
     using (System.Security.Cryptography.RandomNumberGenerator rnd = System.Security.Cryptography.RandomNumberGenerator.Create())
     {
         rnd.GetBytes(salt);
     }
     return(Convert.ToBase64String(salt));
 }
Esempio n. 18
0
        public ECDH()
        {
            priKey = new byte[32];
            using (System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create())
            {
                rng.GetBytes(priKey);
            }
            var PublicKey = ThinNeo.Cryptography.ECC.ECCurve.Secp256r1.G * priKey;

            pubKey = PublicKey.EncodePoint(false);
        }
Esempio n. 19
0
        public Messenger(string arg)
        {
            blockchain = new Blockchain("/blockchain");
            byte[] privateKey = new byte[32];
            System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();
            rng.GetBytes(privateKey);

            userName      = arg;
            EllipticCurve = Rebex.Security.Cryptography.Curve25519.Create(Rebex.Security.Cryptography.Curve25519.Curve25519Sha256);
            EllipticCurve.FromPrivateKey(privateKey);
        }
Esempio n. 20
0
 /// <summary>
 /// Generiert eine Zufallszahl und gibt sie Base64 codiert zurück.
 /// </summary>
 /// <returns></returns>
 public static string GenerateRandom(int length = 128)
 {
     // Salt erzeugen.
     byte[] salt = new byte[length / 8];
     using (System.Security.Cryptography.RandomNumberGenerator rnd =
                System.Security.Cryptography.RandomNumberGenerator.Create())
     {
         rnd.GetBytes(salt);
     }
     return(Convert.ToBase64String(salt));
 }
Esempio n. 21
0
        public static int GetRandomNumber(int maxvalue)
        {
            System.Security.Cryptography.RandomNumberGenerator random =
                System.Security.Cryptography.RandomNumberGenerator.Create();

            byte[] r = new byte[1];
            random.GetBytes(r);
            double val = (double)r[0] / byte.MaxValue;
            int    i   = (int)Math.Round(val * maxvalue, 0);

            return(i);
        }
Esempio n. 22
0
        public static byte[] GetRandomBytes(int targetLength)
        {
            var bytes = new byte[targetLength];

            lock (rnd)
            {
                rnd.GetBytes(bytes);
                //rnd.NextBytes(bytes);
            }

            return(bytes);
        }
Esempio n. 23
0
        //---------------------------------------------------------------------

        /// <summary>
        /// Generates a non-zero random seed using the system clock.
        /// This was found to fail on Mac OSX, due to identical results returned from System.Random (due to an internal error in System.Environment.TickCount)
        /// System.Random was replaced with System.Security.Cryptography.RandomNumberGenerator by Brendan C. Ward on 6/4/2008
        /// </summary>
        public uint GenerateSeed()
        {
            System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create();
            uint seed;

            do
            {
                byte[] temp = new byte[4];
                rng.GetBytes(temp);
                seed = System.BitConverter.ToUInt32(temp, 0);
            } while (seed == 0);
            return(seed);
        }
Esempio n. 24
0
 public byte NextByte()
 {
     if (NextByteBufferIndex >= 10000)
     {
         if (gen == null)
         {
             gen = System.Security.Cryptography.RandomNumberGenerator.Create();
         }
         gen.GetBytes(NextByteBuffer);
         NextByteBufferIndex = 0;
     }
     return(NextByteBuffer[NextByteBufferIndex++]);
 }
Esempio n. 25
0
        /// <summary>
        /// Fills an array of bytes with a cryptographically strong random sequence of values.
        /// </summary>
        /// <param name="data">The array to fill with cryptographically strong random bytes.</param>
        /// <exception cref="ArgumentNullException"><paramref name="data"/> is <c>null</c>.</exception>
        /// <remarks>
        /// The length of the byte array determines how many random bytes are produced.
        /// </remarks>
        public static void GenerateRandom(byte[] data)
        {
#if FEATURE_RNG_CREATE || FEATURE_RNG_CSP
            Randomizer.GetBytes(data);
#else
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }

            var buffer = Windows.Security.Cryptography.CryptographicBuffer.GenerateRandom((uint)data.Length);
            System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(buffer, data);
#endif
        }
Esempio n. 26
0
        private bool AddXSRFTokenToRespone(HttpServer.IHttpResponse response)
        {
            if (m_activexsrf.Count > 500)
            {
                return(false);
            }

            var buf     = new byte[32];
            var expires = DateTime.UtcNow.AddMinutes(XSRF_TIMEOUT_MINUTES);

            m_prng.GetBytes(buf);
            var token = Convert.ToBase64String(buf);

            m_activexsrf.AddOrUpdate(token, key => expires, (key, existingExpires) =>
            {
                // Simulate the original behavior => if the random token, against all odds, is already used
                // we throw an ArgumentException
                throw new ArgumentException("An element with the same key already exists in the dictionary.");
            });

            response.Cookies.Add(new HttpServer.ResponseCookie(XSRF_COOKIE_NAME, token, expires));
            return(true);
        }
Esempio n. 27
0
        public static byte DealCard()
        {
            // Create a byte array to hold the random value.
            byte[] randomCard = new byte[1];
            do
            {
                // Fill the array with a random value.
                rngCsp.GetBytes(randomCard);
            }while (!(randomCard[0] < 208));

            // Return the random number mod the number
            // of cards.
            return((byte)((randomCard[0] % 52)));
        }
Esempio n. 28
0
        private int SecureRandomInt(int min, int max)
        {
            secureRand = System.Security.Cryptography.RandomNumberGenerator.Create();

            //Store bytes of an integer
            byte[] bytes = new byte[4];
            //Generate bytes through the cryptographically secure RNG
            secureRand.GetBytes(bytes);

            //Convert the bytes we got to UInt32
            UInt32 scale = BitConverter.ToUInt32(bytes, 0);

            secureRand.Dispose();
            //Calculate the number between min and max inclusive
            return((int)(min + (max - min) * (scale / (uint.MaxValue + 1.0))));
        }
Esempio n. 29
0
        /// <inheritdoc />
        public override byte[] GenerateRandomBytes(int length)
        {
            if (length < 1)
            {
                throw new ArgumentException(nameof(length));
            }

            var privateKey = new byte[length];

            using (System.Security.Cryptography.RandomNumberGenerator rng = System.Security.Cryptography.RandomNumberGenerator.Create())
            {
                rng.GetBytes(privateKey);
            }

            return(privateKey);
        }
Esempio n. 30
0
        public static UInt128 FromSecureRandom(
            System.Security.Cryptography.RandomNumberGenerator provider)
        {
            UInt128 retVal = null;

            byte[] bytes = new byte[16];
            provider.GetBytes(bytes);
            ulong lower = System.BitConverter.ToUInt64(bytes, 0);
            ulong upper = System.BitConverter.ToUInt64(bytes, 8);

            bytes = null;

            retVal = new UInt128(lower, upper);

            return(retVal);
        } // End Function FromGuid