Exemple #1
0
        /* Good1() change the switch to switch(8) */
        private void Good1()
        {
            switch (8)
            {
            case 7:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
                break;

            default:
                using (HashAlgorithm sha512 = new SHA512CryptoServiceProvider())
                {
                    /* FIX: Secure cryptographic hashing algorithm (SHA-512) */
                    byte[] textWithUTF8           = Encoding.UTF8.GetBytes("Test Input"); /* INCIDENTAL FLAW: Hard-coded input to hash algorithm */
                    byte[] textWithReversibleHash = sha512.ComputeHash(textWithUTF8);
                    IO.WriteLine(IO.ToHex(textWithReversibleHash));
                }
                break;
            }
        }
        /* goodB2G() - use badsource and goodsink*/
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            data = ""; /* initialize data in case there are no cookies */
            /* Read data from cookies */
            {
                HttpCookieCollection cookieSources = req.Cookies;
                if (cookieSources != null)
                {
                    /* POTENTIAL FLAW: Read data from the first cookie value */
                    data = cookieSources[0].Value;
                }
            }
            for (int k = 0; k < 1; k++)
            {
                /* FIX: Hash data before storing in registry */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                    key.CreateSubKey("CWEparent");
                    key = key.OpenSubKey("CWEparent", true);
                    key.CreateSubKey("TestingCWE");
                    key = key.OpenSubKey("TestingCWE", true);
                    key.SetValue("CWE", secureData);
                }
            }
        }
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G()
        {
            string data;

            data = ""; /* Initialize data */
            {
                /* read user input from console with ReadLine */
                try
                {
                    /* POTENTIAL FLAW: Read data from the console using ReadLine */
                    data = Console.ReadLine();
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
            }
            /* FIX: Hash data before storing in registry */
            {
                string salt = "ThisIsMySalt";
                using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                {
                    byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                    byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                    data = IO.ToHex(hashedCredsAsBytes);
                }
            }
            using (SecureString secureData = new SecureString())
            {
                for (int i = 0; i < data.Length; i++)
                {
                    secureData.AppendChar(data[i]);
                }
                RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                key.CreateSubKey("CWEparent");
                key = key.OpenSubKey("CWEparent", true);
                key.CreateSubKey("TestingCWE");
                key = key.OpenSubKey("TestingCWE", true);
                key.SetValue("CWE", secureData);
            }
        }
Exemple #4
0
 /* goodB2G() - use BadSource and GoodSink */
 public static void GoodB2GSink(byte[] dataSerialized)
 {
     try
     {
         string data;
         var    binForm = new BinaryFormatter();
         using (var memStream = new MemoryStream())
         {
             memStream.Write(dataSerialized, 0, dataSerialized.Length);
             memStream.Seek(0, SeekOrigin.Begin);
             data = (string)binForm.Deserialize(memStream);
         }
         /* FIX: Hash data before storing in registry */
         {
             string salt = "ThisIsMySalt";
             using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
             {
                 byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                 byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                 data = IO.ToHex(hashedCredsAsBytes);
             }
         }
         using (SecureString secureData = new SecureString())
         {
             for (int i = 0; i < data.Length; i++)
             {
                 secureData.AppendChar(data[i]);
             }
             RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
             key.CreateSubKey("CWEparent");
             key = key.OpenSubKey("CWEparent", true);
             key.CreateSubKey("TestingCWE");
             key = key.OpenSubKey("TestingCWE", true);
             key.SetValue("CWE", secureData);
         }
     }
     catch (SerializationException exceptSerialize)
     {
         IO.Logger.Log(NLog.LogLevel.Warn, "SerializationException in deserialization", exceptSerialize);
     }
 }
Exemple #5
0
        /// <summary>
        /// Encrypts the specified text.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="key">The key.</param>
        /// <returns>String.</returns>
        /// <exception cref="ArgumentException">Thrown when text was null, empty, or white space.</exception>
        /// <exception cref="ArgumentException">Thrown when key was null, empty, or white space.</exception>
        /// <exception cref="ArgumentException">Thrown when unable to create AES crypto object.</exception>
        public String Encrypt(String text, String key)
        {
            if (String.IsNullOrEmpty(text))
            {
                throw new ArgumentException(Strings.TheTextMustHaveAValue, nameof(text));
            }
            if (String.IsNullOrEmpty(key))
            {
                throw new ArgumentException(Strings.KeyMustHaveAValue, nameof(key));
            }

            var buffer = Encoding.UTF8.GetBytes(text);

            using (var hash = new SHA512CryptoServiceProvider()) {
                var aesKey = new Byte[24];
                Buffer.BlockCopy(hash.ComputeHash(Encoding.UTF8.GetBytes(key)), 0, aesKey, 0, 24);
                using (var aes = Aes.Create()) {
                    if (aes == null)
                    {
                        throw new NullReferenceException(Strings.UnableToCreateAESCryptoObject);
                    }

                    aes.Key = aesKey;

                    using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
                        using (var resultStream = new MemoryStream()) {
                            using (var aesStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write))
                                using (var plainStream = new MemoryStream(buffer)) {
                                    plainStream.CopyTo(aesStream);
                                }

                            var result   = resultStream.ToArray();
                            var combined = new Byte[aes.IV.Length + result.Length];
                            Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length);
                            Array.ConstrainedCopy(result, 0, combined, aes.IV.Length, result.Length);

                            return(Convert.ToBase64String(combined));
                        }
                }
            }
        }
