2

I want to make change in below encryption code so it gives me same encrypted string for a given text again and again.

e.g input string : "test"

output encrypted string : "@#$#@$@#$SDFDSF"

If I input "test" again and again output should be same.

public static string Encrypt(string text, bool encryptSame = false)
    {
        var key = Encoding.UTF8.GetBytes("E546C8DF278CD5931069B522E695D4F3");

        using (var aesAlg = Aes.Create())
        {
            if (encryptSame)
            {
                aesAlg.Padding = PaddingMode.Zeros;
                aesAlg.Mode = CipherMode.ECB;
            }

            using (var encryptor = aesAlg.CreateEncryptor(key, aesAlg.IV))
            {
                
                using (var msEncrypt = new MemoryStream())
                {
                    using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    using (var swEncrypt = new StreamWriter(csEncrypt))
                    {
                        swEncrypt.Write(text);
                    }

                    var iv = aesAlg.IV;

                    var decryptedContent = msEncrypt.ToArray();

                    var result = new byte[iv.Length + decryptedContent.Length];

                    Buffer.BlockCopy(iv, 0, result, 0, iv.Length);
                    Buffer.BlockCopy(decryptedContent, 0, result, iv.Length, decryptedContent.Length);

                    return Convert.ToBase64String(result);
                }
            }
        }
    }
Var
  • 217
  • 5
  • 16
  • The concatenation of randomly generated IV and ciphertext is only useful for the CBC mode (`encryptSame = false`), which uses an IV, but _not_ for the ECB mode (`encryptSame = true`), which does _not_ use an IV at all. The return value of the method in ECB mode differs _only_ because of the IV portion (and its randomness), the generated ciphertext is _always_ the same (assuming the same plaintext and key); the IV specified in `CreateEncryptor` is ignored during encryption in ECB mode. – Topaco Jul 11 '20 at 15:16
  • @topaco I want to encrypt username (email or mobile number) & password while sign up. And while logging in I need to find the math record with credential. I was thinking if I get the same string on encryption I will encrpt the credential while logging in and get the result. Otherwise I have to take all records and decrypt them and find the matching record. Any suggestion for the senario – Var Jul 11 '20 at 19:00
  • This seems to be about password-based authentication. Then, encryption is rather the wrong way. Instead, hashing is used for passwords. However, there are some things to consider, e.g. the use of a salt, a suitable password-hashing function, e.g. Argon2, etc. You can find enough about this on the Internet, e.g. [here](https://gcn.com/articles/2013/12/02/hashing-vs-encryption.aspx) and [here](https://security.stackexchange.com/a/197550). – Topaco Jul 11 '20 at 21:13

0 Answers0