GetNonZeroBytes() public method

public GetNonZeroBytes ( byte data ) : void
data byte
return void
Example #1
0
File: Util.cs Project: githexing/05
        public static string GetUniqueIndentifier(int length)
        {
            if (length <= 0)
            {
                return(string.Empty);
            }
            int maxSize = length;

            char[] chars = new char[62];
            string a     = "abcdefghijklmnopqrstuvwxyz1234567890";

            chars = a.ToCharArray();
            int size = maxSize;

            byte[] data = new byte[1];
            System.Security.Cryptography.RNGCryptoServiceProvider rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
            rng.GetNonZeroBytes(data);
            size = maxSize;
            data = new byte[size];
            rng.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder();

            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length - 1)]);
            }
            if (result[0] >= '0' && result[0] <= '9')
            {
                return(GetUniqueIndentifier(length));
            }
            return(result.ToString());
        }
Example #2
0
 public static UserWallet CreateDatabase(string path, string password)
 {
     using (WalletDataContext ctx = new WalletDataContext(path))
     using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
     {
         byte[] passwordKey = password.ToAesKey();
         byte[] masterKey = new byte[32];
         byte[] iv = new byte[16];
         rng.GetNonZeroBytes(masterKey);
         rng.GetNonZeroBytes(iv);
         masterKey.AesEncrypt(passwordKey, iv);
         Array.Clear(passwordKey, 0, passwordKey.Length);
         ctx.Database.EnsureDeleted();
         ctx.Database.EnsureCreated();
         ctx.Keys.Add(new Key
         {
             Name = Key.MasterKey,
             Value = masterKey
         });
         ctx.Keys.Add(new Key
         {
             Name = Key.IV,
             Value = iv
         });
         ctx.SaveChanges();
     }
     UserWallet wallet = OpenDatabase(path, password);
     wallet.CreateAccount();
     return wallet;
 }
Example #3
0
        /// <summary>
        /// 生成指定长度的唯一标识<see cref="System.String"/>值
        /// </summary>
        /// <param name="length">要生成的标识长度</param>
        /// <returns>唯一标识的<see cref="System.String"/>值</returns>
        public static string GetUniqueIdentifier(int length)
        {
            while (true)
            {
                var maxSize = length;
                var a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                var chars = a.ToCharArray();
                var size = maxSize;
                var data = new byte[1];
                using (var crypto = new RNGCryptoServiceProvider())
                {
                    crypto.GetNonZeroBytes(data);
                    data = new byte[size];
                    crypto.GetNonZeroBytes(data);
                }

                var result = new StringBuilder(size);
                foreach (var b in data)
                {
                    result.Append(chars[b%(chars.Length - 1)]);
                }

                // Unique identifiers cannot begin with 0-9
                if (result[0] >= '0' && result[0] <= '9')
                    continue;

                return result.ToString();
            }
        }
Example #4
0
 public static string GenerateUID()
 {
     try
     {
         int    maxSize = 15;
         int    minSize = 10;
         char[] chars   = new char[63];
         string a;
         a     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
         chars = a.ToCharArray();
         int    size = maxSize;
         byte[] data = new byte[2];
         System.Security.Cryptography.RNGCryptoServiceProvider crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
         crypto.GetNonZeroBytes(data);
         size = maxSize;
         data = new byte[size + 1];
         crypto.GetNonZeroBytes(data);
         StringBuilder result = new StringBuilder(size);
         foreach (byte b in data)
         {
             result.Append(chars[b % (chars.Length - 1)]);
         }
         return(result.ToString().Trim());
     }
     catch (Exception ex)
     {
         return("");
     }
 }
