fork download
  1. #include <functional>
  2. #include <ios>
  3. #include <streambuf>
  4.  
  5. template <typename CharT, class Traits = std::char_traits<CharT>>
  6. class encrypted_basic_streambuf : public std::basic_streambuf<CharT, Traits>
  7. {
  8. public:
  9. // Irgendwie notwendig. Bug?
  10. using char_type = typename std::basic_streambuf<CharT, Traits>::char_type;
  11. using traits_type = typename std::basic_streambuf<CharT, Traits>::traits_type;
  12. using int_type = typename std::basic_streambuf<CharT, Traits>::int_type;
  13.  
  14. using encryption_function = std::function<char_type(char_type)>;
  15.  
  16. encrypted_basic_streambuf(std::basic_ios<char_type, traits_type> &stream,
  17. encryption_function function)
  18. : stream_(stream), streambuf_(stream.rdbuf()), function_(function)
  19. {
  20. stream_.rdbuf(this);
  21. }
  22.  
  23. ~encrypted_basic_streambuf()
  24. {
  25. stream_.rdbuf(streambuf_);
  26. }
  27.  
  28. protected:
  29. int_type underflow() override
  30. {
  31. auto c = streambuf_->sgetc();
  32. return traits_type::eq_int_type(c, traits_type::eof()) ? c : function_(c);
  33. }
  34.  
  35. int_type uflow() override
  36. {
  37. auto c = streambuf_->sbumpc();
  38. return traits_type::eq_int_type(c, traits_type::eof()) ? c : function_(c);
  39. }
  40.  
  41. int_type overflow(int_type c) override
  42. {
  43. streambuf_->sputc(function_(c));
  44. return c;
  45. }
  46.  
  47. private:
  48. std::basic_ios<char_type, traits_type> &stream_;
  49. std::basic_streambuf<char_type, traits_type> *streambuf_;
  50. encryption_function function_;
  51. };
  52.  
  53. #include <iostream>
  54.  
  55. int main()
  56. {
  57. {
  58. encrypted_basic_streambuf<char> encrypter(std::cout, [](char c){return c ^ 'a';});
  59. std::cout << "Hallo Welt";
  60. }
  61. std::cout << "\n Test 2: \n";
  62. {
  63. class xor_encrypter
  64. {
  65. public:
  66. xor_encrypter(char key)
  67. : key_(key) {}
  68.  
  69. char operator() (char c)
  70. {
  71. return c ^ key_++;
  72. }
  73.  
  74. private:
  75. char key_;
  76. };
  77.  
  78. encrypted_basic_streambuf<char> encrypter(std::cout, xor_encrypter('a'));
  79. std::cout << "Hallo Welt";
  80. }
  81. }
  82.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
)

A6

 Test 2: 
)
F0