1

我将一堆加密算法编写为类,现在我想实现加密模式(维基百科中显示的通用模式,而不是算法规范中的特定模式)。我将如何编写一个可以接受任何类的函数?

编辑:

这就是我想要完成的

class mode{
  private:
    algorithm_class

  public:
    mode(Algorithm_class, key, mode){
       algorithm_class = Algorithm_class(key, mode);

    }

};
4

2 回答 2

3

您可以使用抽象类:

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-您不知道也不关心您正在使用哪种特定算法,只是它实现了所有加密算法应该实现的接口。

于 2011-06-05T04:23:58.367 回答
2

嗯,怎么样

template<class AlgorithmType>
class mode{
  private:
    AlgorithmType _algo;

  public:
    mode(const AlgorithmType& algo)
      : _algo(algo) {}
};

?

不需要modekey参数,因为算法可以由用户创建:

mode<YourAlgorithm> m(YourAlgorithm(some_key,some_mode));
于 2011-06-05T04:18:00.180 回答