Example #5
0
 public static UserWallet CreateDatabase(string path, string password)
 {
     SqlConnectionStringBuilder sb = new SqlConnectionStringBuilder();
     sb.AttachDBFilename = path;
     sb.DataSource = @"(LocalDB)\v11.0";
     sb.IntegratedSecurity = true;
     using (WalletDataContext ctx = new WalletDataContext(sb.ToString()))
     using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
     {
         byte[] passwordKey = password.ToAesKey();
         byte[] masterKey = new byte[32];
         byte[] iv = new byte[16];
         rng.GetNonZeroBytes(masterKey);
         rng.GetNonZeroBytes(iv);
         masterKey.AesEncrypt(passwordKey, iv);
         Array.Clear(passwordKey, 0, passwordKey.Length);
         ctx.Database.Delete();
         ctx.Database.Create();
         ctx.Keys.Add(new Key
         {
             Name = Key.MasterKey,
             Value = masterKey
         });
         ctx.Keys.Add(new Key
         {
             Name = Key.IV,
             Value = iv
         });
         ctx.SaveChanges();
     }
     UserWallet wallet = OpenDatabase(path, password);
     wallet.CreateAccount();
     return wallet;
 }
		/// <summary>
		/// http://www.codeproject.com/Articles/14403/Generating-Unique-Keys-in-Net
		/// </summary>
		/// <returns></returns>
		public static string GetUniqueNumber()
		{
			//string result = DateTime.Now.Year.ToString() + Guid.NewGuid().ToString().GetHashCode().ToString("x");
			//return result;

			int maxSize = 8;
			char[] chars = new char[62];
			string a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
			chars = a.ToCharArray();
			int size = maxSize;
			byte[] data = new byte[1];

			var crypto = new RNGCryptoServiceProvider();
			crypto.GetNonZeroBytes(data);
			data = new byte[size];
			crypto.GetNonZeroBytes(data);
			var result = new StringBuilder(size);

			foreach (byte b in data)
			{
				result.Append(chars[b % (chars.Length - 1)]);
			}

			return "CS" + result.ToString();

		}
Example #7
0
        /// <summary>
        /// Gets the Cryptographic Random Character generated string.
        /// Developed by http://www.codeproject.com/KB/aspnet/UniqueKeys.aspx.
        /// </summary>
        /// <param name="characterLength">Length of the character.</param>
        /// <returns>A string with generated key.</returns>
        public static string GetCryptographicRandomCharacterGenerator(int characterLength)
        {
            StringBuilder returnValue;

            try
            {
                int maxSize = characterLength;
                const string characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                char[] chars = characters.ToCharArray();
                var data = new byte[1];

                var crypto = new RNGCryptoServiceProvider();
                crypto.GetNonZeroBytes(data);

                int size = maxSize;
                data = new byte[size];
                crypto.GetNonZeroBytes(data);
                var result = new StringBuilder(size);

                foreach (var b in data)
                {
                    result.Append(chars[b % (chars.Length - 1)]);
                }

                returnValue = result;
            }
            catch (Exception ex)
            {
                Logger.Error("Error at GetCryptographicRandomCharacterGenerator", ex);
                throw;
            }

            return returnValue.ToString();
        }
Example #8
0
        public static void Run()
        {
            using (RNGCryptoServiceProvider key = new RNGCryptoServiceProvider())
            {
                for (int i = 0; i < 12; i++)
                {
                    byte[] b = new byte[1];
                    key.GetNonZeroBytes(b);
                    Random rng = new Random(b[0]);
                    b = new byte[rng.Next(8, 16)];
                    key.GetNonZeroBytes(b);

                    double seed = b.Aggregate((int)1, (x, y) => x * y);
                    Console.WriteLine(seed);
                    int seed2 = 1;
                    for (int j = 0; j < b.Length; j++)
                    {
                        seed2 *= (int)b[j];
                    }
                    Console.WriteLine(seed2);
                    Console.ReadLine();
                }

            }
        }
Example #9
0
 public static byte[] GetBytes(int size)
 {
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[size];
     crypto.GetNonZeroBytes(data);
     return data;
 }
