├── .gitignore ├── main.cpp ├── SConstruct.py ├── README.md ├── kpabe.hpp ├── kpabe_test.cpp ├── LICENSE └── kpabe.cpp /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | #vscode 35 | .vscode/ 36 | 37 | # Scons 38 | .sconsign.dblite -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #include "pbc.h" 5 | 6 | #include "kpabe.hpp" 7 | 8 | using namespace std; 9 | 10 | int main() { 11 | // Setup the scheme 12 | PrivateParams priv; 13 | PublicParams pub; 14 | vector attributeUniverse {1, 2, 3, 4, 5}; 15 | setup(attributeUniverse, pub, priv); 16 | 17 | // Create an access policy and derive a key for it. 18 | // (1 OR 2) AND (3 OR 4) 19 | Node orNodeLeft(Node::Type::OR, {1, 2}); 20 | Node orNodeRight(Node::Type::OR, {3, 4}); 21 | Node root(Node::Type::AND, {orNodeLeft, orNodeRight}); 22 | 23 | auto key = keyGeneration(priv, root); 24 | 25 | // Create an attribute-based secret (attributes 1 and 3). 26 | element_s secret; 27 | vector encryptionAttributes {1, 3}; 28 | auto Cw = createSecret(pub, encryptionAttributes, secret); 29 | 30 | // Recover secret 31 | element_s recovered; 32 | recoverSecret(key, Cw, encryptionAttributes, recovered); 33 | cout << element_cmp(&secret, &recovered) << endl; // should be ==0 34 | 35 | for(auto& attrCiPair: Cw) { 36 | element_clear(&attrCiPair.second); 37 | } 38 | Cw.clear(); 39 | 40 | // Secret cannto be recovered if the encryption attributes do not satisfy the policy. 41 | encryptionAttributes = {1}; 42 | Cw = createSecret(pub, encryptionAttributes, secret); 43 | try { 44 | recoverSecret(key, Cw, encryptionAttributes, recovered); 45 | } catch(const UnsatError& e) { 46 | cout << "Unsatisfied" << endl; 47 | } 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /SConstruct.py: -------------------------------------------------------------------------------- 1 | """SConstruct file that builds: 2 | - kpabe static lib 3 | - main.cpp 4 | - unittests 5 | """ 6 | import os 7 | 8 | CXXFLAGS = ["-std=gnu++14",] 9 | 10 | def getNativeEnv(): 11 | """Get the environment. 12 | """ 13 | INCLUDES = [ 14 | "-I.", 15 | "-I/usr/local/include", 16 | "-I/usr/local/include/pbc", 17 | ] 18 | LIBPATH = [ 19 | "#", 20 | "/usr/local/lib", 21 | ] 22 | LIBS = [ 23 | "pbc", 24 | "gmp", 25 | "mbedcrypto", 26 | "m", 27 | ] 28 | 29 | env = DefaultEnvironment(CXXFLAGS=CXXFLAGS + ["-Os"] + INCLUDES, 30 | LIBS=LIBS, 31 | LIBPATH=LIBPATH) 32 | return env 33 | 34 | def getKpabeLib(env): 35 | """Get target for kpabe static lib. 36 | """ 37 | return env.StaticLibrary("kpabe", ["kpabe.cpp"]) 38 | 39 | def getTestsTarget(env): 40 | """Get test targets. 41 | """ 42 | BOOST_H = "/usr/local/include/boost" 43 | BOOST_TEST_LIB = "boost_unit_test_framework" 44 | 45 | files = ["kpabe_test.cpp"] 46 | testEnv = env.Clone() 47 | testEnv["LIBS"].insert(0, ["kpabe", BOOST_TEST_LIB]) 48 | testCases = []; 49 | for f in files: 50 | targetFile = os.path.join("#", 51 | str(f).split('.')[0].split(os.path.sep)[-1]) 52 | testCases.append(testEnv.Program(targetFile, [f])) 53 | 54 | return testCases 55 | 56 | def getMainTarget(env): 57 | """Get main target. 58 | """ 59 | mainEnv = env.Clone() 60 | mainEnv["LIBS"].insert(0, "kpabe") 61 | return mainEnv.Program("main", "#main.cpp") 62 | 63 | def getAllTargets(env): 64 | """Get all targets. 65 | """ 66 | targets = getTestsTarget(env) + getMainTarget(env) 67 | return targets 68 | 69 | env = getNativeEnv() 70 | env.Default(getAllTargets(env) + getKpabeLib(env)) 71 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # A lightweight Attribute-Based Encryption Scheme in C++ 2 | 3 | This project is a C++ implementation of the lightweight Key-Policy Attribute-Based 4 | Encryption (KP-ABE) scheme from [1]. 5 | 6 | The scheme has significant performance advantages[2] over other schemes by relying on 7 | elliptic curve cryptography as opposed to bilinear pairings. Its security is proved in 8 | the attribute-based selective-set model. 9 | 10 | The implementation can run on a [ESP32](https://github.com/espressif/esp-idf) 11 | device with slight modifications. I removed these modifications for simplicity, but if 12 | you are interested in running it on an ESP32, open an issue and I will add it. 13 | # Compilation 14 | ## Dependencies 15 | The project depends on: 16 | 17 | * [gmp](https://gmplib.org) - The GNU Multiple Precision Arithmetic Library 18 | * [pbc](https://crypto.stanford.edu/pbc/) - Pairing-Based Cryptography Library 19 | * mbedcrypto from [mbedtls](https://tls.mbed.org) 20 | * (for the tests only) [Boost.Test](http://www.boost.org/doc/libs/1_65_1/libs/test/doc/html/index.html) 21 | 22 | The include and library paths for the above can be seen in the [SConstruct.py](SConstruct.py) in the 23 | `INCLUDES` and `LIBPATH` variables. Go ahead and change them if necessary. 24 | 25 | ## Compiling 26 | The project compiles with [scons](http://scons.org) in the root directory. Just run: 27 | 28 | ```sh 29 | scons -f SConstruct.py 30 | ``` 31 | 32 | This generates the static library `libkpabe`, but it's straightforward to compile with 33 | your code without using a library. The above also produces the tests (`kpabe_test`) and a 34 | simple example program (`main`). 35 | 36 | The reason that this is compiled as a static library and that it uses mbedtls instead of 37 | some other common crypto is because the project had to run on a ESP32 38 | device. 39 | 40 | # API 41 | Here is a simple example of generating a key and a secret and then using the key to 42 | recover the secret. 43 | 44 | ```c++ 45 | // Setup the scheme 46 | PrivateParams priv; 47 | PublicParams pub; 48 | vector attributeUniverse {1, 2, 3, 4, 5}; 49 | setup(attributeUniverse, pub, priv); 50 | 51 | // Create an access policy and derive a key for it. 52 | // (1 OR 2) AND (3 OR 4) 53 | Node orNodeLeft(Node::Type::OR, {1, 2}); 54 | Node orNodeRight(Node::Type::OR, {3, 4}); 55 | Node root(Node::Type::AND, {orNodeLeft, orNodeRight}); 56 | 57 | auto key = keyGeneration(priv, root); 58 | 59 | // Create an attribute-based secret (attributes 1 and 3). 60 | element_s secret; 61 | vector encryptionAttributes {1, 3}; 62 | auto Cw = createSecret(pub, encryptionAttributes, secret); // Decryption parameters 63 | 64 | // Recover secret 65 | element_s recovered; 66 | recoverSecret(key, Cw, attributes, recovered); 67 | element_cmp(&secret, &recovered); // should be ==0 68 | 69 | for(auto& attrCiPair: Cw) { //clean up 70 | element_clear(&attrCiPair.second); 71 | } 72 | 73 | // Secret cannot be recovered if the policy is not satisfied by the encryption attributes. 74 | encryptionAttributes = {1}; 75 | Cw = createSecret(pub, encryptionAttributes, secret); 76 | try { 77 | recoverSecret(key, Cw, encryptionAttributes, recovered); 78 | } catch(const UnsatError& e) { 79 | cout << "Unsatisfied" << endl; 80 | } 81 | 82 | // Clean up (this should happen as part of destruction, so my bad) 83 | for(auto& attrDiPair: key.Di) { 84 | element_clear(&attrDiPair.second); 85 | } 86 | 87 | for(auto& attrCiPair: Cw) { 88 | element_clear(&attrCiPair.second); 89 | } 90 | ``` 91 | 92 | I would like to change at least a few things in the API, should I find the time. 93 | Suggestions are always welcome. 94 | 95 | There is also a [python implementation](https://github.com/JHUISI/charm/blob/dev/charm/schemes/abenc/abenc_yct14.py) of this scheme as part of Charm. 96 | 97 | # Issues 98 | It should be possible to use the same attribute more than once in a policy - e.g. 99 | *((1 OR 2) AND (1 OR 3))*. However, the current implementation does not allow this. 100 | 101 | # References 102 | [1] *X. Yao, Z. Chen and Y. Tian, “A lightweight attribute-based encryption scheme for the Internet of Things,” Future Generation Computer Systems, vol. 49, pp. 104-112, 2015.* 103 | [link](http://www.sciencedirect.com/science/article/pii/S0167739X14002039) 104 | 105 | [2] *S. Zickau, D. Thatmann, A. Butyrtschik, I. Denisow and A. Küpper, “Applied Attribute- based Encryption Schemes,” in 19th International ICIN Conference - Innovations in Clouds, Internet and Networks, Paris, 2016.* 106 | [link](http://dl.ifip.org/db/conf/icin/icin2016/1570228068.pdf) 107 | -------------------------------------------------------------------------------- /kpabe.hpp: -------------------------------------------------------------------------------- 1 | #ifndef kpabe_ 2 | #define kpabe_ 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include 10 | 11 | #pragma GCC visibility push(default) 12 | 13 | /** 14 | * @brief KP-ABE implicit parameters. 15 | */ 16 | static const std::string TYPE_A_PARAMS = \ 17 | "type a\n" \ 18 | "q 87807107996633125224377819847540498158068831994142082" \ 19 | "1102865339926647563088022295707862517942266222142315585" \ 20 | "8769582317459277713367317481324925129998224791\n" \ 21 | "h 12016012264891146079388821366740534204802954401251311" \ 22 | "822919615131047207289359704531102844802183906537786776\n" \ 23 | "r 730750818665451621361119245571504901405976559617\n" \ 24 | "exp2 159\n" \ 25 | "exp1 107\n" \ 26 | "sign1 1\n" \ 27 | "sign0 1\n"; 28 | 29 | /** 30 | * @brief Returns a pairing object. 31 | * 32 | * We only ever need one. 33 | */ 34 | pairing_ptr getPairing(); 35 | 36 | /** 37 | * @brief Compute a hash from an element. 38 | */ 39 | void hashElement(element_t e, uint8_t* key); 40 | 41 | class Node { 42 | 43 | public: 44 | enum Type { OR, AND }; 45 | 46 | int attr; 47 | 48 | private: 49 | Type type; 50 | std::vector children; 51 | 52 | public: 53 | Node(const Node& other); 54 | Node(Node&& other); 55 | Node(int attr); 56 | Node(Type type, const std::vector& children = { }); 57 | 58 | Node& operator=(Node other); 59 | Node& operator=(Node&& other); 60 | 61 | void addChild(const Node& node); 62 | const std::vector& getChildren() const; 63 | 64 | //TODO: Abstract traversal order 65 | /** 66 | * @brief Returns all leaf nodes under the given node. 67 | */ 68 | std::vector getLeafs() const; 69 | unsigned int getThreshold() const; 70 | unsigned int getPolyDegree() const; 71 | 72 | /** 73 | * @brief Split the given secret share to the children of the given node. 74 | * 75 | * This sets p(0) = rootSecret and generates a random getPolyDegree polynomial. 76 | * The index of the shares follow the index of the children of the node + 1 (index 0 is 77 | * the root secret). 78 | */ 79 | std::vector splitShares(element_s& rootSecret); 80 | 81 | //TODO: Abstract tree traversal 82 | /** 83 | * @brief Performs Shamir's secret-sharing scheme in a top-down manner. 84 | * 85 | * The secret shares for the access tree are returned as a vector, where the positions 86 | * correspond to the left-to-right tree traversal. 87 | */ 88 | std::vector getSecretShares(element_s& rootSecret); 89 | 90 | /** 91 | * @brief Computes the Lagrange coefficients. 92 | * 93 | * Assumes an interpolated value of 0 and that the children of the node have index() 94 | * values in the range 1..#numChildren. 95 | */ 96 | std::vector recoverCoefficients(); 97 | 98 | /** 99 | * @brief Computes the Lagrange coefficients for a satisfying subset of attributes. 100 | * 101 | * @return A vector of attribute-coefficient pairs. 102 | */ 103 | std::vector< std::pair > 104 | satisfyingAttributes(const std::vector& attributes, 105 | element_s& currentCoeff); 106 | }; 107 | 108 | class DecryptionKey { 109 | 110 | public: 111 | Node accessPolicy; 112 | std::map Di; 113 | 114 | DecryptionKey(const DecryptionKey& other) = default; 115 | DecryptionKey(const Node& policy); 116 | }; 117 | 118 | typedef struct { 119 | element_s pk; 120 | std::map Pi; 121 | } PublicParams; 122 | 123 | typedef struct { 124 | element_s mk; 125 | std::map Si; 126 | } PrivateParams; 127 | 128 | typedef std::map Cw_t; 129 | 130 | /** 131 | * @brief Generates the public and private parameters of the scheme. 132 | */ 133 | void setup(const std::vector& attributes, 134 | PublicParams& publicParams, 135 | PrivateParams& privateParams); 136 | 137 | /** 138 | * @brief Creates a decryption key. 139 | * 140 | * This is the KeyGeneration algorithm. 141 | */ 142 | DecryptionKey keyGeneration(PrivateParams& privateParams, Node &accessPolicy); 143 | 144 | /** 145 | * @brief Creates a KP-ABE secret. 146 | * 147 | * This is the Encryption algorithm, but without deriving a key and encryption. 148 | * Ciphertext C will hold the decryption parameters, the secret is Cs. 149 | */ 150 | Cw_t createSecret(PublicParams& params, 151 | const std::vector& attributes, 152 | element_s& Cs); 153 | 154 | /** 155 | * @brief Recovers a KP-ABE secret using the decryption key and decryption parameters. 156 | */ 157 | void recoverSecret(DecryptionKey& key, 158 | Cw_t& Cw, 159 | const std::vector& attributes, 160 | element_s& Cs); 161 | 162 | /** 163 | * @brief Encrypts a message under a given attribute set. 164 | * 165 | * This is the actual Encryption algorithm, but without a HMAC. 166 | */ 167 | std::vector encrypt(PublicParams& params, 168 | const std::vector& attributes, 169 | const std::string& message, 170 | Cw_t& Cw); 171 | 172 | /** 173 | * @brief Decrypts an attribute-encrypted message. 174 | * 175 | * This is the actual Decryptoon algorithm, but without a HMAC. 176 | */ 177 | std::string decrypt(DecryptionKey& key, 178 | Cw_t& Cw, 179 | const std::vector& attributes, 180 | const std::vector& ciphertext); 181 | 182 | class UnsatError: public std::exception { }; 183 | 184 | #pragma GCC visibility pop 185 | #endif 186 | -------------------------------------------------------------------------------- /kpabe_test.cpp: -------------------------------------------------------------------------------- 1 | #define BOOST_TEST_DYN_LINK 2 | #define BOOST_TEST_MODULE kpabe_test 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | #include "kpabe.hpp" 12 | 13 | using namespace std; 14 | 15 | struct InitPolicy { 16 | Node root; 17 | vector attributes; 18 | 19 | InitPolicy() : root(Node::Type::AND), attributes({1, 2, 3, 4}) { 20 | // (one or two) and (three or four) 21 | vector children1, children2; 22 | for(auto it = attributes.begin(); it != attributes.begin() + attributes.size() / 2; ++it) { 23 | children1.emplace_back(*it); 24 | children2.emplace_back(*(it + 2)); 25 | } 26 | 27 | Node orNodeLeft(Node::Type::OR, children1); 28 | Node orNodeRight(Node::Type::OR, children2); 29 | root.addChild(orNodeLeft); 30 | root.addChild(orNodeRight); 31 | } 32 | }; 33 | 34 | struct InitGenerator: InitPolicy { 35 | PrivateParams priv; 36 | PublicParams pub; 37 | 38 | InitGenerator() : InitPolicy() { 39 | setup({1, 2, 3, 4}, pub, priv); 40 | } 41 | }; 42 | 43 | 44 | BOOST_AUTO_TEST_CASE(hashElement_test) { 45 | element_t el; 46 | element_init_G1(el, getPairing()); 47 | element_random(el); 48 | 49 | uint8_t key[32]; 50 | hashElement(el, key); 51 | //elementToKey(el, key, NULL); 52 | 53 | element_clear(el); 54 | } 55 | 56 | BOOST_FIXTURE_TEST_CASE(getLeafs_test, InitPolicy) { 57 | auto leafs = root.getLeafs(); 58 | for(auto attr: attributes) { 59 | BOOST_CHECK(find(leafs.begin(), leafs.end(), attr) != leafs.end()); 60 | } 61 | } 62 | 63 | BOOST_FIXTURE_TEST_CASE(splitShares_test, InitPolicy) { 64 | 65 | element_t rootSecret; 66 | element_init_Zr(rootSecret, getPairing()); 67 | element_random(rootSecret); 68 | 69 | auto shares = root.splitShares(*rootSecret); 70 | 71 | for(auto& share: shares) { 72 | element_add_ui(&share, &share, 1ul); // Sanity check that the shares are initialized 73 | element_clear(&share); 74 | } 75 | 76 | element_clear(rootSecret); 77 | } 78 | 79 | BOOST_FIXTURE_TEST_CASE(getSecretShares_test, InitPolicy) { 80 | element_t rootSecret; 81 | element_init_Zr(rootSecret, getPairing()); 82 | element_random(rootSecret); 83 | 84 | auto shares = root.getSecretShares(*rootSecret); 85 | 86 | for(auto& share: shares) { 87 | element_add_ui(&share, &share, 1ul); // Sanity check that the shares are initialized 88 | element_clear(&share); 89 | } 90 | 91 | element_clear(rootSecret); 92 | } 93 | 94 | BOOST_FIXTURE_TEST_CASE(recoverCoefficients_test, InitPolicy) { 95 | auto shares = root.recoverCoefficients(); 96 | 97 | for(auto& share: shares) { 98 | element_add_ui(&share, &share, 1ul); // Sanity check that the shares are initialized 99 | element_clear(&share); 100 | } 101 | } 102 | 103 | BOOST_FIXTURE_TEST_CASE(satisfyingAttributes_test, InitPolicy) { 104 | element_t rootCoeff; 105 | element_init_Zr(rootCoeff, getPairing()); 106 | element_set1(rootCoeff); 107 | 108 | vector attr {1, 3}; 109 | vector expected {1, 3}; 110 | auto sat = root.satisfyingAttributes(attr, *rootCoeff); 111 | 112 | BOOST_CHECK(expected.size() == sat.size()); 113 | for(auto& s: sat) { 114 | BOOST_CHECK(find(expected.begin(), expected.end(), s.first) != expected.end()); 115 | element_clear(&s.second); 116 | } 117 | 118 | element_clear(rootCoeff); 119 | } 120 | 121 | BOOST_FIXTURE_TEST_CASE(satisfyingAttributes_negative_test, InitPolicy) { 122 | element_t rootCoeff; 123 | element_init_Zr(rootCoeff, getPairing()); 124 | element_set1(rootCoeff); 125 | 126 | vector attr {1}; 127 | vector expected {}; 128 | auto sat = root.satisfyingAttributes(attr, *rootCoeff); 129 | 130 | BOOST_CHECK(expected.size() == sat.size()); 131 | // Just in case the test fails, clear all elements 132 | for(auto& s: sat) { 133 | const auto& a = s.first; 134 | BOOST_CHECK(find(expected.begin(), expected.end(), a) != expected.end()); 135 | element_clear(&s.second); 136 | } 137 | 138 | element_clear(rootCoeff); 139 | } 140 | 141 | BOOST_AUTO_TEST_CASE(setupTest) { 142 | vector attributes {1, 2, 3}; 143 | PrivateParams priv; 144 | PublicParams pub; 145 | setup(attributes, pub, priv); 146 | } 147 | 148 | BOOST_FIXTURE_TEST_CASE(createSecretTest, InitPolicy) { 149 | vector attrUniverse {1, 2, 3, 4}; 150 | PrivateParams priv; 151 | PublicParams pub; 152 | setup(attributes, pub, priv); 153 | auto key = keyGeneration(priv, root); 154 | vector expectedAttributes {1, 2, 3, 4}; 155 | 156 | BOOST_CHECK(expectedAttributes.size() == key.Di.size()); 157 | for(auto attr: expectedAttributes) { 158 | auto attrDuPairIter = key.Di.find(attr); 159 | BOOST_CHECK(attrDuPairIter != key.Di.end()); 160 | element_clear(&attrDuPairIter->second); 161 | } 162 | } 163 | 164 | BOOST_FIXTURE_TEST_CASE(createSecretAndRecoverSecret, InitGenerator) { 165 | element_s CsEnc, CsDec; 166 | vector encAttr {1, 3}; 167 | auto Cw = createSecret(pub, encAttr, CsEnc); 168 | 169 | auto decKeyPolicy = keyGeneration(priv, root); 170 | recoverSecret(decKeyPolicy, Cw, encAttr, CsDec); 171 | 172 | BOOST_CHECK(!element_cmp(&CsEnc, &CsDec)); 173 | 174 | for(auto& attrCiPair: Cw) { 175 | element_clear(&attrCiPair.second); 176 | } 177 | 178 | for(auto& attrDiPair: decKeyPolicy.Di) { 179 | element_clear(&attrDiPair.second); 180 | } 181 | 182 | element_clear(&CsEnc); 183 | element_clear(&CsDec); 184 | } 185 | 186 | BOOST_FIXTURE_TEST_CASE(encryptAndDecrypt, InitGenerator) { 187 | const string message("Hello World!"); 188 | vector attributes {1}; 189 | 190 | Cw_t Cw; 191 | auto ciphertext = encrypt(pub, attributes, message, Cw); 192 | 193 | Node policy(Node::Type::OR); 194 | policy.addChild(Node(1)); 195 | policy.addChild(Node(2)); 196 | auto key = keyGeneration(priv, policy); 197 | 198 | auto msg = decrypt(key, Cw, attributes, ciphertext); 199 | 200 | for(auto& attrCiPair: Cw) { 201 | element_clear(&attrCiPair.second); 202 | } 203 | 204 | for(auto& attrDiPair: key.Di) { 205 | element_clear(&attrDiPair.second); 206 | } 207 | 208 | BOOST_CHECK(msg == message); 209 | } 210 | 211 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /kpabe.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | #include 11 | #include 12 | #include 13 | 14 | #include "kpabe.hpp" 15 | 16 | using namespace std; 17 | 18 | // For the encrypt/decrypt methods. 19 | static const size_t AES_BLOCK_SIZE = 16; 20 | static const size_t AES_KEY_SIZE = 32; 21 | 22 | pairing_s pairing; 23 | bool isInit = false; 24 | 25 | pairing_ptr getPairing() { 26 | if(!isInit) { 27 | pairing_init_set_str(&pairing, TYPE_A_PARAMS.c_str()); 28 | isInit = true; 29 | } 30 | return &pairing; 31 | } 32 | 33 | void hashElement(element_t e, uint8_t* hashBuf) { 34 | const int elementSize = element_length_in_bytes(e); 35 | uint8_t* elementBytes = new uint8_t[elementSize + 1]; 36 | element_to_bytes(elementBytes, e); 37 | 38 | //TODO: use mbedtls_sha256 39 | auto mdInfo = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256); 40 | mbedtls_md(mdInfo, elementBytes, elementSize, hashBuf); 41 | 42 | delete [] elementBytes; 43 | } 44 | 45 | /** 46 | * Common interface to for symmetric encryption and decryption. 47 | * 48 | * Uses AES-256-CBC and zero-filled IV. 49 | */ 50 | void mbedtlsSymCrypt(const uint8_t* input, size_t ilen, uint8_t* key, uint8_t* output, size_t* olen, mbedtls_operation_t mode) { 51 | const auto cipherInfo = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_CBC); 52 | mbedtls_cipher_context_t ctx; 53 | mbedtls_cipher_setup(&ctx, cipherInfo); 54 | mbedtls_cipher_setkey(&ctx, key, cipherInfo->key_bitlen, mode); 55 | array iv; 56 | iv.fill(0); 57 | mbedtls_cipher_crypt(&ctx, iv.data(), cipherInfo->iv_size, input, ilen, output, olen); 58 | } 59 | 60 | void symEncrypt(const uint8_t* input, size_t ilen, uint8_t* key, uint8_t* output, size_t* olen) { 61 | mbedtlsSymCrypt(input, ilen, key, output, olen, MBEDTLS_ENCRYPT); 62 | } 63 | 64 | void symDecrypt(const uint8_t* input, size_t ilen, uint8_t* key, uint8_t* output, size_t* olen) { 65 | mbedtlsSymCrypt(input, ilen, key, output, olen, MBEDTLS_DECRYPT); 66 | } 67 | 68 | // Node 69 | 70 | Node::Node(const Node& other) { 71 | attr = other.attr; 72 | type = other.type; 73 | children = other.children; 74 | } 75 | 76 | Node::Node(Node&& other): 77 | attr(move(other.attr)), 78 | type(other.type), 79 | children(move(other.children)) { 80 | } 81 | 82 | Node::Node(int attr) { 83 | this->attr = attr; 84 | } 85 | 86 | Node::Node(Type type, const vector& children) { 87 | this->children = children; 88 | this->type = type; 89 | } 90 | 91 | Node& Node::operator=(Node other) { 92 | //TODO: check if not self 93 | swap(attr, other.attr); 94 | swap(type, other.type); 95 | swap(children, other.children); 96 | return *this; 97 | } 98 | 99 | Node& Node::operator=(Node&& other) { 100 | //assert(this != &other); 101 | attr = move(other.attr); 102 | type = move(other.type); 103 | children = move(other.children); 104 | return *this; 105 | } 106 | 107 | void Node::addChild(const Node& node) { 108 | children.push_back(node); 109 | } 110 | 111 | vector Node::getLeafs() const { 112 | vector attrs; 113 | 114 | if(children.empty()) { 115 | // Handles non-leaf node with one child 116 | attrs.push_back(attr); 117 | } else { 118 | for(const Node& child: children) { 119 | if(child.children.empty()) { 120 | attrs.push_back(child.attr); 121 | } else { 122 | auto childAttrs = child.getLeafs(); 123 | attrs.reserve(attrs.size() + childAttrs.size()); 124 | attrs.insert(attrs.end(), childAttrs.begin(), childAttrs.end()); 125 | } 126 | } 127 | } 128 | return attrs; 129 | } 130 | 131 | unsigned int Node::getThreshold() const { 132 | return type == Type::OR ? 1 : static_cast(children.size()); 133 | } 134 | 135 | unsigned int Node::getPolyDegree() const { 136 | return getThreshold() - 1; 137 | } 138 | 139 | vector Node::splitShares(element_s& rootSecret) { 140 | // Generate the coefficients for the polynomial. 141 | auto threshold = getThreshold(); 142 | vector coeff(threshold); 143 | 144 | element_init_same_as(&coeff[0], &rootSecret); 145 | element_set(&coeff[0], &rootSecret); 146 | 147 | // Generate random coefficients, except for q(0), which is set to the rootSecret. 148 | for(int i = 1; i <= getPolyDegree(); ++i) { 149 | element_init_same_as(&coeff[i], &rootSecret); 150 | element_random(&coeff[i]); 151 | } 152 | 153 | // Calculate the shares for each child. 154 | vector shares(children.size()); 155 | 156 | element_t temp; 157 | element_init_Zr(temp, getPairing()); 158 | 159 | // The scheme decription defines an ordering on the children in a node (index(x)). 160 | // Here, we implicitly use a left to right order. 161 | for(int x = 1; x <= children.size(); ++x) { 162 | auto share = &shares[x - 1]; 163 | element_init_same_as(share, &rootSecret); 164 | element_set0(share); 165 | // share = coeff[0] + coeff[1] * x + ... + coeff[threshold - 1] * x ^ (threshold - 1) 166 | for(int power = 0; power < coeff.size(); ++power) { 167 | element_set_si(temp, pow(x, power)); //TODO: handle pow 168 | element_mul(temp, temp, &coeff[power]); 169 | element_add(share, share, temp); 170 | } 171 | } 172 | 173 | element_clear(temp); 174 | for(element_s& c: coeff) { 175 | element_clear(&c); 176 | } 177 | 178 | return shares; 179 | }//splitShares 180 | 181 | vector Node::getSecretShares(element_s& rootSecret) { 182 | vector shares; 183 | if(children.empty()) { 184 | shares.push_back(rootSecret); 185 | } else { 186 | auto childSplits = splitShares(rootSecret); 187 | auto childSplitsIter = childSplits.begin(); 188 | for(Node& child: children) { 189 | auto childShares = child.getSecretShares(*childSplitsIter++); 190 | shares.reserve(shares.size() + childShares.size()); 191 | shares.insert(shares.end(), childShares.begin(), childShares.end()); 192 | } 193 | } 194 | 195 | return shares; 196 | } 197 | 198 | vector Node::recoverCoefficients() { 199 | auto threshold = getThreshold(); 200 | vector coeff(threshold); 201 | 202 | element_t iVal, jVal, temp; 203 | element_init_Zr(iVal, getPairing()); 204 | element_init_Zr(jVal, getPairing()); 205 | element_init_Zr(temp, getPairing()); 206 | 207 | for(int i = 1; i <= threshold; ++i) { 208 | element_set_si(iVal, i); 209 | element_s& result = coeff[i - 1]; 210 | element_init_Zr(&result, getPairing()); 211 | element_set1(&result); 212 | for(int j = 1; j <= threshold; ++j) { 213 | if(i == j) { 214 | continue; 215 | } 216 | // result *= (0 - j) / (i - j) 217 | element_set_si(jVal, -j); 218 | element_add(temp, iVal, jVal); 219 | element_div(temp, jVal, temp); 220 | element_mul(&result, &result, temp); 221 | } 222 | } 223 | 224 | element_clear(iVal); 225 | element_clear(jVal); 226 | element_clear(temp); 227 | 228 | return coeff; 229 | } 230 | 231 | 232 | vector< pair > 233 | Node::satisfyingAttributes(const vector& attributes, 234 | element_s& currentCoeff) { 235 | vector< pair > sat; 236 | 237 | if (children.empty()) { 238 | if(find(attributes.begin(), attributes.end(), attr) != attributes.end()) { 239 | sat.push_back({attr, currentCoeff}); 240 | } 241 | } else { 242 | auto recCoeffs = recoverCoefficients(); 243 | 244 | if(type == Type::AND) { 245 | bool allSatisfied = true; 246 | vector< pair > totalChildSat; 247 | for(int i = 0; i < children.size(); ++i) { 248 | element_mul(&recCoeffs[i], &recCoeffs[i], ¤tCoeff); 249 | auto childSat = children[i].satisfyingAttributes(attributes, recCoeffs[i]); 250 | if(childSat.empty()) { 251 | allSatisfied = false; 252 | break; 253 | } 254 | totalChildSat.reserve(totalChildSat.size() + childSat.size()); 255 | totalChildSat.insert(totalChildSat.end(), childSat.begin(), childSat.end()); 256 | } 257 | if(allSatisfied) { 258 | sat = totalChildSat; 259 | } 260 | } else { 261 | auto& recCoeff0 = recCoeffs[0]; 262 | element_mul(&recCoeff0, &recCoeff0, ¤tCoeff); 263 | for (auto& child: children) { 264 | // TODO: Optimization - 265 | // Should return the shortest non-empty childSat instead of the first one. 266 | auto childSat = child.satisfyingAttributes(attributes, recCoeff0); 267 | if(!childSat.empty()){ 268 | sat = childSat; 269 | break; 270 | } 271 | } 272 | } 273 | } 274 | 275 | return sat; 276 | } 277 | 278 | const vector& Node::getChildren() const { 279 | return children; 280 | } 281 | 282 | // DecryptionKey 283 | 284 | DecryptionKey::DecryptionKey(const Node& policy): accessPolicy(policy) { } 285 | 286 | // Algorithm Setup 287 | 288 | void setup(const vector& attributes, 289 | PublicParams& publicParams, 290 | PrivateParams& privateParams) { 291 | element_init_Zr(&privateParams.mk, getPairing()); 292 | element_random(&privateParams.mk); 293 | 294 | element_t g; 295 | element_init_G1(g, getPairing()); 296 | element_random(g); 297 | 298 | // Generate a random public and private element for each attribute 299 | for(auto attr: attributes) { 300 | // private 301 | element_s& si = privateParams.Si[attr]; 302 | element_init_Zr(&si, getPairing()); 303 | element_random(&si); 304 | 305 | // public 306 | element_s& Pi = publicParams.Pi[attr]; 307 | element_init_G1(&Pi, getPairing()); 308 | element_pow_zn(&Pi, g, &si); 309 | } 310 | 311 | element_init_G1(&publicParams.pk, getPairing()); 312 | element_pow_zn(&publicParams.pk, g, &privateParams.mk); 313 | element_clear(g); 314 | } 315 | 316 | /** 317 | * @brief An abstraction of createKey that allows different operation for hiding the 318 | * secret shares. 319 | * 320 | * @param scramblingFunc A function that sets an element to the result of a function on 321 | * a scambling key and a secret share. In the original paper the scrambling keys are 322 | * the private keys and the function is division. The result of the scrambling is put 323 | * in the first element, the shares in the second, the scramblng keys in the third. 324 | * @type scramblingFunc function 325 | */ 326 | DecryptionKey _keyGeneration(element_s& rootSecret, 327 | map& scramblingKeys, 328 | function scramblingFunc, 329 | Node& accessPolicy) { 330 | auto leafs = accessPolicy.getLeafs(); 331 | auto shares = accessPolicy.getSecretShares(rootSecret); 332 | 333 | DecryptionKey key(accessPolicy); 334 | auto attrIter = leafs.begin(); 335 | auto sharesIter = shares.begin(); 336 | // The below is: Du[attr] = shares[attr] / attributeSecrets[attr] 337 | for(; attrIter != leafs.end(); ++attrIter, ++sharesIter) { 338 | element_s& attrDi = key.Di[*attrIter]; 339 | element_init_Zr(&attrDi, getPairing()); 340 | scramblingFunc(&attrDi, &*sharesIter, &scramblingKeys[*attrIter]); 341 | } 342 | 343 | for(element_s& share: shares) { 344 | element_clear(&share); 345 | } 346 | 347 | return key; 348 | } 349 | 350 | 351 | DecryptionKey keyGeneration(PrivateParams& privateParams, 352 | Node& accessPolicy) { 353 | return _keyGeneration(privateParams.mk, privateParams.Si, element_div, accessPolicy); 354 | } 355 | 356 | Cw_t createSecret(PublicParams& params, 357 | const vector& attributes, 358 | element_s& Cs) { 359 | element_t k; 360 | element_init_Zr(k, getPairing()); 361 | element_random(k); 362 | 363 | element_init_G1(&Cs, getPairing()); 364 | element_pow_zn(&Cs, ¶ms.pk, k); 365 | 366 | Cw_t Cw; 367 | for(auto attr: attributes) { 368 | element_s& i = Cw[attr]; 369 | element_init_G1(&i, getPairing()); 370 | element_pow_zn(&i, ¶ms.Pi[attr], k); 371 | } 372 | element_clear(k); 373 | 374 | return Cw; 375 | } 376 | 377 | void recoverSecret(DecryptionKey& key, 378 | Cw_t& Cw, 379 | const vector& attributes, 380 | element_s& Cs) { 381 | // Get attributes that can satisfy the policy (and their coefficients). 382 | element_t rootCoeff; 383 | element_init_Zr(rootCoeff, getPairing()); 384 | element_set1(rootCoeff); 385 | auto attrs = key.accessPolicy.satisfyingAttributes(attributes, *rootCoeff); 386 | element_clear(rootCoeff); 387 | 388 | if(attrs.empty()) { 389 | throw UnsatError(); 390 | return; 391 | } 392 | 393 | element_t Zy; 394 | element_init_G1(&Cs, getPairing()); 395 | element_init_G1(Zy, getPairing()); 396 | bool pastFirst = false; // Is this the first "part" of the product 397 | 398 | // product = P(Ci ^ (Di * coeff(i))) 399 | // NOTE: attrCoeffPair is modified 400 | for(auto& attrCoeffPair: attrs) { 401 | element_mul(&attrCoeffPair.second, &key.Di[attrCoeffPair.first], &attrCoeffPair.second); 402 | element_pow_zn(Zy, &Cw[attrCoeffPair.first], &attrCoeffPair.second); 403 | 404 | if (pastFirst) { 405 | element_mul(&Cs, &Cs, Zy); 406 | } else { 407 | pastFirst = true; 408 | element_set(&Cs, Zy); 409 | } 410 | } 411 | 412 | for(auto& attrCoeffPair: attrs){ 413 | element_clear(&attrCoeffPair.second); 414 | } 415 | element_clear(Zy); 416 | } 417 | 418 | std::vector encrypt(PublicParams& params, 419 | const vector& attributes, 420 | const string& message, 421 | Cw_t& Cw) { 422 | element_s Cs; 423 | Cw = createSecret(params, attributes, Cs); 424 | 425 | // Use the key to encrypt the data using a symmetric cipher. 426 | size_t messageLen = message.size() + 1; // account for terminating byte 427 | size_t cipherMaxLen = messageLen + AES_BLOCK_SIZE; 428 | vector ciphertext(cipherMaxLen); 429 | 430 | array key; 431 | hashElement(&Cs, key.data()); 432 | size_t clength = 0; 433 | symEncrypt((uint8_t*) message.c_str(), messageLen, key.data(), ciphertext.data(), &clength); 434 | ciphertext.resize(clength); 435 | 436 | element_clear(&Cs); 437 | 438 | return ciphertext; 439 | } 440 | 441 | string decrypt(DecryptionKey& key, 442 | Cw_t& Cw, 443 | const vector& attributes, 444 | const vector& ciphertext) { 445 | element_s Cs; 446 | recoverSecret(key, Cw, attributes, Cs); 447 | vector plaintext(ciphertext.size()); 448 | size_t plaintextLen = 0; 449 | 450 | array symKey; 451 | hashElement(&Cs, symKey.data()); 452 | symDecrypt(ciphertext.data(), ciphertext.size(), symKey.data(), plaintext.data(), &plaintextLen); 453 | plaintext.resize(plaintextLen); 454 | string message((char*) plaintext.data()); 455 | 456 | element_clear(&Cs); 457 | 458 | return message; 459 | } 460 | --------------------------------------------------------------------------------