3

我有一个接口

public interface ICrypto<T> : IDisposable
{
     ICryptoTransform GetDecryptor();

     ICryptoTransform GetEncryptor();

     T GetAlgorithm();
}

我有一个实现

public class TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>
{

    public TripleDESCryptoProvider() { }

    public ICryptoTransform GetDecryptor()
    {
        return GetAlgorithm().CreateDecryptor();
    }

    public ICryptoTransform GetEncryptor()
    {
        return GetAlgorithm().CreateEncryptor();
    }

    public TripleDESCryptoServiceProvider GetAlgorithm()
    {
     ...
    }

    public void Dispose()
    {
        throw new NotImplementedException();
    }
}

我有一个实现上述实现的类

public class CryptoWork<T> where T : ICrypto<T>, new()
{
    protected static T _keyStore;

    public static T KeyStore
    {
        get
        {
            if (_keyStore == null)
            {
                _keyStore = new T();
            }
            return _keyStore;
        }
    }

    /// <summary>
    /// Encrypt a byte array
    /// </summary>
    public string Encrypt(string input)
    {
        byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
        using (var encryptor = KeyStore.GetEncryptor())
        {
            return Convert.ToBase64String(encryptor.TransformFinalBlock(inputArray, 0, inputArray.Length));
        }
    }

    /// <summary>
    /// Decrypt a byte array
    /// </summary>
    public string Decrypt(string input)
    {
        byte[] inputArray = Convert.FromBase64String(input);
        using (var encryptor = KeyStore.GetDecryptor())
        {
            return UTF8Encoding.UTF8.GetString(encryptor.TransformFinalBlock(inputArray, 0, inputArray.Length));
        }
    }
}

我在实例化类时遇到问题CryptoWork<T> where T : ICrypto<T>, new()

两者都不

 var cryptoWork = new CryptoWork < ICrypto < TripleDESCryptoProvider > > ();

也不

var cryptoWork = new CryptoWork < TripleDESCryptoProvider > ();

编译。

4

1 回答 1

6

您已指定:

CryptoWork<T> where T : ICrypto<T>, new()

你正在使用

new CryptoWork<TripleDESCryptoProvider>();

为此,我们需要:

TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>

(因为T= TripleDESCryptoProvider

但是你有:

TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>

和一个公共的无参数构造函数(你有)。选项:

  • 制作TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>
  • 重构 API
  • 使该CryptoWork类型具有 2 个泛型类型参数;一个用于TripleDESCryptoProvider,另一个用于TripleDESCryptoServiceProvider
于 2013-01-17T23:46:06.043 回答