Exemple #6
0
        public string Decrypt(string value, string key)
        {
            value.ThrowIfNullOrEmpty(nameof(value));

            var combined = Convert.FromBase64String(value);
            var buffer   = new byte[combined.Length];
            var hash     = new SHA512CryptoServiceProvider();
            var aesKey   = new byte[24];

            Buffer.BlockCopy(hash.ComputeHash(Encoding.UTF8.GetBytes(key)), 0, aesKey, 0, 24);

            using (var aes = Aes.Create())
            {
                if (aes == null)
                {
                    throw new ArgumentException("Parameter must not be null.", nameof(aes));
                }

                aes.Key = aesKey;

                var iv         = new byte[aes.IV.Length];
                var ciphertext = new byte[buffer.Length - iv.Length];

                Array.ConstrainedCopy(combined, 0, iv, 0, iv.Length);
                Array.ConstrainedCopy(combined, iv.Length, ciphertext, 0, ciphertext.Length);

                aes.IV = iv;

                using (var decryptor = aes.CreateDecryptor(aes.Key, aes.IV))
                    using (var resultStream = new MemoryStream())
                    {
                        using (var aesStream = new CryptoStream(resultStream, decryptor, CryptoStreamMode.Write))
                            using (var plainStream = new MemoryStream(ciphertext))
                            {
                                plainStream.CopyTo(aesStream);
                            }

                        return(Encoding.UTF8.GetString(resultStream.ToArray()));
                    }
            }
        }
Exemple #7
0
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            while (true)
            {
                data = ""; /* initialize data in case there are no cookies */
                /* Read data from cookies */
                {
                    HttpCookieCollection cookieSources = req.Cookies;
                    if (cookieSources != null)
                    {
                        /* POTENTIAL FLAW: Read data from the first cookie value */
                        data = cookieSources[0].Value;
                    }
                }
                break;
            }
            while (true)
            {
                /* FIX: Hash data before storing in a file */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    File.WriteAllText(@"C:\Users\Public\WriteText.txt", secureData.ToString());
                }
                break;
            }
        }
