/* goodB2G() - use BadSource and GoodSink */
        public static void GoodB2GSink(LinkedList <string> dataLinkedList)
        {
            string data = dataLinkedList.Last.Value;

            /* 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());
            }
        }
Пример #2
0
        public string Encrypt(string message)
        {
            SHA512 sha512 = new SHA512CryptoServiceProvider();

            try
            {
                sha512.ComputeHash(ASCIIEncoding.ASCII.GetBytes(message));

                byte[] result = sha512.Hash;

                StringBuilder hash = new StringBuilder();
                for (int i = 0; i < result.Length; i++)
                {
                    hash.Append(result[i].ToString("x2"));
                }

                return(hash.ToString());
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Пример #3
0
        /* Given an input seed, derive the required output.
         */

        private static void DeriveParams(byte[] seed, out byte[] key, out byte[] iv, out string ident)
        {
            // Hash the output using sha512
            byte[] seed_output;

            using (SHA512CryptoServiceProvider sha512csp = new SHA512CryptoServiceProvider())
            {
                seed_output = sha512csp.ComputeHash(seed);
            }

            // Take key from first 32 bytes
            key = new byte[32];
            Buffer.BlockCopy(seed_output, 0, key, 0, 32);

            // Take IV from next 16 bytes
            iv = new byte[16];
            Buffer.BlockCopy(seed_output, 32, iv, 0, 16);

            // Take server identifier (the "ident") from last 16 bytes and base64url encode it
            byte[] ident_raw = new byte[16];
            Buffer.BlockCopy(seed_output, 48, ident_raw, 0, 16);
            ident = UrlBase64Encode(ident_raw);
        }
Пример #4
0
        public string CalculatePasswordHash(string userName, int userID, string password)
        {
            SHA512 hashProvider512 = SHA512CryptoServiceProvider.Create();
            SHA256 hashProvider256 = SHA256CryptoServiceProvider.Create();

            string salt = userID.ToString() + userName;                                                        // construct the salt from the useriD + username

            byte[] saltBytes = new byte[salt.Length * sizeof(char)];                                           // initialise new bytearray, size of the string times size of each char
            System.Buffer.BlockCopy(salt.ToCharArray(), 0, saltBytes, 0, salt.Length);                         // don't use encoding, just copy pure byte data

            byte[] saltHash       = hashProvider256.ComputeHash(saltBytes);                                    // compute the hash from the salt string
            string saltString     = Convert.ToBase64String(saltHash);                                          // convert the hash back to a string
            string passwordString = password + saltString;                                                     // construct the complete password from the password and the saltstring

            byte[] passwordBytes = new byte[passwordString.Length * sizeof(char)];                             // and initialise the new bytearray
            System.Buffer.BlockCopy(passwordString.ToCharArray(), 0, passwordBytes, 0, passwordString.Length); // copy it over


            byte[] passwordHash       = hashProvider512.ComputeHash(passwordBytes); // generate the final hash
            string passwordHashString = Convert.ToBase64String(passwordHash);       // and transform that back into a stringr

            return(passwordHashString);
        }
Пример #5
0
 public string EncryptSha(string text, int repeatCount = 11)
 {
     try
     {
         x++;
         SHA512        sha       = new SHA512CryptoServiceProvider();
         byte[]        shaAsByte = sha.ComputeHash(Encoding.UTF8.GetBytes(text));
         StringBuilder sb        = new StringBuilder();
         foreach (var item in shaAsByte)
         {
             sb.Append(item.ToString("x2"));
         }
         if (x <= repeatCount)
         {
             EncryptSha(sb.ToString(), repeatCount);
         }
         return(sb.ToString());
     }
     catch
     {
         return("");
     }
 }
        /* goodB2G() - use badsource and goodsink */
        public static void GoodB2GSink()
        {
            string data = CWE313_Cleartext_Storage_in_a_File_or_on_Disk__NetClient_68a.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());
            }
        }
