2016-05-13 196 views
1

是否有可能在Poco Crypto中使用AES128设置加密填充?我无法找到任何选项。在Poco Crypto中设置加密填充

std::string Crypto::Encrypt(const std::string &input, const std::string &key) 
{ 
    Poco::Crypto::Cipher::ByteVec iv { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 
    Poco::Crypto::Cipher::ByteVec key2 {key.begin(), key.end()}; 

    Poco::Crypto::Cipher::Ptr pCipher = Poco::Crypto::CipherFactory::defaultFactory() 
     .createCipher(Poco::Crypto::CipherKey("aes128", key2, iv)); 

    std::string output = pCipher->encryptString(input); 

    return std::move(output); 
} 

简单的OpenSSL我有这个选项:

EVP_CIPHER_CTX *ctx; 

EVP_CIPHER_CTX_set_padding(ctx, 0) 

回答

1

默认情况下,填充被启用。

Crypto/include/Poco/Crypto/CryptoTransform.hhttps://pocoproject.org/docs/Poco.Crypto.CryptoTransform.html#230的评论中,加密操作默认被填充。

... 
virtual int setPadding(int padding); 
    /// Enables or disables padding. By default encryption operations are padded using standard block 
    /// padding and the padding is checked and removed when decrypting. If the padding parameter is zero then 
    /// no padding is performed, the total amount of data encrypted or decrypted must then be a multiple of 
    /// the block size or an error will occur. 
... 

如果你想改变填充选项,你应该重写createEncryptor()creatoreDecryptor()Poco::Crypto::Cipher像下面

class CipherWithPadding : public Poco::Crypto::Cipher 
{ 
public: 
    // by default no padding, for more information refer to CryptoTransform::setPadding 
    CipherWithPadding(Poco::Crypto::Cipher::Ptr cipher_impl, int padding = 0) 
    : cipher_(cipher_impl) 
    , padding_(padding) 
    { 
    } 

    virtual ~CipherWithPadding() 
    { 
    } 

    virtual const std::string& name() const 
    { 
     return cipher_->name(); 
    } 

    virtual Poco::Crypto::CryptoTransform* createEncryptor() override 
    { 
     auto ptransform = cipher_->createEncryptor(); 
     if (ptransform) 
      ptransform->setPadding(padding_); 
     return ptransform; 
    } 

    virtual Poco::Crypto::CryptoTransform* createDecryptor() override 
    { 
     auto ptransform = cipher_->createDecryptor(); 
     if (ptransform) 
      ptransform->setPadding(padding_); 
     return ptransform; 
    } 

protected: 
    int padding_; 
    Poco::Crypto::Cipher::Ptr cipher_; 

protected: 
    CipherWithPadding(); 

private: 
    CipherWithPadding(const CipherWithPadding&); 
    CipherWithPadding& operator= (const CipherWithPadding&); 
}; 

然后你的函数应该像下面

std::string Crypto::Encrypt(const std::string &input, const std::string &key) 
{ 
    Poco::Crypto::Cipher::ByteVec iv { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 
    Poco::Crypto::Cipher::ByteVec key2 {key.begin(), key.end()}; 

    CipherWithPadding cipher(Poco::Crypto::CipherFactory::defaultFactory() 
     .createCipher(Poco::Crypto::CipherKey("aes128", key2, iv))); 

    std::string output = cipher.encryptString(input); 

    return std::move(output); 
}