1

Following encryption and decryption algorithms are called via powershell and in a sharepoint application page:

    public static string Encrypt(string dataToEncrypt, string password, string salt)
    {
        AesManaged aes = null;
        MemoryStream memoryStream = null;
        CryptoStream cryptoStream = null;

        try
        {
            Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), 10000);

            aes = new AesManaged();
            aes.Key = rfc2898.GetBytes(32);
            aes.IV = rfc2898.GetBytes(16);

            memoryStream = new MemoryStream();
            cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);

            byte[] data = Encoding.UTF8.GetBytes(dataToEncrypt);
            cryptoStream.Write(data, 0, data.Length);
            cryptoStream.FlushFinalBlock();

            return Convert.ToBase64String(memoryStream.ToArray());
        }
        finally
        {
            if (cryptoStream != null)
                cryptoStream.Close();

            if (memoryStream != null)
                memoryStream.Close();

            if (aes != null)
                aes.Clear();
        }
    }

Why the encrypted string changes? Is it about application domain?

onatm
  • 816
  • 1
  • 11
  • 29

2 Answers2

1

When I run the questions code, with the same data, password, and salt, it produces the same result each time. You should make sure the dataToEncrypt and the Salt are the same each time if even one byte changes the rest of it changes.

However that said, for semantic security, that is not what you want. You want a random salt to make it harder to brute force the password, and a random nonsecret IV set so that two identical plaintexts don't have the same ciphertext.

Here is an example of best practices for encrypting and decrypting string, using the encryption algorithms security features as they are designed. The SimpleEncryptWithPassword is analogous to what you are doing, although in the example the iterations for the derived key are variable and for performance reasons you'd probably want to hard code it.

Community
  • 1
  • 1
jbtule
  • 31,383
  • 12
  • 95
  • 128
1

The encrypted string differs because of the $ character. $ should be escaped while the function is called via powershell.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
onatm
  • 816
  • 1
  • 11
  • 29