2 * Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
16 #include <openssl/rand.h>
17 #include <openssl/crypto.h>
18 #include <openssl/hmac.h>
19 #include <openssl/aes.h>
20 #include <openssl/err.h>
21 #include <openssl/sha.h>
23 #include <klay/filesystem.h>
24 #include <klay/exception.h>
26 #include "../logger.h"
27 #include "key-generator.h"
29 #define PBKDF_DEFAULT_ITERATION 1000
32 #error This requires AES
35 #ifdef OPENSSL_NO_SHA256
36 #error This requires SHA256
39 #ifdef OPENSSL_NO_SHA512
40 #error This requires SHA512
45 namespace KeyGenerator {
49 EVP_add_cipher(EVP_aes_256_cbc());
50 EVP_add_digest(EVP_sha256());
51 EVP_add_digest(EVP_sha512());
60 BinaryData PBKDF(const BinaryData& pass,
61 const BinaryData& salt,
65 BinaryData ret(resultSize, 0);
67 ::PKCS5_PBKDF2_HMAC((char *)pass.data(), pass.size(),
68 salt.data(), salt.size(), iteration,
69 EVP_sha256(), resultSize, ret.data());
74 BinaryData AESEncrypt(const BinaryData& in,
75 const BinaryData& key,
78 BinaryData ret(in.size(), 0);
82 ctx = ::EVP_CIPHER_CTX_new();
84 ::EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key.data(), iv.data());
86 ::EVP_CIPHER_CTX_set_padding(ctx, 0);
87 ::EVP_EncryptUpdate(ctx, ret.data(), &len, in.data(), in.size());
90 ::EVP_EncryptFinal_ex(ctx, &ret[len], &len);
93 ::EVP_CIPHER_CTX_free(ctx);
98 BinaryData AESDecrypt(const BinaryData& in,
99 const BinaryData& key,
100 const BinaryData& iv)
102 BinaryData ret(in.size(), 0);
107 ctx = ::EVP_CIPHER_CTX_new();
109 ::EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key.data(), iv.data());
110 ::EVP_CIPHER_CTX_set_padding(ctx, 0);
111 ::EVP_DecryptUpdate(ctx, ret.data(), &len, in.data(), in.size());
115 ::EVP_DecryptFinal_ex(ctx, &ret[len], &len);
118 ::EVP_CIPHER_CTX_free(ctx);
123 BinaryData HMAC(const BinaryData& key, const BinaryData& in)
125 BinaryData ret(256 / 8);
128 ::HMAC(EVP_sha256(), key.data(), key.size(), in.data(), in.size(),
129 ret.data(), &md_len);
134 BinaryData RNG(size_t resultSize)
136 BinaryData ret(resultSize);
138 if(::RAND_bytes(ret.data(), resultSize) != 1)
139 throw runtime::Exception("RAND_bytes() failed");
144 BinaryData SHA256(const BinaryData& in)
146 BinaryData ret(256 / 8);
148 ::SHA256(in.data(), in.size(), ret.data());
153 BinaryData SHA512(const BinaryData& in)
155 BinaryData ret(512 / 8);
157 ::SHA512(in.data(), in.size(), ret.data());
162 } // namespace KeyManager