Create unique encryption - c#

It is use to encrypt a string to create a unique fingerprint like 8FAC-5806-FF54-4174-F89E-43DE-97A6-5648.
How can I convert it back from the 8FAC-5806-FF54-4174-F89E-43DE-97A6-5648 to the string?
MD5 is single encryption, so have to use tripleDES to retrieve it back. but how to create a string like this 8FAC-5806-FF54-4174-F89E-43DE-97A6-5648 using the method below:
public static string Encrypt(string strToEncrypt, string strKey)
{
try
{
TripleDESCryptoServiceProvider objDESCrypto = new TripleDESCryptoServiceProvider();
MD5CryptoServiceProvider objHashMD5 = new MD5CryptoServiceProvider();
byte[] byteHash, byteBuff;
string strTempKey = strKey;
byteHash = objHashMD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(strTempKey));
objHashMD5 = null;
objDESCrypto.Key = byteHash;
objDESCrypto.Mode = CipherMode.ECB; //CBC, CFB
byteBuff = ASCIIEncoding.ASCII.GetBytes(strToEncrypt);
return Convert.ToBase64String(objDESCrypto.CreateEncryptor().TransformFinalBlock(byteBuff, 0, byteBuff.Length));
}
catch (Exception ex)
{
return "Wrong Input. " + ex.Message;
}
}

The code uses MD5 to generate the fingerprint. MD5 is a one-way hashing algorithm. This means that it's not possible to reverse the algorithm to get the original value back. Hashing is not encryption. If you want to encrypt your string and be able to decrypt it, you need to use an encryption algorithm such as AES.

Related

Special characters in MD5 encryption

