Hi All,
My client required to encrypt password using symmetric key cryptography(Private Key).
When user account will be created then password of the user will be encrypted and save in the database table with the help of the private key.
The private key should be change with some interval of the time.
I have develop below code, I am using key like "
B374A26A71490437AA024E4FADD5B497FDFF1A8EA6FF12F6FB65AF2720B59CCF
".
Actually encrypt data with key is Ok but when I decrypt data we need the IV key also and its different for each encryption.
I don't want to save any key in the database. How to manage it please suggest.
I used the below code:
private RijndaelManaged CreateCipher()
{
RijndaelManaged cipher = new RijndaelManaged();
cipher.KeySize = 256;
cipher.BlockSize = 128;
cipher.Padding = PaddingMode.ISO10126;
cipher.Mode = CipherMode.CBC;
string text = System.IO.File.ReadAllText("D:\\ITC\\Symmetric Key\\Key.txt");
byte[] key = HexToByteArray(text);
cipher.Key = key;
return cipher;
}
public byte[] HexToByteArray(string hexString)
{
if (0 != (hexString.Length % 2))
{
throw new ApplicationException("Hex string must be multiple of 2 in length");
}
int byteCount = hexString.Length / 2;
byte[] byteValues = new byte[byteCount];
for (int i = 0; i < byteCount; i++)
{
byteValues[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
}
return byteValues;
}
public string Encrypt(string plainText)
{
RijndaelManaged rijndael = CreateCipher();
ICryptoTransform cryptoTransform = rijndael.CreateEncryptor();
byte[] plain = Encoding.UTF8.GetBytes(plainText);
byte[] cipherText = cryptoTransform.TransformFinalBlock(plain, 0, plain.Length);
Program Prm = new Program();
CipherText = Convert.ToBase64String(cipherText);
IV = Convert.ToBase64String(rijndael.IV);
Console.WriteLine(Convert.ToBase64String(rijndael.IV));
return CipherText;
}
public string Decrypt(string iv, string cipherText)
{
RijndaelManaged cipher = CreateCipher();
cipher.IV = Convert.FromBase64String(iv);
ICryptoTransform cryptTransform = cipher.CreateDecryptor();
byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
byte[] plainText = cryptTransform.TransformFinalBlock(cipherTextBytes, 0, cipherTextBytes.Length);
return (Encoding.UTF8.GetString(plainText));
}