Example #10
0
 /// <summary>
 /// Generates a cryptographically secure random integer
 /// </summary>
 /// <returns>https://xkcd.com/221/</returns>
 public static int randomNumber()
 {
     byte[] data = new byte[1];
     using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider())
     {
         crypto.GetNonZeroBytes(data);
         data = new byte[31];
         crypto.GetNonZeroBytes(data);
     }
     return Math.Abs(BitConverter.ToInt32(data, 0));
 }
 public static string GetUniqueKey(int maxSize)
 {
     var data = new byte[1];
     var crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[maxSize];
     crypto.GetNonZeroBytes(data);
     var result = new StringBuilder(maxSize);
     foreach (var b in data)
     {
         result.Append(Chars[b % (Chars.Length)]);
     }
     return result.ToString();
 }
 public static string GetUniqueKey(int maxSize)
 {
     char[] chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
     var data = new byte[1];
     var crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[maxSize];
     crypto.GetNonZeroBytes(data);
     var result = new StringBuilder(maxSize);
     foreach (byte b in data)
     {
         result.Append(chars[b % (chars.Length)]);
     }
     return result.ToString();
 }
Example #13
0
        /// <summary>
        /// Generate unique string with specified length.
        /// </summary>
        /// <param name="size">string length</param>
        /// <param name="time">whether generted string contains current time code</param>
        /// <returns></returns>
        public static string GenerateKey(int size, bool time)
        {
            StringBuilder sb = new StringBuilder();
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            byte[] data = new byte[size];
            crypto.GetNonZeroBytes(data);
            foreach (byte b in data)
            {
                sb.Append(KEY_CHARS[b % (KEY_CHARS.Length - 1)]);
            }

            if (time)
            {
                DateTime dt = DateTime.Now;
                sb.Append(YEAR_KEY_CHARS[dt.Year - 2000]);
                sb.Append(MONTH_KEY_CHARS[dt.Month]);
                sb.Append(DAY_KEY_CHARS[dt.Day]);
                sb.Append(HOUR_KEY_CHARS[dt.Hour]);
                sb.Append(MIN1_KEY_CHARS[dt.Minute / 10]);
                sb.Append(MIN2_KEY_CHARS[dt.Minute % 10]);
                sb.Append(SEC1_KEY_CHARS[dt.Second / 10]);
                sb.Append(SEC2_KEY_CHARS[dt.Second % 10]);
                sb.Append(MSEC1_KEY_CHARS[dt.Millisecond / 100]);
                sb.Append(MSEC2_KEY_CHARS[dt.Millisecond % 100 / 10]);
                sb.Append(MSEC3_KEY_CHARS[dt.Millisecond % 10]);
            }
            return sb.ToString();
        }
        private static string GenerateLegacySaltedHash(string input, string hashAlgorithmId)
        {
            var saltBytes = new byte[SaltLengthInBytes];

            using (var cryptoProvider = new RNGCryptoServiceProvider())
            {
                cryptoProvider.GetNonZeroBytes(saltBytes);
            }

            var textBytes = Encoding.Unicode.GetBytes(input);

            var saltedTextBytes = new byte[saltBytes.Length + textBytes.Length];
            Array.Copy(saltBytes, saltedTextBytes, saltBytes.Length);
            Array.Copy(textBytes, 0, saltedTextBytes, saltBytes.Length, textBytes.Length);

            byte[] hashBytes;
            using (var hashAlgorithm = HashAlgorithm.Create(hashAlgorithmId))
            {
                hashBytes = hashAlgorithm.ComputeHash(saltedTextBytes);
            }

            var saltPlusHashBytes = new byte[saltBytes.Length + hashBytes.Length];
            Array.Copy(saltBytes, saltPlusHashBytes, saltBytes.Length);
            Array.Copy(hashBytes, 0, saltPlusHashBytes, saltBytes.Length, hashBytes.Length);

            var saltedHash = Convert.ToBase64String(saltPlusHashBytes);
            return saltedHash;
        }