Exemple #8
0
        public static string Encrypt(this string text, string key)
        {
            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException("Key must have valid value.", nameof(key));
            }
            if (string.IsNullOrEmpty(text))
            {
                throw new ArgumentException("The text must have valid value.", nameof(text));
            }

            var buffer = Encoding.UTF8.GetBytes(text);
            var hash   = new SHA512CryptoServiceProvider();
            var aesKey = new byte[24];

            Buffer.BlockCopy(hash.ComputeHash(Encoding.UTF8.GetBytes(key)), 0, aesKey, 0, 24);

            using (var aes = Aes.Create()) {
                if (aes == null)
                {
                    throw new ArgumentException("Parameter must not be null.", nameof(aes));
                }

                aes.Key = aesKey;

                using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
                    using (var resultStream = new MemoryStream()) {
                        using (var aesStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write))
                            using (var plainStream = new MemoryStream(buffer)) {
                                plainStream.CopyTo(aesStream);
                            }

                        var result   = resultStream.ToArray();
                        var combined = new byte[aes.IV.Length + result.Length];
                        Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length);
                        Array.ConstrainedCopy(result, 0, combined, aes.IV.Length, result.Length);

                        return(Convert.ToBase64String(combined));
                    }
            }
        }
 /* goodG2B() - use goodsource and badsink */
 private void GoodG2B(HttpRequest req, HttpResponse resp)
 {
     string dataCopy;
     {
         string data;
         using (SecureString securePwd = new SecureString())
         {
             using (SecureString secureUser = new SecureString())
             {
                 for (int i = 0; i < "AP@ssw0rd".Length; i++)
                 {
                     /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */
                     securePwd.AppendChar("AP@ssw0rd"[i]);
                 }
                 for (int i = 0; i < "user".Length; i++)
                 {
                     /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */
                     securePwd.AppendChar("user"[i]);
                 }
                 /* FIX: Set data to a hash of credentials */
                 {
                     string salt = "ThisIsMySalt";
                     using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                     {
                         string credentialsToHash  = secureUser.ToString() + ":" + securePwd.ToString();
                         byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, credentialsToHash));
                         byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                         data = IO.ToHex(hashedCredsAsBytes);
                     }
                 }
             }
         }
         dataCopy = data;
     }
     {
         string data = dataCopy;
         /* NOTE: potential incidental issues with not setting secure or HttpOnly flag */
         /* POTENTIAL FLAW: Store data directly in cookie */
         resp.AppendCookie(new HttpCookie("auth", data));
     }
 }
Exemple #10
0
        public Upload Create(string fname, byte[] file, int owner)
        {
            Random rnd    = new Random();
            Upload upload = new Upload()
            {
                Name   = fname,
                Date   = DateTime.Now.AddDays(rnd.Next(-100, 100)),
                Owner  = owner,
                Sha256 = _csp.ComputeHash(file)
            };

            if (!_context.Uploads.Any(x =>
                                      x.Sha256.SequenceEqual(upload.Sha256)))
            {
                upload.Blob = file;
            }
            _context.Uploads.Add(upload);
            _context.SaveChanges();

            return(upload);
        }
Exemple #11
0
        private byte[] computeHashKey(string keyData)
        {
            byte[]        keyBytes = Encoding.ASCII.GetBytes(textBoxEncryptionKey.Text);
            HashAlgorithm hashAlgorithm;

            if (comboBoxHashAlgorithm.Text == "SHA-256")
            {
                hashAlgorithm = new SHA256CryptoServiceProvider();
                return(hashAlgorithm.ComputeHash(keyBytes));
            }
            else if (comboBoxHashAlgorithm.Text == "SHA-512")
            {
                hashAlgorithm = new SHA512CryptoServiceProvider();
                return(hashAlgorithm.ComputeHash(keyBytes));
            }
            else
            {
                hashAlgorithm = new MD5CryptoServiceProvider();
                return(hashAlgorithm.ComputeHash(keyBytes));
            }
        }
        public override void Bad()
        {
            switch (7)
            {
            case 7:
                using (HashAlgorithm sha = new SHA512CryptoServiceProvider())
                {
                    /* FLAW: SHA512 with no salt */
                    byte[] textWithoutSaltBytes = Encoding.UTF8.GetBytes("hash me");
                    byte[] hashedBytes          = sha.ComputeHash(textWithoutSaltBytes);
                    sha.Clear();
                    IO.WriteLine(IO.ToHex(hashedBytes));
                }
                break;

            default:
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
                IO.WriteLine("Benign, fixed string");
                break;
            }
        }
    // --------------------------------------------------------------------------------------
    //170830 para hashear novamente o identifierID (que vem como hash5 mas foi facilmente decriptado)
    //       em: https://stackoverflow.com/questions/43042428/sha256-is-returning-invalid-characters-in-the-hash
    //
    static string GetHash(string input)
    {           //SHA512 sha512Hash = SHA512.Create();   NullReferenceException: Object reference not set to an instance of an object
                //Em https://stackoverflow.com/questions/30055358/md5-gethash-work-only-in-unity-editor :
                //MD5.Create() doesn't return an object on Unity Android when the Stripping Level is set to Micro mscorlib, but 'new MD5CryptoServiceProvider()' does.
        var sha512Hash = new SHA512CryptoServiceProvider();

        // Convert the input string to a byte array and compute the hash.//
        byte[] data = sha512Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return(sBuilder.ToString());
    }