Пример #7
0
        public static string Hash(int algorithm, string planeText)
        {
            HashAlgorithm hash;

            switch (algorithm)
            {
            case SHA128:
                hash = new SHA1CryptoServiceProvider();
                break;

            case SHA256:
                hash = new SHA256CryptoServiceProvider();
                break;

            case SHA384:
                hash = new SHA384CryptoServiceProvider();
                break;

            case SHA512:
                hash = new SHA512CryptoServiceProvider();
                break;

            default:
                throw new NoSuchAlgorithmException(planeText + ": Not Found");
            }
            Encoding encoding = Encoding.UTF8;

            byte[] plane    = encoding.GetBytes(planeText);
            var    sBuilder = new StringBuilder();

            byte[] hashed = hash.ComputeHash(plane);
            for (int i = 0; i < hashed.Length; i++)
            {
                sBuilder.Append(hashed[i].ToString("x2"));
            }
            return(sBuilder.ToString());
        }
Пример #8
0
 /* goodB2G() - use badsource and goodsink */
 private void GoodB2G()
 {
     string dataCopy;
     {
         string data;
         /* get environment variable ADD */
         /* POTENTIAL FLAW: Read data from an environment variable */
         data     = Environment.GetEnvironmentVariable("ADD");
         dataCopy = data;
     }
     {
         string data = dataCopy;
         /* 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(HttpRequest req, HttpResponse resp)
 {
     string dataCopy;
     {
         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"];
             }
         }
         dataCopy = data;
     }
     {
         string data = dataCopy;
         /* 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());
         }
     }
 }
        /* goodB2G() - use badsource and goodsink*/
        private void GoodB2G(HttpRequest req, HttpResponse resp)
        {
            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();
                }
            }
            for (int k = 0; k < 1; k++)
            {
                /* 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));
            }
        }
Пример #11
0
        private String CalcularHashSHA512(Stream sArquivo)
        {
            byte[] hashSHA512 = null;
            try
            {
                try
                {
                    SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider();
                    sArquivo.Position = 0;
                    hashSHA512        = sha512.ComputeHash(sArquivo);
                }
                catch (Exception ex)
                {
                    this.MudarText(ckbSHA512, "SHA512  Erro");
                    if (this.InvokeRequired)
                    {
                        this.BeginInvoke(new MethodExibirHash(ExibirHash), ex.Message);
                    }
                    MessageBox.Show(ex.Message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "ERRO", MessageBoxButtons.OK, MessageBoxIcon.Error);
                if (this.InvokeRequired)
                {
                    this.BeginInvoke(new MethodExibirHash(ExibirHash), ex.Message);
                }
                throw new Exception(ex.Message, ex.InnerException);
            }

            String hashSHA512Text = BitConverter.ToString(hashSHA512).Replace("-", "");

            this.ExibirHash(hashSHA512Text);
            this.MudarText(ckbSHA512, "SHA512");
            return(hashSHA512Text);
        }
        /* goodB2G2() - use badsource and goodsink by reversing statements in second if  */
        private void GoodB2G2(HttpRequest req, HttpResponse resp)
        {
            string data;

            if (privateFive == 5)
            {
                /* POTENTIAL FLAW: Read data from a querystring using Params.Get */
                data = req.Params.Get("name");
            }
            else
            {
                /* INCIDENTAL: CWE 561 Dead Code, the code below will never run
                 * but ensure data is inititialized before the Sink to avoid compiler errors */
                data = null;
            }
            if (privateFive == 5)
            {
                /* 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());
                }
            }
        }
Пример #13
0
        public static string ComputeHash(string msg)
        {
            string result    = string.Empty;
            var    md5       = new MD5CryptoServiceProvider();
            var    sha1      = new SHA1CryptoServiceProvider();
            var    sha256    = new SHA256CryptoServiceProvider();
            var    sha384    = new SHA384CryptoServiceProvider();
            var    sha512    = new SHA512CryptoServiceProvider();
            var    ripemd160 = new RIPEMD160Managed();

            var source = System.Text.UTF8Encoding.Default.GetBytes(msg);

            var algorithms = new Dictionary <string, HashAlgorithm>();

            algorithms["md5"]       = md5;
            algorithms["sha1"]      = sha1;
            algorithms["sha256"]    = sha256;
            algorithms["sha384"]    = sha384;
            algorithms["sha512"]    = sha512;
            algorithms["ripemd160"] = ripemd160;

            result = Convert.ToBase64String(sha512.ComputeHash(source));
            return(result);
        }
Пример #14
0
        /// <summary>
        /// Generate SHA512 hash string.
        /// </summary>
        /// <param name="str">A string</param>
        /// <returns>Generated hash</returns>
        public static string HashString(string str)
        {
            var cryptoServiceProvider = new SHA512CryptoServiceProvider();

            var cryptoString = Encoding.UTF8.GetBytes(str);

            var hash = cryptoServiceProvider.ComputeHash(cryptoString);

            var ret = "";

            foreach (var a in hash)
            {
                if (a < 16)
                {
                    ret += "0" + a.ToString("x");
                }
                else
                {
                    ret += a.ToString("x");
                }
            }

            return(ret);
        }
Пример #15
0
        /// <summary>
        /// Metodo para generar un token binario(Tipo no base2)
        /// </summary>
        /// <param name="idReceptor"></param>
        /// <returns></returns>
        public string generarTokenBinario(string consecutivo)
        {
            string resultado = "";

            //Se inicializa el proveedor de servicio
            SHA512CryptoServiceProvider proServ = new SHA512CryptoServiceProvider();

            try
            {
                //Se obtienen los bytes del consecutivo
                byte[] tokenBytes = System.Text.Encoding.UTF8.GetBytes(consecutivo);
                //Se aplica el hash
                byte[] tokBytes = proServ.ComputeHash(tokenBytes);
                //Se limpia el proveedor de servicios
                proServ.Clear();

                resultado = Convert.ToBase64String(tokBytes);
            }
            catch (Exception)
            {
            }

            return(resultado);
        }
Пример #16
0
 private void GoodB2G2Sink(string data, HttpRequest req, HttpResponse resp)
 {
     if (goodB2G2Private)
     {
         /* 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());
         }
     }
 }
        /* 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"];
                }
            }
            /* 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);
            }
        }
Пример #18
0
        /// <summary>
        /// 创建Hash算法
        /// </summary>
        /// <param name="hashProvider"></param>
        /// <returns></returns>
        internal static HashAlgorithm CreateHashAlgorithm(EnumHashProvider hashProvider)
        {
            HashAlgorithm hashAlgorithm = null;

            switch (hashProvider)
            {
            case EnumHashProvider.MD5CryptoServiceProvider:
                hashAlgorithm = new MD5CryptoServiceProvider();
                break;

            case EnumHashProvider.RIPEMD160Managed:
                hashAlgorithm = new RIPEMD160Managed();
                break;

            case EnumHashProvider.SHA1CryptoServiceProvider:
                hashAlgorithm = new SHA1CryptoServiceProvider();
                break;

            case EnumHashProvider.SHA1Managed:
                hashAlgorithm = new SHA1Managed();
                break;

            case EnumHashProvider.SHA256Managed:
                hashAlgorithm = new SHA256CryptoServiceProvider();
                break;

            case EnumHashProvider.SHA384Managed:
                hashAlgorithm = new SHA384CryptoServiceProvider();
                break;

            case EnumHashProvider.SHA512Managed:
                hashAlgorithm = new SHA512CryptoServiceProvider();
                break;
            }
            return(hashAlgorithm);
        }
Пример #19
0
        private void RequestFileChunk()
        {
            if (fileStream.Length < length)
            {
                var stream = new MemoryStream();
                var writer = new BinaryWriter(stream);

                writer.Write((byte)MessageType.FileRequest);
                writer.Write(fileStream.Length);
                SendPacket(stream.ToArray());
            }
            else
            {
                fileStream.Close();
                fileStream = File.OpenRead(tempPath);
                var hash = new SHA512CryptoServiceProvider().ComputeHash(fileStream);
                fileStream.Close();
                var myHashName = "";
                foreach (var b in hash)
                {
                    myHashName += b.ToString("x2");
                }
                if (hashName == myHashName)
                {
                    File.Delete(filePath);
                    File.Move(tempPath, filePath);
                    SendPacket(new byte[] { (byte)MessageType.FileReceived });
                }
                else
                {
                    File.Delete(tempPath);
                    fileStream = File.OpenWrite(tempPath);
                    RequestFileChunk();
                }
            }
        }
 /* Good1() changes PRIVATE_CONST_FIVE==5 to PRIVATE_CONST_FIVE!=5 */
 private void Good1()
 {
     if (PRIVATE_CONST_FIVE != 5)
     {
         /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
         IO.WriteLine("Benign, fixed string");
     }
     else
     {
         using (HashAlgorithm sha = new SHA512CryptoServiceProvider())
         {
             /* FIX: Use a sufficiently random salt */
             var salt = new byte[32];
             using (var random = new RNGCryptoServiceProvider())
             {
                 random.GetNonZeroBytes(salt);
                 byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt));
                 byte[] hashedBytes       = sha.ComputeHash(textWithSaltBytes);
                 sha.Clear();
                 IO.WriteLine(IO.ToHex(hashedBytes));
             }
         }
     }
 }
Пример #21
0
        private static string Decrypt(string connectionString)
        {
            if (Cipher == null || Cipher.Length == 0)
            {
                return(connectionString);
            }
            else
            {
                // Preserve FIPS compliance
                SHA512 hashProvider;
                if (Environment.OSVersion.Version.Major > 5 || (Environment.OSVersion.Version.Major == 5 && Environment.OSVersion.Version.Minor >= 2))
                {
                    hashProvider = new SHA512CryptoServiceProvider();
                }
                else
                {
                    hashProvider = new SHA512Managed();
                }

                using (var hash = hashProvider)
                    using (var cipher = new Rfc2898DeriveBytes(Cipher, hash.ComputeHash(Cipher), 3))
                        using (var decryptor = new AesCryptoServiceProvider())
                        {
                            var key = cipher.GetBytes(decryptor.KeySize / 8);
                            var iv  = cipher.GetBytes(decryptor.BlockSize / 8);
                            var dec = decryptor.CreateDecryptor(key, iv);

                            var connectionStringBytes = Convert.FromBase64String(connectionString);             // Reading from config file is always in Base64

                            // ToDo: check here for wrong password w/ System.Security.Cryptography.HMAC (catch the exception and display a meaningful message to the developer - or swallow the error)
                            var decryptedBytes = dec.TransformFinalBlock(connectionStringBytes, 0, connectionStringBytes.Length);

                            return(Encoding.UTF8.GetString(decryptedBytes));
                        }
            }
        }
Пример #22
0
        public static int AuthenticateUser(string userName, string userPassword)
        {
            byte[]           passwordHash;
            byte[]           salt;
            string           find = "select * from dbo.Users where Username=@Username";
            List <UserModel> user;
            UserModel        data = new UserModel
            {
                Username = userName,
            };

            user = SqlDataAccess.LoadData(find, data);
            if (user.Count() != 0 & userPassword != null)
            {
                salt = user[0].Salt;
                using (var sha = new SHA512CryptoServiceProvider())
                {
                    var hashdata = Encoding.ASCII.GetBytes(userPassword).Concat(salt).ToArray <byte>();

                    var shadata = sha.ComputeHash(hashdata);
                    passwordHash = shadata;
                }
                if (passwordHash.SequenceEqual(user[0].Password))
                {
                    return(user[0].Id);
                }
                else
                {
                    return(0);
                }
            }
            else
            {
                return(0);
            }
        }
        /* 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 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());
                }
            }
        }
Пример #24
0
 private static string SHA512Crypt(string txt, Encoding encoding = null)
 {
     try
     {
         encoding = encoding ?? Encoding.UTF8;
         if (string.IsNullOrEmpty(txt))
         {
             throw new Exception("原文不能为空!");
         }
         SHA512CryptoServiceProvider sha = new SHA512CryptoServiceProvider();
         byte[] org    = encoding.GetBytes(txt);
         byte[] output = sha.ComputeHash(org);
         string retStr = "";
         for (int i = 0; i < output.Length; i++)
         {
             retStr += output[i].ToString("x2");
         }
         return(retStr);
     }
     catch (Exception)
     {
         throw;
     }
 }
Пример #25
0
 /* goodB2G() - use BadSource and GoodSink */
 public static void GoodB2GSink(byte[] dataSerialized, HttpRequest req, HttpResponse resp)
 {
     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 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());
         }
     }
     catch (SerializationException exceptSerialize)
     {
         IO.Logger.Log(NLog.LogLevel.Warn, "SerializationException in deserialization", exceptSerialize);
     }
 }
