我创建了一个 C# 控制台应用程序(我不太擅长 C#),
它基本上使用 xor 密码加密输入文件。
代码如下:
using System;
using System.IO;
using System.Text;
using System.Diagnostics;
namespace XorCryptor
{
class Program
{
public static void Main(string[] args)
{
if(args.Length != 3)
{
Console.WriteLine("Usage: xorcryptor password file_in.txt file_out.txt");
Console.Write("Press any key to continue...");
Console.ReadKey(true);
return;
}
Stopwatch sw = Stopwatch.StartNew();
BinaryReader infileb;
try{
infileb = new BinaryReader(File.Open(args[1], FileMode.Open));
}catch(IOException){
Console.WriteLine("Error reading from input file (is it in use by another program?)");
return;
}
byte[] encb = Crypt(infileb.ReadBytes((int)infileb.BaseStream.Length),args[0]);
infileb.Close();
BinaryWriter outfileb;
try{
outfileb = new BinaryWriter(File.Open(args[2], FileMode.Create));
}catch(IOException){
Console.WriteLine("Error writing to output file (is it in use by another program?)");
return;
}
outfileb.Write(encb);
outfileb.Close();
sw.Stop();
Console.WriteLine("Size: "+encb.Length.ToString());
Console.WriteLine("Elapsed milliseconds: "+sw.ElapsedMilliseconds.ToString());
}
internal static byte[] Crypt(byte[] text, string password)
{
int i2 = 0;
byte[] result = new byte[text.Length];
foreach(byte b in text)
{
result[i2] = Convert.ToByte(b ^ password[i2 % password.Length]);
i2++;
}
return result;
}
}
}
然后是等效的 Python 版本,(我使用 SharpDevelop 4.0 构建可执行文件):
import System
from System.IO import File, FileMode, BinaryReader, BinaryWriter
from System.Diagnostics import Stopwatch
import sys
def crypt(text, password):
result = System.Array.CreateInstance(System.Byte, text.Length)
for i, b in enumerate(text):
result[i] = System.Convert.ToByte(b ^ ord(password[i % len(password)]))
return result
argv = System.Environment.GetCommandLineArgs()
if len(argv) != 4:
print "Usage: pyxorcryptor password file_in file_out"
print "Press any key to exit...",
System.Console.ReadKey(True)
sys.exit(1)
sw = Stopwatch.StartNew()
try:
infileb = BinaryReader(File.Open(argv[2], FileMode.Open))
outfileb = BinaryWriter(File.Open(argv[3], FileMode.Create))
except IOException, e:
print e.ToString()
sys.exit(1)
encb = crypt(infileb.ReadBytes(int(infileb.BaseStream.Length)), argv[1])
infileb.Close()
outfileb.Write(encb)
outfileb.Close()
sw.Stop()
print "Size: {0}\nTime (ms): {1}".format(len(encb), sw.ElapsedMilliseconds)
使用相同的 3,827 kb 纯文本文件测试它们的速度,
我明白了:
C#:
.NET 4.0 的 IronPython 2.6
所以我认为我们可以得出结论,IronPython 比 C# 慢得多,
在这种特殊情况下。
我可能在这两个文件的代码中的某个地方犯了错误,请随时指出它们。我还在学习。