Adapt key-manager to work with OpenSSL 1.1 preserving 1.0 compatibility
[platform/core/security/key-manager.git] / src / manager / service / ss-crypto.cpp
index 1da144a..f6a2de2 100644 (file)
@@ -1,5 +1,5 @@
 /*
- *  Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
+ *  Copyright (c) 2016 - 2019 Samsung Electronics Co., Ltd All Rights Reserved
  *
  *  Licensed under the Apache License, Version 2.0 (the "License");
  *  you may not use this file except in compliance with the License.
 
 #include <dpl/log/log.h>
 
+// lengths defined as macro to be used independent to type (size_t, unsigned int, int)
+#define SALT_SIZE 32
+#define KEY_SIZE 16
+#define IV_SIZE KEY_SIZE
+
 namespace CKM {
 
 namespace {
 
-const int SALT_SIZE = 32;
-const int KEY_SIZE = 16;
-
 RawBuffer _get_key(const std::string &id)
 {
        unsigned char salt[SALT_SIZE];
@@ -56,8 +58,9 @@ RawBuffer _get_key(const std::string &id)
 
 RawBuffer _get_iv(const RawBuffer &src)
 {
-       RawBuffer iv(KEY_SIZE);
-       size_t ivlen = iv.size();
+       RawBuffer iv(SHA_DIGEST_LENGTH);
+
+       unsigned int ivlen = 0;
 
        if (::EVP_Digest(src.data(), src.size(), iv.data(), &ivlen, ::EVP_sha1(), nullptr)
                        != 1) {
@@ -65,13 +68,31 @@ RawBuffer _get_iv(const RawBuffer &src)
                return RawBuffer();
        }
 
+       if (ivlen < IV_SIZE) {
+               LogError("Invalid iv size: " << ivlen);
+               return RawBuffer();
+       }
+
+       iv.resize(IV_SIZE);
+
        return iv;
 }
 
 RawBuffer _decrypt(const RawBuffer &key, const RawBuffer &iv, const RawBuffer &ciphertext)
 {
        auto algo = ::EVP_aes_128_cbc();
-       int tmp_len = (ciphertext.size() / algo->block_size + 1) * algo->block_size;
+       auto block_size = ::EVP_CIPHER_block_size(algo);
+       int tmp_len = (ciphertext.size() / block_size + 1) * block_size;
+
+       if (key.size() != KEY_SIZE) {
+               LogError("Invalid key size: " << key.size() << ", expected: " << KEY_SIZE);
+               return RawBuffer();
+       }
+
+       if (iv.size() != IV_SIZE) {
+               LogError("Invalid iv size: " << iv.size() << ", expected: " << IV_SIZE);
+               return RawBuffer();
+       }
 
        RawBuffer plaintext(tmp_len, 0);