Exemple #14
0
        /*Hash a string using SAH512.*/
        public static string HashString(string toHash)
        {
            using (SHA512CryptoServiceProvider sha = new SHA512CryptoServiceProvider())
            {
                byte[] dataToHash = Encoding.UTF8.GetBytes(toHash);
                byte[] hashed     = sha.ComputeHash(dataToHash);

                // Create a new Stringbuilder to collect the bytes
                // and create a string.
                StringBuilder sBuilder = new StringBuilder();

                // Loop through each byte of the hashed data
                // and format each one as a hexadecimal string.
                for (int i = 0; i < hashed.Length; i++)
                {
                    sBuilder.Append(hashed[i].ToString("x2"));
                }

                return(sBuilder.ToString());
            }
        }
Exemple #15
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="Path"></param>
 /// <param name="Uppercase"></param>
 /// <param name="Error"></param>
 /// <returns></returns>
 public static string FILEtoSHA512(string Path, bool Uppercase = false, string Error = Constants.ErrorMessage)
 {
     try
     {
         if (File.Exists(Path))
         {
             using SHA512 SHA512     = new SHA512CryptoServiceProvider();
             using FileStream Stream = File.OpenRead(Path);
             byte[] Hash = SHA512.ComputeHash(Stream);
             return(Uppercase == false?BitConverter.ToString(Hash).Replace("-", "").ToLowerInvariant() : BitConverter.ToString(Hash).Replace("-", "").ToUpperInvariant());
         }
         else
         {
             return(Error);
         }
     }
     catch
     {
         return(Error + Constants.ErrorTitle + "HH-FTS4!)");
     }
 }
        private static byte[] CalculateHash(string password, ref byte[] salt)
        {
            if (!salt.Any(v => v != 0))
            {
                RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
                rng.GetBytes(salt);
            }

            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);

            byte[] hashPlaintext = new byte[salt.Length + passwordBytes.Length];

            passwordBytes.CopyTo(hashPlaintext, 0);
            salt.CopyTo(hashPlaintext, passwordBytes.Length);

            SHA512CryptoServiceProvider sha = new SHA512CryptoServiceProvider();

            byte[] hash = sha.ComputeHash(hashPlaintext);

            return(hash);
        }
 /* goodB2G() - use badsource and goodsink */
 public static void GoodB2GSink(string data)
 {
     /* FIX: Hash data before storing in a file */
     {
         string salt = "ThisIsMySalt";
         using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
         {
             byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
             byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
             data = IO.ToHex(hashedCredsAsBytes);
         }
     }
     using (SecureString secureData = new SecureString())
     {
         for (int i = 0; i < data.Length; i++)
         {
             secureData.AppendChar(data[i]);
         }
         File.WriteAllText(@"C:\Users\Public\WriteText.txt", secureData.ToString());
     }
 }
Exemple #18
0
 /// <summary>
 /// 计算SHA-512码
 /// </summary>
 /// <param name="word">字符串</param>
 /// <param name="toUpper">返回哈希值格式 true:英文大写,false:英文小写</param>
 /// <returns></returns>
 public static string Hash_SHA_512(string word, bool toUpper = true)
 {
     try
     {
         SHA512CryptoServiceProvider SHA512CSP = new SHA512CryptoServiceProvider();
         byte[] bytValue = Encoding.UTF8.GetBytes(word);
         byte[] bytHash  = SHA512CSP.ComputeHash(bytValue);
         SHA512CSP.Clear();
         //根据计算得到的Hash码翻译为SHA-1码
         string sHash = "", sTemp = "";
         for (int counter = 0; counter < bytHash.Length; counter++)
         {
             long i = bytHash[counter] / 16;
             if (i > 9)
             {
                 sTemp = ((char)(i - 10 + 0x41)).ToString();
             }
             else
             {
                 sTemp = ((char)(i + 0x30)).ToString();
             }
             i = bytHash[counter] % 16;
             if (i > 9)
             {
                 sTemp += ((char)(i - 10 + 0x41)).ToString();
             }
             else
             {
                 sTemp += ((char)(i + 0x30)).ToString();
             }
             sHash += sTemp;
         }
         //根据大小写规则决定返回的字符串
         return(toUpper ? sHash : sHash.ToLower());
     }
     catch (Exception ex)
     {
         throw new Exception(ex.Message);
     }
 }
