Merge "Fix accessing freed memory in X509CertificateStore::Update()" into tizen
[platform/framework/native/appfw.git] / src / security / crypto / FSecCryptoAesCipher.cpp
1 //
2 // Copyright (c) 2012 Samsung Electronics Co., Ltd.
3 //
4 // Licensed under the Apache License, Version 2.0 (the License);
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //     http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 //
16
17 /**
18  * @file                FSecCryptoAesCipher.cpp
19  * @brief               This file contains the declaration of Tizen::Security::Crypto::AesCipher.
20  */
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unique_ptr.h>
24 #include <openssl/evp.h>
25 #include <openssl/crypto.h>
26 #include <FBaseResult.h>
27 #include <FBaseErrors.h>
28 #include <FSecCryptoAesCipher.h>
29 #include <FSecSecretKey.h>
30 #include <FBaseSysLog.h>
31 #include "FSecCrypto_SymmetricCipher.h"
32
33 using namespace Tizen::Base;
34
35
36 namespace Tizen { namespace Security { namespace Crypto
37 {
38
39 static const int _TRANSFORMATION_STRING_PART_1_LENGTH = 3;
40 static const int _TRANSFORMATION_STRING_PART_2_BEGIN = 4;
41 static const int _TRANSFORMATION_STRING_PART_2_LENGTH = 3;
42 static const int _TRANSFORMATION_STRING_PART_3_BEGIN = 8;
43 static const int _TRANSFORMATION_STRING_PART_3_LENGTH_A = 9;
44 static const int _TRANSFORMATION_STRING_PART_3_LENGTH_B = 12;
45
46 AesCipher::AesCipher(void)
47         : __pSymmetricCipher(null)      // Default is AES/CBC/128
48         , __pCipherAlgorithm(null)
49         , __pAesCipherImpl(null)
50 {
51 }
52
53 AesCipher::~AesCipher(void)
54 {
55         delete __pSymmetricCipher;
56 }
57
58 result
59 AesCipher::Construct(const Tizen::Base::String& transformation, CipherOperation opMode)
60 {
61         result r = E_SUCCESS;
62         bool padVal = false;
63         String cipherMode = null;
64         String padding = null;
65         String keyBit = null;
66
67         SysAssertf(__pSymmetricCipher == null, "Already constructed. Calling Construct() twice or more on a same instance is not allowed for this class");
68
69         __pSymmetricCipher = new (std::nothrow) _SymmetricCipher();
70         SysTryReturn(NID_SEC_CRYPTO, __pSymmetricCipher != null, E_OUT_OF_MEMORY, E_OUT_OF_MEMORY, "[E_OUT_OF_MEMORY] Failed to allocate memory.");
71
72         SysTryCatch(NID_SEC_CRYPTO, transformation.GetLength() > 0, r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The transformation string should be valid.");
73
74         // Setting the key size, cipher mode and padding for the Aes Construct
75         r = transformation.SubString(0, _TRANSFORMATION_STRING_PART_1_LENGTH, cipherMode);
76         SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid.");
77
78         if (cipherMode.CompareTo(L"CBC") == E_SUCCESS)
79         {
80                 r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH, keyBit);
81                 SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid.");
82
83                 if (keyBit.CompareTo(L"128") == E_SUCCESS)
84                 {
85                         __pCipherAlgorithm = EVP_aes_128_cbc();
86                 }
87                 else if (keyBit.CompareTo(L"192") == E_SUCCESS)
88                 {
89                         __pCipherAlgorithm = EVP_aes_192_cbc();
90                 }
91                 else if (keyBit.CompareTo(L"256") == E_SUCCESS)
92                 {
93                         __pCipherAlgorithm = EVP_aes_256_cbc();
94                 }
95                 else
96                 {
97                         r = E_INVALID_ARG;
98                         SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested key length is not supported.");
99                         goto CATCH;
100                 }
101         }
102         else if (cipherMode.CompareTo(L"ECB") == E_SUCCESS)
103         {
104                 r = transformation.SubString(_TRANSFORMATION_STRING_PART_2_BEGIN, _TRANSFORMATION_STRING_PART_2_LENGTH, keyBit);
105                 SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid.");
106
107                 if (keyBit.CompareTo(L"128") == E_SUCCESS)
108                 {
109                         __pCipherAlgorithm = EVP_aes_128_ecb();
110                 }
111                 else if (keyBit.CompareTo(L"192") == E_SUCCESS)
112                 {
113                         __pCipherAlgorithm = EVP_aes_192_ecb();
114                 }
115                 else if (keyBit.CompareTo(L"256") == E_SUCCESS)
116                 {
117                         __pCipherAlgorithm = EVP_aes_256_ecb();
118                 }
119                 else
120                 {
121                         r = E_INVALID_ARG;
122                         SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested key length is not supported.");
123                         goto CATCH;
124                 }
125         }
126         else
127         {
128                 r = E_INVALID_ARG;
129                 SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested mode is not supported.");
130                 goto CATCH;
131         }
132
133         r = transformation.SubString(_TRANSFORMATION_STRING_PART_3_BEGIN, _TRANSFORMATION_STRING_PART_3_LENGTH_A, padding);
134         SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid.");
135
136         if (padding.CompareTo(L"NOPADDING") == E_SUCCESS)
137         {
138                 padVal = false;
139         }
140         else
141         {
142                 r = transformation.SubString(_TRANSFORMATION_STRING_PART_3_BEGIN, _TRANSFORMATION_STRING_PART_3_LENGTH_B, padding);
143                 SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), r = E_INVALID_ARG, E_INVALID_ARG, "The transformation string should be valid.");
144
145                 if (padding.CompareTo(L"PKCS7PADDING") == E_SUCCESS)
146                 {
147                         padVal = true;
148                 }
149                 else
150                 {
151                         r = E_INVALID_ARG;
152                         SysLogException(NID_SEC_CRYPTO, r, "The cipher algorithm for requested padding is not supported.");
153                         goto CATCH;
154                 }
155         }
156
157         // sets the Transformation String
158         r = __pSymmetricCipher->SetTransformation(__pCipherAlgorithm, padVal);
159         SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] Failed to do set transformation operation.", GetErrorMessage(r));
160
161         SysTryCatch(NID_SEC_CRYPTO, opMode == CIPHER_ENCRYPT || opMode == CIPHER_DECRYPT || opMode == CIPHER_WRAP || opMode == CIPHER_UNWRAP,
162                         r = E_INVALID_ARG, E_INVALID_ARG, "[E_INVALID_ARG] The opMode should be valid.");
163
164         // sets the CipherOpearation
165         r = __pSymmetricCipher->SetCipherOperation(opMode);
166         SysTryCatch(NID_SEC_CRYPTO, !IsFailed(r), , r, "[%s] The cipher operation request should be valid.", GetErrorMessage(r));
167
168 CATCH:
169         if (IsFailed(r))
170         {
171                 delete __pSymmetricCipher;
172                 __pSymmetricCipher = null;
173         }
174         return r;
175 }
176
177 result
178 AesCipher::SetKey(const Tizen::Security::ISecretKey& key)
179 {
180         result r = E_SUCCESS;
181         int keyLen = 0;
182
183         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
184
185         std::unique_ptr<ByteBuffer> pKey(key.GetEncodedN());
186         SysTryReturnResult(NID_SEC_CRYPTO, pKey != null, E_INVALID_ARG, "Input key data should be valid.");
187
188         keyLen = static_cast< int >(pKey->GetRemaining());
189         SysTryReturnResult(NID_SEC_CRYPTO, keyLen == __pCipherAlgorithm->key_len, E_INVALID_ARG, "Input key length should be equal to algorithm key length.");
190
191         r = __pSymmetricCipher->SetKey(key);
192         SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set key operation.", GetErrorMessage(r));
193
194         return r;
195 }
196
197 result
198 AesCipher::SetInitialVector(const Tizen::Base::ByteBuffer& initialVector)
199 {
200         result r = E_SUCCESS;
201
202         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
203
204         r = __pSymmetricCipher->SetInitialVector(initialVector);
205         SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do set initial vector operation.", GetErrorMessage(r));
206
207         return r;
208 }
209
210 ByteBuffer*
211 AesCipher::EncryptN(const Tizen::Base::ByteBuffer& input)
212 {
213         ByteBuffer* pOutput = null;
214
215         ClearLastResult();
216
217         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
218
219         pOutput = __pSymmetricCipher->DoCipherN(input);
220         SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do encrypt operation", GetErrorMessage(GetLastResult()));
221
222         return pOutput;
223 }
224
225 ByteBuffer*
226 AesCipher::DecryptN(const Tizen::Base::ByteBuffer& input)
227 {
228         ByteBuffer* pOutput = null;
229
230         ClearLastResult();
231
232         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
233
234         pOutput = __pSymmetricCipher->DoCipherN(input);
235         SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do decrypt operation", GetErrorMessage(GetLastResult()));
236
237         return pOutput;
238 }
239
240 result
241 AesCipher::Initialize(void)
242 {
243         result r = E_SUCCESS;
244
245         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
246
247         r = __pSymmetricCipher->Initialize();
248         SysTryReturn(NID_SEC_CRYPTO, !IsFailed(r), r, r, "[%s] Failed to do initialize operation.", GetErrorMessage(r));
249
250         return r;
251 }
252
253 ByteBuffer*
254 AesCipher::UpdateN(const Tizen::Base::ByteBuffer& input)
255 {
256         ByteBuffer* pOutput = null;
257
258         ClearLastResult();
259
260         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
261
262         pOutput = __pSymmetricCipher->UpdateN(input);
263         SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do update operation", GetErrorMessage(GetLastResult()));
264
265         return pOutput;
266 }
267
268 ByteBuffer*
269 AesCipher::FinalizeN(void)
270 {
271         ByteBuffer* pOutput = null;
272
273         ClearLastResult();
274
275         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
276
277         pOutput = __pSymmetricCipher->FinalizeN();
278         SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do finalize operation", GetErrorMessage(GetLastResult()));
279
280         return pOutput;
281 }
282
283 ByteBuffer*
284 AesCipher::WrapN(const Tizen::Base::ByteBuffer& secretKey)
285 {
286         ByteBuffer* pOutput = null;
287
288         ClearLastResult();
289
290         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
291
292         pOutput = __pSymmetricCipher->WrapN(secretKey);
293         SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do wrap operation", GetErrorMessage(GetLastResult()));
294
295         return pOutput;
296 }
297
298 ByteBuffer*
299 AesCipher::UnwrapN(const Tizen::Base::ByteBuffer& wrappedKey)
300 {
301         ByteBuffer* pOutput = null;
302
303         ClearLastResult();
304
305         SysAssertf(__pSymmetricCipher != null, "Not yet constructed. Construct() should be called before use.");
306
307         pOutput = __pSymmetricCipher->UnwrapN(wrappedKey);
308         SysTryReturn(NID_SEC_CRYPTO, pOutput != null, null, GetLastResult(), "[%s]Failed to do unwrap operation", GetErrorMessage(GetLastResult()));
309
310         return pOutput;
311 }
312
313 } } } //Tizen::Security::Crypto