SHA256 是否被认为是不安全的?- SonarQube Quality Gate - 我该如何解决?

Is SHA256 considered insecure?- SonarQube Quality Gate - How can I fix it?

我有下面一段代码

        private static string sensitiveKey = "<REPLACE_WITH_KEY>"  

        public static string Encrypt(string input)
        {
            // Get the bytes of the string
            byte[] passwordBytes = Encoding.UTF8.GetBytes(sensitiveKey);
            // Hash the password with SHA256
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
            byte[] bytesEncrypted = EncryptStringToBytes_Aes(input, passwordBytes);
            string result = Convert.ToBase64String(bytesEncrypted);
            return result;
        }

SonarQube 说

Cryptographic hash functions are used to uniquely identify information without storing their original form. When not done properly, an attacker can steal the original information by guessing it (ex: with a rainbow table), or replace the original data with another one having the same hash.

还有

use only hashing algorithms which are currently known to be strong. Avoid using algorithms like MD5 and SHA1 completely in security contexts.

所以问题是,我如何改进我的代码以使其安全?

有样品出来吗?

您可以尝试向散列密码添加盐,因为未加盐的散列往往更容易受到字典和彩虹 table 攻击。

hash("hello") =
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

hash("hello" + "QxLUF1bgIAdeQX") = 
9e209040c863f84a31e719795b2577523954739fe5ed3b58a75cff2127075ed1

hash("hello" + "bv5PehSMfV11Cd") = 
d1d3ec2e6f20fd420d50e2642992841d8338a314b8ea157c9e18477aaef226ab

上面的代码是加盐通常如何工作的示例。您将固定字符串连接到密码,然后对结果进行哈希处理。 salt 应该是固定长度的,并且 永远不要重复使用 。这就是你的情况:

        private static string salt = "<REPLACE_WITH_FIXED_LENGTH_SALT>";
        private static string sensitiveKey = "<REPLACE_WITH_KEY>";  
        private static string salted_key = salt + sensitiveKey;

        public static string Encrypt(string input)
        {
            // Get the bytes of the string
            byte[] passwordBytes = Encoding.UTF8.GetBytes(salted_key);
            // Hash the password with SHA256
            passwordBytes = SHA256.Create().ComputeHash(passwordBytes);
            byte[] bytesEncrypted = EncryptStringToBytes_Aes(input, passwordBytes);
            string result = Convert.ToBase64String(bytesEncrypted);
            return result;
        }