Exemple #19
0
        private static byte[] Encrypt(byte[] data, out byte[] key)
        {
            key = Hash(data);
            if (key is null)
            {
                throw new ArgumentException("Key must have valid value.", nameof(key));
            }
            if (data is null)
            {
                throw new ArgumentException("The text must have valid value.", nameof(data));
            }

            byte[] buffer = data;
            SHA512CryptoServiceProvider hash = new SHA512CryptoServiceProvider();

            byte[] aesKey = new byte[24];
            Buffer.BlockCopy(hash.ComputeHash(key), 0, aesKey, 0, 24);

            using Aes aes = Aes.Create();
            if (aes == null)
            {
                throw new ArgumentException("Parameter must not be null.", nameof(aes));
            }

            aes.Key = aesKey;

            using ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
            using MemoryStream resultStream  = new MemoryStream();
            using (CryptoStream aesStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write))
            {
                using MemoryStream plainStream = new MemoryStream(buffer);
                plainStream.CopyTo(aesStream);
            }

            byte[] result   = resultStream.ToArray();
            byte[] combined = new byte[aes.IV.Length + result.Length];
            Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length);
            Array.ConstrainedCopy(result, 0, combined, aes.IV.Length, result.Length);
            return(combined);
        }
        public static string Hash(string text, HashingMode mode)
        {
            var textBytes = Encoding.UTF8.GetBytes(text);

            byte[] hashBytes;
            switch (mode)
            {
            case HashingMode.SHA_1:
                var SHA1 = new SHA1CryptoServiceProvider();
                hashBytes = SHA1.ComputeHash(textBytes);
                break;

            case HashingMode.SHA_2_256:
                var SHA2_256 = new SHA256CryptoServiceProvider();
                hashBytes = SHA2_256.ComputeHash(textBytes);
                break;

            case HashingMode.SHA_2_512:
                var SHA2_512 = new SHA512CryptoServiceProvider();
                hashBytes = SHA2_512.ComputeHash(textBytes);
                break;

            //case HashingMode.SHA_3_256:
            //    var SHA3_256 = new Sha3Digest(256);
            //    SHA3_256.Update(Convert.ToByte(textBytes));
            //    SHA3_256.DoFinal(hashBytes);
            //    break;
            //case HashingMode.SHA_3_256:
            //    var SHA3_512 = new Sha3Digest(512);
            //    break;
            default:
                var SHA_default = new SHA1CryptoServiceProvider();
                hashBytes = SHA_default.ComputeHash(textBytes);
                break;
            }

            var hash = HelperFunctions.FromByteToHex(hashBytes);

            return(hash);
        }
 /* goodB2G() - use badsource and goodsink */
 private void GoodB2G(HttpRequest req, HttpResponse resp)
 {
     string dataCopy;
     {
         string data;
         using (SecureString securePwd = new SecureString())
         {
             using (SecureString secureUser = new SecureString())
             {
                 for (int i = 0; i < "AP@ssw0rd".Length; i++)
                 {
                     /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */
                     securePwd.AppendChar("AP@ssw0rd"[i]);
                 }
                 for (int i = 0; i < "user".Length; i++)
                 {
                     /* INCIDENTAL: CWE-798 Use of Hard-coded Credentials */
                     securePwd.AppendChar("user"[i]);
                 }
                 /* POTENTIAL FLAW: Set data to credentials (without hashing or encryption) */
                 data = secureUser.ToString() + ":" + securePwd.ToString();
             }
         }
         dataCopy = data;
     }
     {
         string data = dataCopy;
         /* FIX: Hash data before storing in cookie */
         {
             string salt = "ThisIsMySalt";
             using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
             {
                 byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                 byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                 data = IO.ToHex(hashedCredsAsBytes);
             }
         }
         resp.AppendCookie(new HttpCookie("auth", data));
     }
 }
