为什么我不能在 MonoTouch 上使用一个加密器来加密多个字符串?

发布于 2024-11-29 11:40:04 字数 3258 浏览 2 评论 0原文

我使用以下(精简的)类来加密一些数据,然后再将其从 iPad 应用程序发送到 WCF Web 服务。

public class FlawedAlgorithm
{
    protected static byte[] key = { 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
    protected static byte[] vector = { 13, 37, 13, 37, 13, 37, 13, 37, 13, 37, 13, 37, 13, 37, 13, 37 };
    protected ICryptoTransform encryptor, decryptor;
    protected UTF8Encoding encoder;

    public FlawedAlgorithm()
    {
        using (var rijndael = new RijndaelManaged())
        {
            this.encryptor = rijndael.CreateEncryptor(key, vector);
            this.decryptor = rijndael.CreateDecryptor(key, vector);
        }

        this.encoder = new UTF8Encoding();
    }

    public string Encrypt(string unencrypted)
    {
        var buffer = this.encoder.GetBytes(unencrypted);

        return Convert.ToBase64String(Encrypt(buffer));
    }

    public string Decrypt(string encrypted)
    {
        var buffer = Convert.FromBase64String(encrypted);

        return this.encoder.GetString(Decrypt(buffer));
    }

    private byte[] Encrypt(byte[] buffer)
    {
        var encryptStream = new MemoryStream();

        using (var cryptoStream = new CryptoStream(encryptStream, this.encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(buffer, 0, buffer.Length);
        }

        return encryptStream.ToArray();
    }

    private byte[] Decrypt(byte[] buffer)
    {
        var decryptStream = new MemoryStream();

        using (var cryptoStream = new CryptoStream(decryptStream, this.decryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(buffer, 0, buffer.Length);
        }

        return decryptStream.ToArray();
    }
}

当我在服务器和 iPad 上运行以下代码时,两者都会打印相同的加密字符串。

var algorithm = new FlawedAlgorithm();

Console.WriteLine(algorithm.Encrypt("Some string"));

但是,当我尝试加密第二个值时,服务器和 iPad 上的结果不同。

var algorithm = new FlawedAlgorithm();

// The first encryption still functions correctly.
Console.WriteLine(algorithm.Encrypt("Some string"));

// This second encryption produces a different value on the iPad.
Console.WriteLine(algorithm.Encrypt("This text is a bit longer"));

当我在服务器上解密有偏差的 iPad 结果时,解密的字符串的一部分是乱码。来自服务器的加密结果正确解密。

如果我为每个调用创建一个新的 FlawedAlgorithm 实例,则问题不会自行显现,例如:

// These statements produce the correct results on the iPad.
Console.WriteLine(new FlawedAlgorithm().Encrypt("Some string"));
Console.WriteLine(new FlawedAlgorithm().Encrypt("This text is a bit longer"));

这使我认为问题出在所涉及对象的状态中的某个位置。我已检查 Encrypt(string) 方法中的 buffer 变量,并且 UTF8Encoding 实例生成的值是正确的。这意味着加密器字段(或其底层实现)是罪魁祸首

当我开始改变第一个加密值的大小时,我可以看到第二个加密调用的结果发生变化。这可能意味着流的某些部分没有被正确清除或覆盖。但是 FlawedAlgorithm 类使用的流不是其状态的一部分;它们在每次方法调用时重新创建。而且 cryptor 对象看起来不像是管理自己的流的类型。

还有其他人遇到过类似的问题吗? RijndaelManaged 类是否有缺陷?或者 MonoTouch 中是否存在一些与此加密示例无关的流和内存管理陷阱?

PS:我已经在iPad和iPad模拟器上进行了测试;两者都表现出这种奇怪的行为。

I'm using the following (trimmed-down) class to encrypt some data before sending it from an iPad app to a WCF web service.

public class FlawedAlgorithm
{
    protected static byte[] key = { 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42, 42 };
    protected static byte[] vector = { 13, 37, 13, 37, 13, 37, 13, 37, 13, 37, 13, 37, 13, 37, 13, 37 };
    protected ICryptoTransform encryptor, decryptor;
    protected UTF8Encoding encoder;

    public FlawedAlgorithm()
    {
        using (var rijndael = new RijndaelManaged())
        {
            this.encryptor = rijndael.CreateEncryptor(key, vector);
            this.decryptor = rijndael.CreateDecryptor(key, vector);
        }

        this.encoder = new UTF8Encoding();
    }

    public string Encrypt(string unencrypted)
    {
        var buffer = this.encoder.GetBytes(unencrypted);

        return Convert.ToBase64String(Encrypt(buffer));
    }

    public string Decrypt(string encrypted)
    {
        var buffer = Convert.FromBase64String(encrypted);

        return this.encoder.GetString(Decrypt(buffer));
    }

    private byte[] Encrypt(byte[] buffer)
    {
        var encryptStream = new MemoryStream();

        using (var cryptoStream = new CryptoStream(encryptStream, this.encryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(buffer, 0, buffer.Length);
        }

        return encryptStream.ToArray();
    }

    private byte[] Decrypt(byte[] buffer)
    {
        var decryptStream = new MemoryStream();

        using (var cryptoStream = new CryptoStream(decryptStream, this.decryptor, CryptoStreamMode.Write))
        {
            cryptoStream.Write(buffer, 0, buffer.Length);
        }

        return decryptStream.ToArray();
    }
}

When I run the following code on the server and the iPad, both print the same encrypted string.

var algorithm = new FlawedAlgorithm();

Console.WriteLine(algorithm.Encrypt("Some string"));

However, when I try to encrypt a second value, the results on the server and iPad are different.

var algorithm = new FlawedAlgorithm();

// The first encryption still functions correctly.
Console.WriteLine(algorithm.Encrypt("Some string"));

// This second encryption produces a different value on the iPad.
Console.WriteLine(algorithm.Encrypt("This text is a bit longer"));

When I decrypt the deviating iPad result on the server, part of the decrypted string is gibberish. The encrypted results from the server decrypt correctly.

The problem does not manifest itself if I create a new FlawedAlgorithm instance for each call, e.g.:

// These statements produce the correct results on the iPad.
Console.WriteLine(new FlawedAlgorithm().Encrypt("Some string"));
Console.WriteLine(new FlawedAlgorithm().Encrypt("This text is a bit longer"));

This leads me to think that the problem lies somewhere in the state of the objects involved. I have inspected the buffer variable in the Encrypt(string) method and the values produced by the UTF8Encoding instance are correct. This implies that the encryptor field (or its underlying implementation) is the culprit.

When I start varying the size of the first encrypted value, I can see changes in the result of the second encryption call. This would probably mean that some part of a stream isn't being cleared or overwritten properly. But the streams the FlawedAlgorithm class uses, aren't part of its state; they are recreated on each method call. And the encryptor object doesn't seem like the type that manages its own streams.

Has anyone else encountered a problem similar to this? Is the RijndaelManaged class flawed? Or are there some stream and memory management pitfalls in MonoTouch at play here, unrelated to this cryptography example?

P.S.: I have tested this on both the iPad and the iPad Simulator; both display this strange behavior.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谜兔 2024-12-06 11:40:04

使用 .NET 加密时,您必须始终检查 ICryptoTransform.CanReuseTransform(或假设它将返回 false)。如果它返回 false,则您无法重复使用相同的加密器/解密器,并且必须创建新实例。

跳过此检查意味着框架中的任何更改(或通过配置文件,因为加密是可插入的)可能会在将来破坏您的应用程序。

您可以使用类似的方法:

 ICryptoTransform Decryptor {
    get {
       if (decryptor == null || !decryptor.CanReuseTransform)
          decryptor = rijndael.CreateDecryptor (key, vector);
        return decryptor;
    }
 }

向加密例程的调用者隐藏这种复杂性。

When using .NET cryptography you must always check ICryptoTransform.CanReuseTransform (or assume it will return false). If it returns false then you cannot reuse the same encryptor/decryptor and must create new instances.

Skipping this check means that any changes in the framework (or via configuration files, since cryptography is pluggable) will likely break your application in the future.

You can use something like:

 ICryptoTransform Decryptor {
    get {
       if (decryptor == null || !decryptor.CanReuseTransform)
          decryptor = rijndael.CreateDecryptor (key, vector);
        return decryptor;
    }
 }

to hide this complexity from the caller of your cryptographic routines.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文