Example #15
0
            public static string ComputeHash(string plaintext, Supported_HA hash, byte[] salt)
            {
                int minSaltLength = 4;
                int maxSaltLenght = 6;
                byte[] SaltBytes = null;

                if(salt!=null)
                {
                    SaltBytes = salt;
                }
                else
                {
                    Random r = new Random();
                    int SaltLenght = r.Next(minSaltLength, maxSaltLenght);
                    SaltBytes = new byte[SaltLenght];
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                    rng.GetNonZeroBytes(SaltBytes);
                    rng.Dispose();
                }

                byte[] plaintData = ASCIIEncoding.UTF8.GetBytes(plaintext);
                byte[] plainDataAndSalt = new byte[plaintData.Length + SaltBytes.Length];

                for(int x=0; x<plaintData.Length;x++)
                {
                    plainDataAndSalt[x] = plaintData[x];
                    
                }
                for (int n = 0; n < SaltBytes.Length; n++)
                    plainDataAndSalt[plaintData.Length + n] = SaltBytes[n];

                byte[] hashValue = null;

                switch(hash)
                {
                    case Supported_HA.SHA256:
                        SHA256Managed sha= new SHA256Managed();
                        hashValue= sha.ComputeHash(plainDataAndSalt);
                        sha.Dispose();
                        break;

                    case Supported_HA.SHA384:
                        SHA384Managed sha1 = new SHA384Managed();
                        hashValue = sha1.ComputeHash(plainDataAndSalt);
                        sha1.Dispose();
                        break;
                    case Supported_HA.SHA512:
                        SHA512Managed sha2 = new SHA512Managed();
                        hashValue = sha2.ComputeHash(plainDataAndSalt);
                        sha2.Dispose();
                        break;
                }

                byte[] resuflt = new byte[hashValue.Length + SaltBytes.Length];
                for (int x = 0; x < hashValue.Length; x++)
                    resuflt[x] = hashValue[x];
                for (int n = 0; n < SaltBytes.Length; n++)
                    resuflt[hashValue.Length + n] = SaltBytes[n];
                return Convert.ToBase64String(resuflt);
            }
Example #16
0
 public static string GenerateSecureSalt()
 {
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     byte[] buffer = new byte[24];
     rng.GetNonZeroBytes(buffer);
     return Convert.ToBase64String(buffer);
 }
Example #17
0
        /// <summary>
        /// Generates a cryptographically secure block of data suitable for salting hashes.
        /// </summary>
        /// <returns>A cryptographically secure block of data suitable for salting hashes.</returns>
        public static int GenerateSalt()
        {
            const int MinSaltSize = 1;
            const int MaxSaltSize = 2;

            // Generate a random number to determine the salt size.
            Random random = new Random();
            int saltSize = random.Next(MinSaltSize, MaxSaltSize);

            // Allocate a byte array, to hold the salt.
            byte[] saltBytes = new byte[saltSize];

            // Initialize the cryptographically secure random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltBytes);

            string sSalt = string.Empty;
            int iSalt = 0;

            for (int i = 0; i < saltBytes.Count(); i++)
            {
                sSalt = String.Concat(sSalt, saltBytes[i].ToString());
            }

            iSalt = Convert.ToInt32(sSalt);

            return iSalt;
        }
Example #18
0
 /// <summary>
 /// Generates random salt.
 /// </summary>
 /// <returns></returns>
 public static string GenerateSalt()
 {
     var saltBytes = new byte[32];
     using (var provider = new RNGCryptoServiceProvider())
         provider.GetNonZeroBytes(saltBytes);
     return Convert.ToBase64String(saltBytes);
 }
        /// <summary>
        /// Encrypt the specified data using the provided key. The
        /// encrypted data will be returned as a base 64 encoded
        /// string.
        /// </summary>
        /// <param name="data">The data string to encrypt.</param>
        /// <param name="key">The key to use for encryption.</param>
        public static String Encrypt(String data, String key)
        {
            // Generate an initialization vector.
              RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
              byte[] iv = new byte[16];
              rng.GetNonZeroBytes(iv);

              byte[] dataBytes = Encoding.ASCII.GetBytes(data);
              byte[] toEncryptBytes = new byte[iv.Length + dataBytes.Length];

              // Build the data to encrypt using the iv and the source data.
              System.Array.Copy(iv, 0, toEncryptBytes, 0, iv.Length);
              System.Array.Copy(dataBytes, 0, toEncryptBytes, iv.Length, dataBytes.Length);

              RijndaelManaged cipher = new RijndaelManaged();
              cipher.KeySize = 128;
              cipher.BlockSize = 128;
              cipher.Mode = CipherMode.CBC;
              cipher.Padding = PaddingMode.PKCS7;
              cipher.IV = iv;
              cipher.Key = Encoding.ASCII.GetBytes(key);

              ICryptoTransform crypto = cipher.CreateEncryptor();
              byte[] encryptedData = crypto.TransformFinalBlock(toEncryptBytes, 0, toEncryptBytes.Length);

              return System.Convert.ToBase64String (encryptedData);
        }