Exemple #22
0
        protected override void Seed(DatabaseContext context)
        {
            var sha512CryptoProvider = new SHA512CryptoServiceProvider();

            var user = new UserEntity
            {
                Username     = "******",
                PasswordHash = sha512CryptoProvider.ComputeHash(Encoding.ASCII.GetBytes("Password123")),
                IsActive     = true,
                //Role = "Admin",
                CreateDate     = DateTime.Now,
                LastUpdateDate = DateTime.Now,
                Profile        = new UserProfileEntity
                {
                    FirstName      = "John",
                    LastName       = "Doe",
                    EmailAddress   = "*****@*****.**",
                    CreateDate     = DateTime.Now,
                    LastUpdateDate = DateTime.Now
                },
                CreatedBy = new List <IssueEntity>
                {
                    new IssueEntity
                    {
                        Type           = "Bug",
                        Status         = "InProgress",
                        Priority       = "High",
                        Title          = "Test Issue Title",
                        Description    = "Test Issue Description",
                        CreateDate     = DateTime.Now,
                        LastUpdateDate = DateTime.Now
                    }
                }
            };

            context.Users.Add(user);

            base.Seed(context);
        }
Exemple #23
0
        } //compute hash from arguments and return hash value as string

        private static string GetSHA512Hash(string text)
        {
            //create variables for computing hash and making it a string
            UnicodeEncoding UniCode = new UnicodeEncoding();

            byte[] HashResult;
            byte[] msg        = UniCode.GetBytes(text);
            SHA512 hashString = new SHA512CryptoServiceProvider();
            string Str        = "";

            //compute hash with SHA512 module and format output as string
            //convert bytes in HashResult to string values
            HashResult = hashString.ComputeHash(msg);
            foreach (byte x in HashResult)
            {
                Str += String.Format("{0:x2}", x);
            }

            //clear excess resource usage
            hashString.Clear();
            return(Str);
        } //compute hash from arguments and return hash value as string
Exemple #24
0
        public static string Encrypt(this string text, string key)
        {
            var buffer = Encoding.UTF8.GetBytes(text);

            var hash = new SHA512CryptoServiceProvider();

            var aesKey = new byte[24];

            Buffer.BlockCopy(hash.ComputeHash(Encoding.UTF8.GetBytes(key)), 0, aesKey, 0, 24);

            using (var aes = Aes.Create())
            {
                aes.Key = aesKey;

                using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))

                    using (var resultStream = new MemoryStream())
                    {
                        using (var aesStream = new CryptoStream(resultStream, encryptor, CryptoStreamMode.Write))

                            using (var plainStream = new MemoryStream(buffer))
                            {
                                plainStream.CopyTo(aesStream);
                            }

                        var result = resultStream.ToArray();

                        var combined = new byte[aes.IV.Length + result.Length];

                        Array.ConstrainedCopy(aes.IV, 0, combined, 0, aes.IV.Length);

                        Array.ConstrainedCopy(result, 0, combined, aes.IV.Length, result.Length);

                        var resultado = Convert.ToBase64String(combined);

                        return(resultado);
                    }
            }
        }
Exemple #25
0
 private void GoodB2G1Sink(string data, HttpRequest req, HttpResponse resp)
 {
     if (goodB2G1Private)
     {
         /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
         IO.WriteLine("Benign, fixed string");
     }
     else
     {
         /* FIX: Hash data before storing in cookie */
         {
             string salt = "ThisIsMySalt";
             using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
             {
                 byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                 byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                 data = IO.ToHex(hashedCredsAsBytes);
             }
         }
         resp.AppendCookie(new HttpCookie("auth", data));
     }
 }
