End Google Ads 201810 - BS.net 01 -->
Hi Everyone.
I'm pretty new to C#, and I'm having a bit of a problem. I have an application which will be saving passwords to an xml document, so I want to encrypt them. I have created some simple code which manages to encrypt the information but complains when I try to decrypt it with “Padding is invalid and cannot be removed”. I have tried different padding modes including PaddingMode.None with no luck.
I’m sure I'm missing something simple... Please can somebody help me???
Thanks
Code
class Program
{
static void Main(string[] args)
{
string Orig = "Paul Unsworth";
string Key = "as^le)ds~{3sjlk3*$ake^ia29?jf%a!";
string IV = "ad|k#f(*&lk$df()";
string Encrypted = Encrypt(Orig, Key, IV);
string Decrypted = Decrypt(Encrypted, Key, IV);
Console.WriteLine("Original Text:\r\n {0}", Orig);
Console.WriteLine("Encrypted Text:\r\n {0}", Encrypted);
Console.WriteLine("Decrypted Text:\r\n {0}", Decrypted);
Console.ReadLine();
}
static string Encrypt(string val, string key, string iv)
{
byte[] bVal = toBytes(val);
byte[] bKey = toBytes(key);
byte[] bIV = toBytes(iv);
MemoryStream ms = new MemoryStream();
Rijndael r = Rijndael.Create();
r.Key = bKey;
r.IV = bIV;
r.Padding = PaddingMode.PKCS7;
CryptoStream cs = new CryptoStream(ms, r.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(bVal, 0, bVal.Length);
cs.Close();
string result = toString(ms.ToArray());
ms.Close();
return result;
}
static string Decrypt(string val, string key, string iv)
{
byte[] bVal = toBytes(val);
byte[] bKey = toBytes(key);
byte[] bIV = toBytes(iv);
MemoryStream ms = new MemoryStream();
Rijndael r = Rijndael.Create();
r.Key = bKey;
r.IV = bIV;
r.Padding = PaddingMode.PKCS7;
CryptoStream cs = new CryptoStream(ms, r.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(bVal, 0, bVal.Length);
cs.Close();
string result = toString(ms.ToArray());
ms.Close();
return result;
}
static byte[] toBytes(string str)
{
ASCIIEncoding a = new ASCIIEncoding();
return a.GetBytes(str);
}
static string toString(byte[] b)
{
ASCIIEncoding a = new ASCIIEncoding();
return a.GetString(b);
}
}
oooo, the Jedi's will feel this one....
مواقع النشر (المفضلة)