Example #20
0
        public static string MiniGuid()
        {
            var chars = A.ToCharArray();
            var data = new byte[1];
            var crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            const int size = MaxSize;
            data = new byte[size];
            crypto.GetNonZeroBytes(data);
            var result = new StringBuilder(size);

            foreach (var b in data)
                result.Append(chars[b%(chars.Length - 1)]);

            return result.ToString();
        }
        public void Performance_tests()
        {
            // random write.
            var gen = new RNGCryptoServiceProvider();
            var bytes = 1024;
            var data = new byte[bytes];
            gen.GetNonZeroBytes(data);
            var stopwatch = Stopwatch.StartNew();
            var records = 200;

            var total = records * bytes;
            Console.WriteLine("Data is {0} records of {1} bytes == {2} bytes or {3} MB", records, bytes, total, total / 1024 / 1024);

            for (int i = 0; i < records; i++)
            {
                _stream.TryAppend(data);
            }

            var timeSpan = stopwatch.Elapsed;
            Console.WriteLine("Writing one by one in {0}", timeSpan.TotalSeconds);

            int counter = 0;
            var reading = Stopwatch.StartNew();
            foreach (var tapeRecord in _stream.ReadRecords(0, int.MaxValue))
            {
                counter += tapeRecord.Data.Length;
            }
            Console.WriteLine("Reading in {0} seconds", reading.Elapsed.TotalSeconds);
            Console.WriteLine("Read {0} bytes of raw data", counter);
        }
 public byte[] GenerateSalt()
 {
     var rngCrypto = new RNGCryptoServiceProvider();
     var saltBytes = new byte[64];
     rngCrypto.GetNonZeroBytes(saltBytes);
     return saltBytes;
 }
Example #23
0
        static void Main(string[] args)
        {
            var rng = new RNGCryptoServiceProvider();

            var a = new byte[16];

            for (int i = 0; i < 10; i++)
            {
                //rng.GetBytes(a);
                rng.GetNonZeroBytes(a);

                foreach (var item in a)
                {
                    Console.Write("{0,4}", item);
                }

                Console.WriteLine();
            }

            //algoritmo de criptografia: trocar letras de lugar de acordo com uma chave pré-definida

            //bcfjkmpqrsuvwxyzagnldoetih -> chave de criptografia
            //abcdefghijklmnopqrstuvwxyz

            //atacar o inimigo -> mensagem
            //blbfbgyrxrwrpy -> mensagem cifrada (encriptada, criptografada)
            //atacaroinimigo -> mensagem decifrada (decriptada)

            Console.ReadKey();
        }
 /// <summary>
 /// Generates the salt.
 /// </summary>
 /// <returns></returns>
 private static byte[] GenerateSalt()
 {
     var saltBytes = new byte[64];
     var rng = new RNGCryptoServiceProvider();
     rng.GetNonZeroBytes(saltBytes);
     return saltBytes;
 }
Example #25
0
 public string GetSalt(int saltLength)
 {
     var rng = new RNGCryptoServiceProvider();
     var saltBytes = new byte[saltLength];
     rng.GetNonZeroBytes(saltBytes);
     return BitConverter.ToString(saltBytes).Replace("-", "");
 }
Example #26
0
 public static string ComputeHash(string pwd)
 {
     byte[] salt = new byte[new Random().Next(4, 8)];
     RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
     rng.GetNonZeroBytes(salt);
     return ComputeHash(pwd, salt);
 }
