I have an Interface
public interface ICrypto<T> : IDisposable
{
ICryptoTransform GetDecryptor();
ICryptoTransform GetEncryptor();
T GetAlgorithm();
}
I have an implementation
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();
}
}
i have a class that implements implementation above
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));
}
}
}
I am having problem instantiating class CryptoWork<T> where T : ICrypto<T>, new()
:
Neither
var cryptoWork = new CryptoWork < ICrypto < TripleDESCryptoProvider > > ();
nor
var cryptoWork = new CryptoWork < TripleDESCryptoProvider > ();
compiles.
You have specified:
CryptoWork<T> where T : ICrypto<T>, new()
and you are using
new CryptoWork<TripleDESCryptoProvider>();
For that to work, we would need:
TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>
(since T
= TripleDESCryptoProvider
)
But you have:
TripleDESCryptoProvider : ICrypto<TripleDESCryptoServiceProvider>
and a public parameterless constructor (which you have). Options:
TripleDESCryptoProvider : ICrypto<TripleDESCryptoProvider>
CryptoWork
type have 2 generic type parameters; one for the TripleDESCryptoProvider
, another for the TripleDESCryptoServiceProvider
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.