Hi. I was taught in another thread about extensions, and I find that awesome. I was just going through my utility class making some stuff extensions so I can simplify my code, and it reminded me of a question I had. I needed the ability to encrypt strings for safe data storage. I'm a beginner, so no way was I going to tackle that myself. Ergo, I found and lifted some code on the net for encryption:
This works great. I needed the ability though to check if a string has already been encrypted by the method. So if I edit one of my config files and put a password in manually, when the program loads it will check and if the pwd is plain text, encrypt and rewrite config. So I did this:
It works cuz if it's not encrypted, DecryptString throws an exception and returns the input value. Problem is, when I am debugging something and set the error handling mode to ignore try/catch so I can debug other code, it's annoying cuz every time I read something plaintext the IDE breaks at the exception in DecryptString too. Is there a way to check if a string was encrypted without relying on throwing exceptions? Or is there a way to tell Visual Studio 2017 to not break execution in a certain method regardless of my error handling settings?
Thanks!
C#:
public static string EncryptString(string Message, string Passphrase = "(my default value here)") {
byte[] Results;
UTF8Encoding UTF8 = new UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToEncrypt = UTF8.GetBytes(Message);
try {
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return Convert.ToBase64String(Results);
}
public static string DecryptString(string Message, string Passphrase = "(my default value here)") {
try {
byte[] Results;
UTF8Encoding UTF8 = new UTF8Encoding();
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
byte[] DataToDecrypt = Convert.FromBase64String(Message);
try {
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
} finally {
TDESAlgorithm.Clear();
HashProvider.Clear();
}
return UTF8.GetString(Results);
} catch {
return Message;
}
}
C#:
public static bool IsEncrypted(this string value) {
return DecryptString(value) != value;
}
Thanks!