I'm having a problem with MD5 encryption in C# and SQL Server, it only happens on rows with special characters.
Here is the Code in c#:
public virtual string RowHash<T>(T item)
{
PropertyInfo[] properties = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
var finalvalue = "";
foreach (PropertyInfo p in properties)
{
if (p.Name != "Hash")
{
if (!p.CanWrite || !p.CanRead) { continue; }
MethodInfo mget = p.GetGetMethod(false);
MethodInfo mset = p.GetSetMethod(false);
// Get and set methods have to be public
if (mget == null) { continue; }
if (mset == null) { continue; }
var value = p.GetValue(item, null) == null ? "" : p.GetValue(item, null) is Entity? ((Entity)p.GetValue(item, null)).Id.ToString() : p.GetValue(item, null).ToString();
finalvalue += value;
}
}
return finalvalue;
}
public static string GetMD5(string text)
{
var md5 = MD5CryptoServiceProvider.Create();
var encoding = new ASCIIEncoding();
byte[] stream = null;
var sb = new StringBuilder();
stream = md5.ComputeHash(encoding.GetBytes(text));
for (int i = 0; i < stream.Length; i++) sb.AppendFormat("{0:x2}", stream[i]);
return sb.ToString();
}
public static string PasswordMD5(string password)
{
var pwd = GetMD5(password + GetMD5(password).Substring(0,2));
return pwd;
}
With the method RowHash I get concatenated all the fields from the Row unless the field hash that will store the result, then I sent it to the method PasswordMD5 that creates the encrypted Hash we save in the database.
Then I do the same in SQL Server with this code:
CONVERT(VARCHAR(32), HashBytes('MD5',CONVERT(VARCHAR(MAX),CONVERT(VARCHAR(MAX),ISNULL([Field1],''))+ISNULL([Field2],'')+ISNULL([Field3],'')+CONVERT(VARCHAR(MAX),ISNULL([Field4],''))+ISNULL(CONVERT(VARCHAR(MAX),[Field5]),'')+ISNULL(CONVERT(VARCHAR(MAX),Field6]),'')+CONVERT(VARCHAR(MAX),Field7]))+SUBSTRING(CONVERT(VARCHAR(32),HashBytes('MD5',CONVERT(VARCHAR(MAX),CONVERT(VARCHAR(MAX),ISNULL([Field1],''))+ISNULL([Field2],'')+ISNULL([Field3],'')+CONVERT(VARCHAR(MAX),ISNULL([Field4],''))+ISNULL(CONVERT(VARCHAR(MAX),Field5]),'')+ISNULL(CONVERT(VARCHAR(MAX),[Field6]),'')+CONVERT(VARCHAR(MAX),Field7]))) 2), 1, )), 2)
Then I compare this with the Hash that I created in C# to check the integrity of the data I have in the database. This works perfectly fine for all the rows without special characters, but fail for all the rows that contain any special characters like é or ö.
This is an issue I faced some time ago, but the task was paused by other priorities, I don't remember exactly what solutions I already tried, I remember that I tried some solutions changing the encoding of the strings in C# but none worked.
What I am doing wrong?
Thanks in advance.
Finally I cannot find a good solution using MD5, I moved to SHA256 and it worked using this answer:
https://stackoverflow.com/a/19214122/4890862
I Use this Encrypt and Decrypt method for my code and i already tested with special character and its work fine for me. i will send you my code plz test this once i hope it will work you.
TableFilter Is common class file which file contains encrypt and decrypt method nothing else you can write these two method on .cs page.
public static string Encrypt(string toEncrypt, bool useHashing = true)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
System.Configuration.AppSettingsReader settingsReader =
new AppSettingsReader();
// Get the key from config file
string key = (string)settingsReader.GetValue("EncryptionKey",
typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
//If hashing use get hashcode regards to your key
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray =
cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string cipherString, bool useHashing = true)
{
byte[] keyArray;
//get the byte code of the string
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
System.Configuration.AppSettingsReader settingsReader =
new AppSettingsReader();
//Get your key from config file to open the lock!
string key = (string)settingsReader.GetValue("EncryptionKey",
typeof(String));
if (useHashing)
{
//if hashing was used get the hash code with regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//release any resource held by the MD5CryptoServiceProvider
hashmd5.Clear();
}
else
{
//if hashing was not implemented get the byte code of the key
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(
toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//return the Clear decrypted TEXT
return UTF8Encoding.UTF8.GetString(resultArray);
}
: For textbox string (instead of txtpassword.text put testingé123ö for Understanding))
login_Model.Password = TableFilter.Encrypt("testingé123ö");
: Web.config
<add key="EncryptionKey" value="encyptionkeyvalue"/>

How to triple des C# method according to swift method

How to change C# encryption method to the same as swift? I tried below code, but it's converting the string different. I want according to same as swift due to decryption method. I am using 3des. My C# method encrypt/decrypt is working fine.
I want same as C# in Swift.
C#
public static string Encrypt(string PlainText)
{
try
{
if (PlainText.Length > 0)
{
string key = "FIFEDCBA98765432104AABFD";
byte[] PlainTextArray = UTF8Encoding.UTF8.GetBytes(PlainText);
byte[] keyArray = MD5.CreateMd5ByteArray(key);
TripleDESCryptoServiceProvider TripleDes = new TripleDESCryptoServiceProvider();
TripleDes.Key = keyArray;
TripleDes.Mode = CipherMode.ECB;
TripleDes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = TripleDes.CreateEncryptor();
byte[] CipherString = cTransform.TransformFinalBlock(PlainTextArray, 0, PlainTextArray.Length);
TripleDes.Clear();
return Convert.ToBase64String(CipherString, 0, CipherString.Length);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw;
}
}
SWIFT
func tripleDesEncrypt(PlainString: String) -> String{
let keyData = "FIFEDCBA98765432104AABFD"
let PlainStringvar = PlainString
guard let data = PlainStringvar.data(using: .utf8) else {
return ""
}
let cryptData = NSMutableData(length: Int(data.count) + kCCBlockSize3DES)!
let keyLength = size_t(kCCKeySize3DES)
let operation: CCOperation = UInt32(kCCEncrypt)
let algoritm: CCAlgorithm = UInt32(kCCAlgorithm3DES)
let options: CCOptions = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)
var numBytesEncrypted :size_t = 0
let cryptStatus = CCCrypt(operation,
algoritm,
options,
keyData.bytes, keyLength,
nil,
data.bytes, data.count,
cryptData.mutableBytes, cryptData.length,
&numBytesEncrypted)
if UInt32(cryptStatus) == UInt32(kCCSuccess) {
cryptData.length = Int(numBytesEncrypted)
var base64cryptString = cryptData.base64EncodedString(options: .lineLength64Characters)
return base64cryptString//// encodeString(str: base64cryptString)
} else {
print("Error: \(cryptStatus)")
}
return ""
}
Your problem in C# appears to be this line:
byte[] keyArray = MD5.CreateMd5ByteArray(key);
Assuming that function (which is not part of the .NET BCL, so I assume it's something custom that you wrote) creates an MD5 hash of your 3DES key, that's the only difference between your C# and Swift versions.
In Swift, you encrypt the value using a key which is the UTF-8 encoded value of "FIFE...".
In C#, you encrypt the value using a key which is the MD5 hash of the UTF-8 encoded value if "FIFE...".
If you replace that line with the following one:
var keyArray = Encoding.UTF8.GetBytes(key);
then both functions return the same ciphertext for the same plaintext values.

How to store a system.net.mail password in the database

I need to store email passwords which will be used with system.net.mail. These need to be retrieved and sent as plain text but I don't want to store them as plain text. This isn't really about security as its for an intranet and I just don't want the results being displayed in plain text in the CMS.
I've read plenty of articles saying that storing password should be done using SHA1. From what I've read hashing is no good because the plain text cant be retrieved.
I am currently trying this methods:
public static string EncodePasswordToBase64(string password)
{
try
{
byte[] encData_byte = new byte[password.Length];
encData_byte = System.Text.Encoding.UTF8.GetBytes(password);
string encodedData = Convert.ToBase64String(encData_byte);
return encodedData;
}
catch (Exception ex)
{
throw new Exception("Error in base64Encode" + ex.Message);
}
}
and
public static string DecodeFrom64(string encodedData)
{
System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
System.Text.Decoder utf8Decode = encoder.GetDecoder();
byte[] todecode_byte = Convert.FromBase64String(encodedData);
int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
char[] decoded_char = new char[charCount];
utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
string result = new String(decoded_char);
return result;
}
but I cant seem to find the correct data type in my database to store the value. Its currently set to nvarchar(MAX).
The cell contents display like this (with spaces between each value):
Q X B j L W V w M X B =
Strangely when I click and enter the cell to copy the data all I get is:
Q
What data type should I use for this column?
You can use something like this..
//For encrypting string.
public static string Encrypt(string toEncrypt, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
string key = "UglyRandomKeyLike-lkj54923c478";
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
// To decrypt string
public static string Decrypt(string cipherString, bool useHashing)
{
byte[] keyArray;
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
string key = "UglyRandomKeyLike-lkj54923c478";
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
The above mentioned method will encrypt your password and you can store it in varchar field in your database. The second method takes encrypted password and return it in normal string
I hope this is what you are looking for.. I am not able to comment in your question.
Well, you're correct that hashing is not the correct way to go. What you actually want to use is Symmetric Encryption which will allow you to encrypt the data in the DB but then to decrypt it back in your main program.
AES is the recommended standard. Here is an example of how it used in C#.
I'd read a little bit more about how to correctly choose an IV to avoid common pitfalls.

C# triple DES wrapper problems: TransformFinalBlock throws 'Bad data'

I have a triple DES wrapper in C# that consists of two static functions, Encrypt and Decrypt. Occasionally, Decrypt fails with TransformFinalBlock(..., ...) throwing the error 'Bad data'.
Why is this happening?
What's the solution?
Thanks in advance.
public static string Encrypt(string toencrypt, string key, bool usehashing = true)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toencrypt);
byte[] resultArray;
//If hashing use get hashcode regards to your key
if (usehashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
try
{
//transform the specified region of bytes array to resultArray
resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
}
catch (System.Exception ex)
{
//Release resources held by TripleDes Encryptor
tdes.Clear();
return "";
}
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string todecrypt, string key, bool usehashing = true)
{
byte[] keyArray;
byte[] toEncryptArray;
byte[] resultArray;
//get the byte code of the string
try
{
toEncryptArray = Convert.FromBase64String(todecrypt.Replace(" ", "+"));//The replace happens only when spaces exist in the string (hence not a Base64 string in the first place).
}
catch (System.Exception ex)
{
return "";
}
if (usehashing)
{
//if hashing was used get the hash code with regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//release any resource held by the MD5CryptoServiceProvider
hashmd5.Clear();
}
else
{
//if hashing was not implemented get the byte code of the key
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
try
{
resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
}
catch (System.Exception ex)
{
//Release resources held by TripleDes Encryptor
tdes.Clear();
return "";
}
//Release resources held by TripleDes Encryptor
tdes.Clear();
//return the Clear decrypted TEXT
return UTF8Encoding.UTF8.GetString(resultArray);
}
An example string that once encrypted causes Decrypt to fail would be:
AgAAAA*AQAAAA*aAAAAA*jfgGTw*nY+sHZ2PrBmdj6wVnY+sEZ2PrA2dj6wFk4GhCJOHoQqdj6x9nY+seQ*trIBAA*AAMAAA**+L7PHiJ76M8OTV4BjXCkuDgDG2u7AcW87p1KU7KTSCKI3fYTnYAcGk1gyS62AvZO4g1FrsVbzoAnsX9Y0Ju+V9YjaYr9+Xr+pen4SEas0NjRvntv0gqU0QZOj9bjKXx1Izc9Dw1HCUqjUGBcwakQo6kBlvb2v2/pV9dM4B3RM6m7rmaW79CSc7CC3DQjnqA5HMHC5k65pOK0KT76MzTawYQotNOk0BabTO3HpVcI8BNNjSsIP7TvtxXBmbc6TfXahw1zLTvC4iTSPnsgz0jhxvHhHD+N0cblfQhAK/nt2IZQuWGL3jW0oPpPJnjhGMWQPDLXbNwp23WUv8GXIPKevXbushYKjutmsdqJT7C1mcB45XhbYCVUVbLIja1AV831YeHqqke2msSaisg37UM+urL9EFIueUHZgZryhQUSjAhZDiHXqosoQou92RqbTK5YTqYY+zyBBzRt2r7KS3v5u9smtWMNk8Xcn42a6pFFxd6g4u0/s/SVm7NFb2UbREvp75lBVxEQv5IIznPSHfDnLtuX8pLfrZ/AVQ+gM9AGvzBjHGNYDQJ6VhgkHOZMeuLISJXjfGX0ZPFYKd+CPObpbFlukOSlIB5epRDnuggTLnthpN06Kle+iDqz1Q96ty4mfzwuhRwxvQ7EMzTykHXxC8p9bLKMr86K/vart2D9w1g9RtyS+pekgW8lkutWWGdu1eZml/5abNmlW5VgSJiuA9Yyrd2UNjUl6/a0oMKHPk6b2gZkpmENpO7auC9HA2gO
However most strings do not cause it to fail. This must be something to do with special characters I'm guessing.
First, please provide the initial unencrypted key and string which generates that encrypted block that fails. Then we may have a better chance of figuring out why there's an issue. However, that being requested, I see a few potential pitfalls in your code, mostly related to not disposing of types which implement IDisposable. Here's a small refactoring of the code which takes that into account (amongst a few other small adjustments):
public static string Encrypt(string toencrypt, string key, bool usehashing = true)
{
byte[] keyArray;
// If hashing use get hash code regards to your key
if (usehashing)
{
using (var hashmd5 = new MD5CryptoServiceProvider())
{
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key));
}
}
else
{
keyArray = Encoding.UTF8.GetBytes(key);
}
// set the secret key for the tripleDES algorithm
// mode of operation. there are other 4 modes.
// We choose ECB(Electronic code Book)
// padding mode(if any extra byte added)
using (var tdes = new TripleDESCryptoServiceProvider
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
})
using (var transform = tdes.CreateEncryptor())
{
try
{
var toEncryptArray = Encoding.UTF8.GetBytes(toencrypt);
// transform the specified region of bytes array to resultArray
var resultArray = transform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
// Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
catch (Exception)
{
return string.Empty;
}
}
}
public static string Decrypt(string todecrypt, string key, bool usehashing = true)
{
byte[] toEncryptArray;
// get the byte code of the string
try
{
toEncryptArray = Convert.FromBase64String(todecrypt.Replace(" ", "+")); // The replace happens only when spaces exist in the string (hence not a Base64 string in the first place).
}
catch (Exception)
{
return string.Empty;
}
byte[] keyArray;
if (usehashing)
{
// if hashing was used get the hash code with regards to your key
using (var hashmd5 = new MD5CryptoServiceProvider())
{
keyArray = hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key));
}
}
else
{
// if hashing was not implemented get the byte code of the key
keyArray = Encoding.UTF8.GetBytes(key);
}
// set the secret key for the tripleDES algorithm
// mode of operation. there are other 4 modes.
// We choose ECB(Electronic code Book)
// padding mode(if any extra byte added)
using (var tdes = new TripleDESCryptoServiceProvider
{
Key = keyArray,
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
})
using (var transform = tdes.CreateDecryptor())
{
try
{
var resultArray = transform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
// return the Clear decrypted TEXT
return Encoding.UTF8.GetString(resultArray);
}
catch (Exception)
{
return string.Empty;
}
}
}

