Craig

Craig

  • NA
  • 20
  • 0

Encrypting Strings

May 21 2008 2:37 PM

I've written C# ASP.NET code that encrypts a password and stores it in an Access database. The code retrieves the encrypted password but can not decrypt it.   Please see encryption and decryption code below.  I can only guess that the encrypted string  is "corrupted" when storing in Access and thus can not be decrypted.     The password is encrypted as a base64 string.  Can anyone explain why?  Perhaps someone knows of other encryption/decryption code.

 

 

static SymmetricAlgorithm encryptionAlgorithm = InitializeEncryptionAlgorithm();
static SymmetricAlgorithm InitializeEncryptionAlgorithm()
        {
            SymmetricAlgorithm rijaendel = RijndaelManaged.Create();
            rijaendel.GenerateKey();
            rijaendel.GenerateIV();
            return rijaendel;
        }

        /// <summary>
        /// Encrypts the string and returns a base64 encoded encrypted string.
        /// </summary>
        /// <param name="clearText">The clear text.</param>
        /// <returns></returns>
        public static string EncryptString(string clearText)
        {
            byte[] clearTextBytes = Encoding.UTF8.GetBytes(clearText);
            byte[] encrypted = encryptionAlgorithm.CreateEncryptor().TransformFinalBlock(clearTextBytes, 0, clearTextBytes.Length);
            return Convert.ToBase64String(encrypted);
        }

        /// <summary>
        /// Decrypts the base64 encrypted string and returns the cleartext.
        /// </summary>
        /// <param name="encryptedEncodedText">The clear text.</param>
        /// <exception type="System.Security.Cryptography.CryptographicException">Thrown the string to be decrypted
        /// was encrypted using a different encryptor (for example, if we recompile and
        /// receive an old string).</exception>
        /// <returns></returns>
         public static string DecryptString(string encryptedEncodedText)
        {
          
                byte[] encryptedBytes = Convert.FromBase64String(encryptedEncodedText);
                byte[] decryptedBytes = encryptionAlgorithm.CreateDecryptor().TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
                return Encoding.UTF8.GetString(decryptedBytes);
          
        }


Answers (1)