Exemple #26
0
 protected override PasswdBase Secret()
 {
     if (this.date.VersionHash == "")
     {
         throw new Exception("the VERSION is not set");
     }
     using (HMACSHA512 hash512 = new HMACSHA512()) {
         using (RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider()) {
             Random     cntRnd = new Random();
             CryExtInfo extra  = new CryExtInfo();
             extra.Count = cntRnd.Next(this.MinCount, this.MaxCount);
             extra.Salt  = new byte[64];
             //fill the Randomize salt ,the Salt's length is
             //512bit
             rnd.GetNonZeroBytes(extra.Salt);
             using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider()) {
                 byte[] KeyBuffer = new byte[64];
                 rnd.GetNonZeroBytes(KeyBuffer);
                 KeyBuffer           = sha512.ComputeHash(KeyBuffer);
                 extra.Key           = KeyBuffer;
                 hash512.Key         = KeyBuffer;
                 this.date.ExtraInfo = extra;
                 byte[] pwdBuffer;
                 byte[] pwdDate = Encoding.UTF8.GetBytes(this.Password);
                 //now we add the salt to the string
                 byte[] pwdWithSalt = new byte[pwdDate.Length + extra.Salt.Length];
                 Array.Copy(pwdDate, pwdWithSalt, pwdDate.Length);
                 Array.Copy(extra.Salt, 0, pwdWithSalt, pwdDate.Length, extra.Salt.Length);
                 pwdBuffer = hash512.ComputeHash(pwdWithSalt);
                 for (int i = 0; i <= extra.Count; i++)
                 {
                     pwdBuffer = hash512.ComputeHash(pwdBuffer);
                 }
                 this.date.Password = pwdBuffer;
             }
         }
     }
     return(this.date);
 }
Exemple #27
0
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            while (true)
            {
                data = ""; /* initialize data in case id is not in query string */
                /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
                {
                    if (req.QueryString["id"] != null)
                    {
                        data = req.QueryString["id"];
                    }
                }
                break;
            }
            while (true)
            {
                /* FIX: Hash data before storing in a file */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    File.WriteAllText(@"C:\Users\Public\WriteText.txt", secureData.ToString());
                }
                break;
            }
        }
        /* goodB2G() - use badsource and goodsink */
        private void GoodB2G()
        {
            string data;

            while (true)
            {
                /* get environment variable ADD */
                /* POTENTIAL FLAW: Read data from an environment variable */
                data = Environment.GetEnvironmentVariable("ADD");
                break;
            }
            while (true)
            {
                /* FIX: Hash data before storing in registry */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                    key.CreateSubKey("CWEparent");
                    key = key.OpenSubKey("CWEparent", true);
                    key.CreateSubKey("TestingCWE");
                    key = key.OpenSubKey("TestingCWE", true);
                    key.SetValue("CWE", secureData);
                }
                break;
            }
        }
Exemple #29
0
        /* goodB2G() - use badsource and goodsink*/
        private void GoodB2G()
        {
            string data;

            data = ""; /* Initialize data */
            {
                /* read user input from console with ReadLine */
                try
                {
                    /* POTENTIAL FLAW: Read data from the console using ReadLine */
                    data = Console.ReadLine();
                }
                catch (IOException exceptIO)
                {
                    IO.Logger.Log(NLog.LogLevel.Warn, exceptIO, "Error with stream reading");
                }
            }
            for (int k = 0; k < 1; k++)
            {
                /* FIX: Hash data before storing in a file */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    File.WriteAllText(@"C:\Users\Public\WriteText.txt", secureData.ToString());
                }
            }
        }
Exemple #30
0
        /* goodB2G() - use badsource and goodsink*/
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            string data;

            data = ""; /* initialize data in case id is not in query string */
            /* POTENTIAL FLAW: Parse id param out of the URL querystring (without using getParameter()) */
            {
                if (req.QueryString["id"] != null)
                {
                    data = req.QueryString["id"];
                }
            }
            for (int k = 0; k < 1; k++)
            {
                /* FIX: Hash data before storing in registry */
                {
                    string salt = "ThisIsMySalt";
                    using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
                    {
                        byte[] buffer             = Encoding.UTF8.GetBytes(string.Concat(salt, data));
                        byte[] hashedCredsAsBytes = sha512.ComputeHash(buffer);
                        data = IO.ToHex(hashedCredsAsBytes);
                    }
                }
                using (SecureString secureData = new SecureString())
                {
                    for (int i = 0; i < data.Length; i++)
                    {
                        secureData.AppendChar(data[i]);
                    }
                    RegistryKey key = Registry.CurrentUser.OpenSubKey("Software", true);
                    key.CreateSubKey("CWEparent");
                    key = key.OpenSubKey("CWEparent", true);
                    key.CreateSubKey("TestingCWE");
                    key = key.OpenSubKey("TestingCWE", true);
                    key.SetValue("CWE", secureData);
                }
            }
        }