Пример #26
0
        /// <summary>
        /// Read the file and calculate the checksum
        ///</summary>
        /// <param name="type">the hash type to use</param>
        /// <param name="fileName">the file to read</param>
        /// <returns>the hex representation of the hash using uppercase chars</returns>
        public static String getFileHash(HashType type, String fileName)
        {
            try
            {
                var HashValue = new byte[0];

                using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                {
                    switch (type)
                    {
                    case HashType.MD5:
                        using (var h = new MD5CryptoServiceProvider()) { HashValue = h.ComputeHash(fileStream); }
                        break;

                    case HashType.SHA1:
                        using (var h = new SHA1CryptoServiceProvider()) { HashValue = h.ComputeHash(fileStream); }
                        break;

                    case HashType.SHA256:
                        using (var h = new SHA256CryptoServiceProvider()) { HashValue = h.ComputeHash(fileStream); }
                        break;

                    case HashType.SHA384:
                        using (var h = new SHA384CryptoServiceProvider()) { HashValue = h.ComputeHash(fileStream); }
                        break;

                    case HashType.SHA512:
                        using (var h = new SHA512CryptoServiceProvider()) { HashValue = h.ComputeHash(fileStream); }
                        break;
                    }
                }

                return(BitConverter.ToString(HashValue).Replace("-", String.Empty));
            }
            catch (Exception ex) { return(ex.Message); }
        }
        /* 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 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());
            }
        }
Пример #28
0
        public string SHA512_Encoding(string s)
        {
            try
            {
                String strData = "";

                byte[] plainTextBytes = Ecd_.GetBytes(s);

                HashAlgorithm Hash;
                Hash = new SHA512CryptoServiceProvider();

                byte[] hashed = Hash.ComputeHash(plainTextBytes);
                for (int i = 0; i < hashed.Length; ++i)
                {
                    strData += string.Format("{0:x2}", hashed[i]);
                }

                //MD 5 변환
                return(strData);
            }
            catch (Exception) { }

            return(null);
        }
 /* Good1() changes true to false */
 private void Good1()
 {
     if (false)
     {
         /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */
         IO.WriteLine("Benign, fixed string");
     }
     else
     {
         byte[] hashedBytes;
         using (SHA512CryptoServiceProvider sha512 = new SHA512CryptoServiceProvider())
         {
             using (RNGCryptoServiceProvider random = new RNGCryptoServiceProvider())
             {
                 var salt = new byte[32];
                 /* FIX: Use a sufficiently random salt */
                 random.GetNonZeroBytes(salt);
                 byte[] textWithSaltBytes = Encoding.UTF8.GetBytes(string.Concat("hash me", salt));
                 hashedBytes = sha512.ComputeHash(textWithSaltBytes);
             }
         }
         IO.WriteLine(IO.ToHex(hashedBytes));
     }
 }
        /* goodG2B() - use goodsource and badsink */
        private static void GoodG2B(HttpRequest req, HttpResponse resp)
        {
            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);
                        }
                    }
                }
            }
            Container dataContainer = new Container();

            dataContainer.containerOne = data;
            CWE315_Cleartext_Storage_in_Cookie__Web_67b.GoodG2BSink(dataContainer, req, resp);
        }