Example #27
0
 public static string GenerateRandomString(int length)
 {
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     byte[] data = new byte[length];
     crypto.GetNonZeroBytes(data);
     return BitConverter.ToString(data).Replace("-", "").ToLowerInvariant();
 }
Example #28
0
        public string CreateSalt()
        {
            byte[] saltData;
            // Define min and max salt sizes.
            int minSaltSize = 4;
            int maxSaltSize = 8;

            // Generate a random number for the size of the salt.
            Random random = new Random();
            int saltSize = random.Next(minSaltSize, maxSaltSize);

            // Allocate a byte array, which will hold the salt.
            saltData = new byte[saltSize];

            // Initialize a random number generator.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

            // Fill the salt with cryptographically strong byte values.
            rng.GetNonZeroBytes(saltData);

            string result = "";
            foreach (Byte b in saltData)
            {
                result += b.ToString("X"); // convert byte to hex
            }
            return result;
        }
Example #29
0
 public static string GenerateToken()
 {
     RNGCryptoServiceProvider r = new RNGCryptoServiceProvider();
     byte[] buffer = new byte[39];
     r.GetNonZeroBytes(buffer);
     return Convert.ToBase64String(buffer);
 }
 public static string GetUniqueKey(int maxSize)
 {
     char[] chars = new char[62];
     chars = "123456789".ToCharArray();
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[maxSize];
     crypto.GetNonZeroBytes(data);
     StringBuilder result = new StringBuilder(maxSize);
     foreach (byte b in data)
     {
         result.Append(chars[b % (chars.Length)]);
     }
     return result.ToString();
 }
Example #31
0
 public static string RandomString(int length)
 {
     char[] chars = new char[62];
     chars =
     "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
     byte[] data = new byte[1];
     RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
     crypto.GetNonZeroBytes(data);
     data = new byte[length];
     crypto.GetNonZeroBytes(data);
     StringBuilder result = new StringBuilder(length);
     foreach (byte b in data)
     {
         result.Append(chars[b % (chars.Length)]);
     }
     return result.ToString();
 }
        /// <summary>
        /// Return At string Ramdom
        /// </summary>
        /// <returns>string</returns>

        public static string Aleatory(List<string> charsetSelecting, int numberOfChar)
        {            
            byte[] data = new byte[1];
            
            using (RNGCryptoServiceProvider cryptoServiceProvider = new RNGCryptoServiceProvider())
            {
                cryptoServiceProvider.GetNonZeroBytes(data);
                data = new byte[numberOfChar];
                cryptoServiceProvider.GetNonZeroBytes(data);
            }

            StringBuilder stringBuilder = new StringBuilder(numberOfChar);
            foreach (byte num in data)
                stringBuilder.Append(charsetSelecting[(int)num % charsetSelecting.Count]);

            return stringBuilder.ToString();
        }
Example #33
0
        protected void GenerateRandomDataButton_Click(object sender, EventArgs e)
        {
            // Generate random 10 byte array.
            var rnd   = new System.Security.Cryptography.RNGCryptoServiceProvider();
            var bytes = new System.Byte[10];

            rnd.GetNonZeroBytes(bytes);
            DataTextBox.Text = string.Join("", bytes.Select(x => x.ToString("X2")));
        }
Example #34
0
        public static string Salt()
        {
            var random = new byte[16];

            using (var rng = new System.Security.Cryptography.RNGCryptoServiceProvider())
            {
                rng.GetNonZeroBytes(random);
            }

            return(Convert.ToBase64String(random));
        }
Example #35
0
        public static string GetUniqueID()
        {
            int maxSize = 30;

            char[] chars = new char[62];
            string a;

            a     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            chars = a.ToCharArray();
            int size = maxSize;

            byte[] data = new byte[1];
            System.Security.Cryptography.RNGCryptoServiceProvider crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
            //crypto.GetNonZeroBytes(data);

            data = new byte[size];
            crypto.GetNonZeroBytes(data);
            System.Text.StringBuilder result = new System.Text.StringBuilder(size);
            foreach (byte b in data)
            {
                result.Append(chars[b % (chars.Length - 1)]);
            }
            return(result.ToString());
        }
