我们有一个使用Persits Software的aspEncrypt的遗留Web应用程序。我有数千个使用该设置加密的文件,因此我需要保持兼容。
我正在尝试在C#中编写一个新的实用程序应用程序以匹配相同的加密。这里的目标是不在新应用程序中使用aspEncrypt,并使用.NET框架内置的东西来匹配加密。如果成功,那么我可以在旧文件和新文件上使用相同的传统解密例程。
使用aspEncrypt处理加密步骤的示例代码:
public static int EncryptFileWithRawKey2()
{
string InputFile = @"D:\TEMP\004\testfile.txt"; // contains single line of ANSI text with no end of line characters "hello this is a file"
string OutPutFile = @"D:\TEMP\004\testfile.txt.3.xxx";
string RawKey = "4CDD1518CD6662C9D1583A8732173EDC";
int iRet = 0;
ASPENCRYPTLib.ICryptoKey eKey = null;
try
{
ASPENCRYPTLib.CryptoManager CM = new ASPENCRYPTLib.CryptoManager();
ASPENCRYPTLib.ICryptoContext Context = CM.OpenContext("", 0, 0);
ASPENCRYPTLib.ICryptoBlob Blob = CM.CreateBlob();
Blob.Hex = RawKey;
eKey = Context.ImportRawKey(Blob, ASPENCRYPTLib.CryptoAlgorithms.calgRC2);
ASPENCRYPTLib.ICryptoBlob IVblob = CM.CreateBlob();
IVblob.Hex = "0000000000000000";
eKey.SetIV(IVblob);
eKey.Mode = ASPENCRYPTLib.CryptoCipherModes.ccmCBC;
eKey.Padding = ASPENCRYPTLib.CryptoCipherPadding.ccpPKCS5;
eKey.EffectiveLength = 40;
eKey.EncryptFile(InputFile.Trim(), OutPutFile.Trim());
if (File.Exists(OutPutFile) == true)
iRet = 1;
}
catch (Exception e)
{
Console.WriteLine("EncryptFileWithRawKey2 FAILED");
Console.WriteLine(e.ToString());
iRet = - 1;
}
return iRet;
}
这是我写的代码,到目前为止,这是一个不成功的尝试来匹配它:
public static void EncryptTextToFile2()
{
String Data = "hello this is a file";
String FileName = @"D:\TEMP\004\testfile.txt.4.xxx";
String sTempKey = "4CDD1518CD6662C9D1583A8732173EDC";
byte[] Key;
byte[] IV;
try
{
Key = StringToByteArray(sTempKey);
IV = StringToByteArray("0000000000000000");
FileStream fStream = File.Open(FileName, FileMode.OpenOrCreate);
RC2 RC2alg = RC2.Create();
RC2alg.Padding = PaddingMode.PKCS7;
RC2alg.Mode = CipherMode.CBC;
RC2alg.KeySize = 40;
RC2alg.EffectiveKeySize = 40;
CryptoStream cStream = new CryptoStream(fStream, RC2alg.CreateEncryptor(Key, IV), CryptoStreamMode.Write);
cStream.FlushFinalBlock();
StreamWriter sWriter = new StreamWriter(cStream);
sWriter.WriteLine(Data);
sWriter.Close();
cStream.Close();
fStream.Close();
}
catch (CryptographicException e)
{
Console.WriteLine("A Cryptographic error occurred: {0}", e.Message);
}
catch (UnauthorizedAccessException e)
{
Console.WriteLine("A file error occurred: {0}", e.Message);
}
}
public static byte[] StringToByteArray(string hex)
{
return Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
两个例程的输出不匹配。我无法更改使用AspEncrypt库的逻辑,因此我需要以某种方式更改第二部分代码以匹配第一部分的输出。