我写了一堆加密算法作为类,现在我想实现加密模式(维基百科中显示的通用模式,而不是算法规范中的特定模式)。我将如何编写可以接受任何类的函数?
编辑:
这是我想要完成的
class mode{
private:
algorithm_class
public:
mode(Algorithm_class, key, mode){
algorithm_class = Algorithm_class(key, mode);
}
};
最佳答案
你可以使用抽象类:
class CryptoAlgorithm
{
public:
// whatever functions all the algorithms do
virtual vector<char> Encrypt(vector<char>)=0;
virtual vector<char> Decrypt(vector<char>)=0;
virtual void SetKey(vector<char>)=0;
// etc
}
// user algorithm
class DES : public CryptoAlgorithm
{
// implements the Encrypt, Decrypt, SetKey etc
}
// your function
class mode{
public:
mode(CryptoAlgorithm *algo) // << gets a pointer to an instance of a algo-specific class
//derived from the abstract interface
: _algo(algo) {}; // <<- make a "Set" method to be able to check for null or
// throw exceptions, etc
private:
CryptoAlgorithm *_algo;
}
// in your code
...
_algo->Encrypt(data);
...
//
通过这种方式,当您调用 _algo->Encrypt
- 您不知道也不关心您使用的是哪种特定算法,只是它实现了所有加密算法的接口(interface)应该实现。
关于c++ - 类作为函数c++的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240944/