以下是我的加密和解密方法。我有两个数据库,并将加密后的密码从一个数据库复制到另一个数据库。这段代码原本是vb语言编写的,但我已将其转换为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());
}
}
}
登录代码:
MessageBox.Show(crypto.DecryptData(obj.password))
当我们调用 DecryptData(string encryptedtext)
方法时,会抛出一个异常,指出 Invalid length for a Base-64 char array or string
。我该怎么办?