Example #36
0
        private void btnGO_Click(object sender, EventArgs e)
        {
            this.Enabled = false;

            SSC.RNGCryptoServiceProvider rng = new SSC.RNGCryptoServiceProvider();
            byte[] source_length             = new byte[2];
            rng.GetNonZeroBytes(source_length);
            byte[] SOURCE = new byte[source_length[0] + (source_length[1] * 256)];
            rng.GetBytes(SOURCE);

            string hashIN = Convert.ToBase64String(new SSC.SHA1Managed().ComputeHash(SOURCE));

            // V3 V3 V3 V3

            // use these two lines for specific passphrases
            //string PASSPHRASE = "TripleSecManaged";
            //byte[] PASSPHRASE_BYTES = new UTF8Encoding().GetBytes(PASSPHRASE);

            // use these two lines for random passphrases
            byte[] PASSPHRASE_BYTES = new byte[source_length[0]];
            rng.GetBytes(PASSPHRASE_BYTES);

            byte[] stuffIN   = TripleSecManaged.V3.Encrypt(SOURCE, PASSPHRASE_BYTES);
            byte[] stuffOUT  = null;
            bool   didItWork = TripleSecManaged.V3.TryDecrypt(stuffIN, PASSPHRASE_BYTES, out stuffOUT);

            string hashOUT = didItWork ?  // don't try to do anything with stuffOUT if the function failed
                             Convert.ToBase64String(new SSC.SHA1Managed().ComputeHash(stuffOUT)) : "[null]";

            txtOutput.Clear();
            if (hashIN != hashOUT || didItWork == false)
            {
                txtOutput.AppendText("V3 FAILURE!!!\r\n" + hashIN + "\r\n" + hashOUT);
            }
            else
            {
                txtOutput.AppendText("V3 SUCCESS!!!\r\n" + hashOUT);
            }
            txtOutput.AppendText("\r\nV3 Source Length: " + SOURCE.Length);
            txtOutput.AppendText("\r\nV3 Passphrase Length: " + PASSPHRASE_BYTES.Length);
            txtOutput.AppendText("\r\n\"V3 Did It Work?\": " + didItWork);
            //txtOutput.AppendText("\r\n\r\n" + TripleSecManaged.Utilities.BytesToHexString(stuffIN));

            // V4 V4 V4 V4

            // use these two lines for specific passphrases
            //string PASSPHRASE = "TripleSecManaged";
            //byte[] PASSPHRASE_BYTES = new UTF8Encoding().GetBytes(PASSPHRASE);

            // use these two lines for random passphrases
            PASSPHRASE_BYTES = new byte[source_length[0]];
            rng.GetBytes(PASSPHRASE_BYTES);

            stuffIN   = TripleSecManaged.V4.Encrypt(SOURCE, PASSPHRASE_BYTES);
            stuffOUT  = null;
            didItWork = TripleSecManaged.V4.TryDecrypt(stuffIN, PASSPHRASE_BYTES, out stuffOUT);

            hashOUT = didItWork ?  // don't try to do anything with stuffOUT if the function failed
                      Convert.ToBase64String(new SSC.SHA1Managed().ComputeHash(stuffOUT)) : "[null]";
            if (hashIN != hashOUT || didItWork == false)
            {
                txtOutput.AppendText("\r\n\r\nV4 FAILURE!!!\r\n" + hashIN + "\r\n" + hashOUT);
            }
            else
            {
                txtOutput.AppendText("\r\n\r\nV4 SUCCESS!!!\r\n" + hashOUT);
            }
            txtOutput.AppendText("\r\nV4 Source Length: " + SOURCE.Length);
            txtOutput.AppendText("\r\nV4 Passphrase Length: " + PASSPHRASE_BYTES.Length);
            txtOutput.AppendText("\r\n\"V4 Did It Work?\": " + didItWork);

            this.Enabled = true;
        }