Here are my encryption and decryption methods. I have two databases and I copied the encrypted password from one database to the other. The code was in vb but I converted it into C#.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace AccountSystem.Class{
class ClEncrDecr
{
private TripleDESCryptoServiceProvider tripleDESCryptoServiceProvider = new TripleDESCryptoServiceProvider();
private byte[] TruncateHash(string key, int length)
{
SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
//Hash the Key
byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
byte[] hash = sha1.ComputeHash(keyBytes);
// truncate or pad the hash
Array.Resize(ref hash, length);
return hash;
}
public ClEncrDecr()
{
string key = "ABCD";
tripleDESCryptoServiceProvider.Key = TruncateHash(key, tripleDESCryptoServiceProvider.KeySize / 8 );
tripleDESCryptoServiceProvider.IV = TruncateHash("", tripleDESCryptoServiceProvider.BlockSize / 8 );
}
public string EncryptData(string plainText)
{
byte[] plaintextBytes = System.Text.Encoding.Unicode.GetBytes(plainText);
MemoryStream ms = new MemoryStream();
CryptoStream encStream = new CryptoStream(ms, tripleDESCryptoServiceProvider.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
encStream.Write(plaintextBytes, 0, plaintextBytes.Length);
encStream.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
public string DecryptData(string encryptedtext)
{
byte[] encryptedBytes = Convert.FromBase64String(encryptedtext);
MemoryStream ms = new MemoryStream();
CryptoStream decStream = new CryptoStream(ms, tripleDESCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write);
decStream.Write(encryptedBytes, 0, encryptedBytes.Length);
decStream.FlushFinalBlock();
return System.Text.Encoding.Unicode.GetString(ms.ToArray());
}
}
}
Login Code :
MessageBox.Show(crypto.DecryptData(obj.password))
When we call DecryptData(string encryptedtext)
it throws an exception saying Invalid length for a Base-64 char array or string
. What can I do?