1//
2// Cipher.cpp
3//
4// Library: Crypto
5// Package: Cipher
6// Module: Cipher
7//
8// Copyright (c) 2008, Applied Informatics Software Engineering GmbH.
9// and Contributors.
10//
11// SPDX-License-Identifier: BSL-1.0
12//
13
14
15#include "Poco/Crypto/Cipher.h"
16#include "Poco/Crypto/CryptoStream.h"
17#include "Poco/Crypto/CryptoTransform.h"
18#include "Poco/Base64Encoder.h"
19#include "Poco/Base64Decoder.h"
20#include "Poco/HexBinaryEncoder.h"
21#include "Poco/HexBinaryDecoder.h"
22#include "Poco/StreamCopier.h"
23#include "Poco/Exception.h"
24#include <sstream>
25#include <memory>
26
27
28namespace Poco {
29namespace Crypto {
30
31
32Cipher::Cipher()
33{
34}
35
36
37Cipher::~Cipher()
38{
39}
40
41
42std::string Cipher::encryptString(const std::string& str, Encoding encoding)
43{
44 std::istringstream source(str);
45 std::ostringstream sink;
46
47 encrypt(source, sink, encoding);
48
49 return sink.str();
50}
51
52
53std::string Cipher::decryptString(const std::string& str, Encoding encoding)
54{
55 std::istringstream source(str);
56 std::ostringstream sink;
57
58 decrypt(source, sink, encoding);
59 return sink.str();
60}
61
62
63void Cipher::encrypt(std::istream& source, std::ostream& sink, Encoding encoding)
64{
65 CryptoInputStream encryptor(source, createEncryptor());
66
67 switch (encoding)
68 {
69 case ENC_NONE:
70 StreamCopier::copyStream(encryptor, sink);
71 break;
72
73 case ENC_BASE64:
74 case ENC_BASE64_NO_LF:
75 {
76 Poco::Base64Encoder encoder(sink);
77 if (encoding == ENC_BASE64_NO_LF)
78 {
79 encoder.rdbuf()->setLineLength(0);
80 }
81 StreamCopier::copyStream(encryptor, encoder);
82 encoder.close();
83 }
84 break;
85
86 case ENC_BINHEX:
87 case ENC_BINHEX_NO_LF:
88 {
89 Poco::HexBinaryEncoder encoder(sink);
90 if (encoding == ENC_BINHEX_NO_LF)
91 {
92 encoder.rdbuf()->setLineLength(0);
93 }
94 StreamCopier::copyStream(encryptor, encoder);
95 encoder.close();
96 }
97 break;
98
99 default:
100 throw Poco::InvalidArgumentException("Invalid argument", "encoding");
101 }
102}
103
104
105void Cipher::decrypt(std::istream& source, std::ostream& sink, Encoding encoding)
106{
107 CryptoOutputStream decryptor(sink, createDecryptor());
108
109 switch (encoding)
110 {
111 case ENC_NONE:
112 StreamCopier::copyStream(source, decryptor);
113 decryptor.close();
114 break;
115
116 case ENC_BASE64:
117 case ENC_BASE64_NO_LF:
118 {
119 Poco::Base64Decoder decoder(source);
120 StreamCopier::copyStream(decoder, decryptor);
121 decryptor.close();
122 }
123 break;
124
125 case ENC_BINHEX:
126 case ENC_BINHEX_NO_LF:
127 {
128 Poco::HexBinaryDecoder decoder(source);
129 StreamCopier::copyStream(decoder, decryptor);
130 decryptor.close();
131 }
132 break;
133
134 default:
135 throw Poco::InvalidArgumentException("Invalid argument", "encoding");
136 }
137}
138
139
140} } // namespace Poco::Crypto
141