Cryptography - remote SQL Server + desktop app

I'm developing a desktop app. that should work over Internet and communicate with remote DB. App's data have to be encrypted wile transfer.
The simplest way is to create the static key and use it while read-write the data from DB. But if I do so I would not be able to change that key. I suppose there are solutions that allow to solve this problem.
Can you tell, please, how do developers operate when they need dynamic encryption in their app's?
Thank you
Copy this code and test it anyway you want.. WPF Console App ect..
using System;
using System.Security.Cryptography;
using System.Text;
public static class DataEncryption
{
public static string Encrypt(string input, string key)
{
byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public static string Decrypt(string input, string key)
{
byte[] inputArray = Convert.FromBase64String(input);
TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
tripleDES.Mode = CipherMode.ECB;
tripleDES.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tripleDES.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
tripleDES.Clear();
return UTF8Encoding.UTF8.GetString(resultArray);
}
}
this should give you an idea of what I am talking about.
that should work over Internet and communicate with remote DB
This is one of the things that happens with SSL/TLS. The server and client set up a secure channel that eavesdroppers cannot intercept. I'd recommend reading the book Applied Cryptography to learn how this, and other similar protocols work. PGP is a reasonably familiar application that you may wish to study.
how do developers operate when they need dynamic encryption in their apps?
Generally, previous employers have used self-generated public key certificates. Depending on the business needs, either each version of the software gets a different cert, or each user gets a different cert (this ends up as part of the license key that each user gets). If one is leaked, that individual certificate can be revoked.
If you need to encrypt data for transfer only, then you should use an encrypted (i.e. SSL/TLS) connection. MS SQL Server supports this:
Encrypting Connections to SQL Server
How To Do Simple Encryption
Try this Code as well it also works really well .. basically what ever string you want encrypted just pass that string to the methods you may have to alter the code to work for your project feel fee to consume the code as you please.
using System;
using System.Text;
using System.Security.Cryptography;
namespace EncryptStringSample
{
class MainClass
{
public static string EncryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// Step 2. Create a new TripleDESCryptoServiceProvider object
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
// Step 3. Setup the encoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
// Step 4. Convert the input string to a byte[]
byte[] DataToEncrypt = UTF8.GetBytes(Message);
// Step 5. Attempt to encrypt the string
try
{
ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
Results = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
// Step 6. Return the encrypted string as a base64 encoded string
return Convert.ToBase64String(Results);
}
public static string DecryptString(string Message, string Passphrase)
{
byte[] Results;
System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
// Step 1. We hash the passphrase using MD5
// We use the MD5 hash generator as the result is a 128 bit byte array
// which is a valid length for the TripleDES encoder we use below
MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(Passphrase));
// Step 2. Create a new TripleDESCryptoServiceProvider object
TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
// Step 3. Setup the decoder
TDESAlgorithm.Key = TDESKey;
TDESAlgorithm.Mode = CipherMode.ECB;
TDESAlgorithm.Padding = PaddingMode.PKCS7;
// Step 4. Convert the input string to a byte[]
byte[] DataToDecrypt = Convert.FromBase64String(Message);
// Step 5. Attempt to decrypt the string
try
{
ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
}
finally
{
// Clear the TripleDes and Hashprovider services of any sensitive information
TDESAlgorithm.Clear();
HashProvider.Clear();
}
// Step 6. Return the decrypted string in UTF8 format
return UTF8.GetString( Results );
}
public static void Main(string[] args)
{
// The message to encrypt.
string Msg = "This world is round, not flat, don't believe them!";
string Password = "secret";
string EncryptedString = EncryptString(Msg, Password);
string DecryptedString = DecryptString(EncryptedString, Password);
Console.WriteLine("Message: {0}",Msg);
Console.WriteLine("Password: {0}",Password);
Console.WriteLine("Encrypted string: {0}",EncryptedString);
Console.WriteLine("Decrypted string: {0}",DecryptedString);
}
}
}

Categories

Resources