Unverified Commit c2abb08c authored by Oleh Nikolaiev's avatar Oleh Nikolaiev Committed by GitHub

Merge pull request #5 from skalenetwork/enhancement/SKALE-1512-add-DKG-to-SGX

Enhancement/skale 1512 add dkg to sgx
parents 5e8794fb de5752ae
......@@ -83,7 +83,31 @@ bool hex2carray(const char * _hex, uint64_t *_bin_len,
}
bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length ) {
int len = strnlen(_hex, _max_length);//2 * BUF_LEN);
if (len == 0 && len % 2 == 1)
return false;
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) {
int high = char2int((char)_hex[i * 2]);
int low = char2int((char)_hex[i * 2 + 1]);
if (high < 0 || low < 0) {
return false;
}
_bin[i] = (unsigned char) (high * 16 + low);
}
return true;
}
bool sign(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t _n, size_t _signerIndex,
......@@ -97,15 +121,27 @@ bool sign(const char* _encryptedKeyHex, const char* _hashHex, size_t _t, size_t
uint64_t binLen;
hex2carray(_hashHex, &binLen, hash->data());
// assert(binLen == hash->size());
auto keyShare = std::make_shared<BLSPrivateKeyShareSGX>(keyStr, _t, _n);
// {
auto sigShare = keyShare->signWithHelperSGX(hash, _signerIndex);
// }
auto sigShareStr = sigShare->toString();
strncpy(_sig, sigShareStr->c_str(), BUF_LEN);
//std::string sigShareStr = keyShare->signWithHelperSGXstr(hash, _signerIndex);
//strncpy(_sig, sigShareStr.c_str(), BUF_LEN);
// std::string test_sig = "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855:9810286616503120081238481858289626967170509983220853777870754480048381194141:5";
// auto sig_ptr = std::make_shared<std::string>(test_sig);
// strncpy(_sig, sig_ptr->c_str(), BUF_LEN);
std::cerr<< "sig " << _sig <<std::endl;
return true;
}
......
......@@ -26,6 +26,8 @@ EXTERNC int char2int(char _input);
EXTERNC void carray2Hex(const unsigned char *d, int _len, char* _hexArray);
EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin );
EXTERNC bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length );
......
......@@ -99,7 +99,7 @@ BLSPrivateKeyShareSGX::BLSPrivateKeyShareSGX(
encryptedKeyHex = _encryptedKeyHex;
}
std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::string BLSPrivateKeyShareSGX::signWithHelperSGXstr(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex) {
shared_ptr<signatures::Bls> obj;
......@@ -133,8 +133,6 @@ std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
}
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
......@@ -165,6 +163,10 @@ std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
bls_sign_message(eid, &errStatus, errMsg, encryptedKey,
encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
// strncpy(signature, "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855", 1024);
printf("---: %s\n", signature);
if (status != SGX_SUCCESS) {
gmp_printf("SGX enclave call to bls_sign_message failed: 0x%04x\n", status);
......@@ -186,15 +188,130 @@ std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second;
std::string sig = signature;
sig.append(":");
sig.append(hint);
return sig;
}
std::shared_ptr<BLSSigShare> BLSPrivateKeyShareSGX::signWithHelperSGX(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex) {
/* shared_ptr<signatures::Bls> obj;
if (_signerIndex == 0) {
BOOST_THROW_EXCEPTION(runtime_error("Zero signer index"));
}
if (hash_byte_arr == nullptr) {
BOOST_THROW_EXCEPTION(runtime_error("Hash is null"));
}
obj = make_shared<signatures::Bls>(
signatures::Bls(requiredSigners, totalSigners));
std::pair<libff::alt_bn128_G1, std::string> hash_with_hint =
obj->HashtoG1withHint(hash_byte_arr);
int errStatus = 0;
string* xStr = stringFromFq(&(hash_with_hint.first.X));
if (xStr == nullptr) {
BOOST_THROW_EXCEPTION(runtime_error("Null xStr"));
}
string* yStr = stringFromFq(&(hash_with_hint.first.Y));
if (xStr == nullptr) {
BOOST_THROW_EXCEPTION(runtime_error("Null yStr"));
}
char errMsg[BUF_LEN];
memset(errMsg, 0, BUF_LEN);
char xStrArg[BUF_LEN];
char yStrArg[BUF_LEN];
char signature [BUF_LEN];
memset(xStrArg, 0, BUF_LEN);
memset(yStrArg, 0, BUF_LEN);
strncpy(xStrArg, xStr->c_str(), BUF_LEN);
strncpy(yStrArg, yStr->c_str(), BUF_LEN);
size_t sz = 0;
uint8_t encryptedKey[BUF_LEN];
bool result = hex2carray(encryptedKeyHex->c_str(), &sz, encryptedKey);
if (!result) {
BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid hex encrypted key"));
}
cerr << "Key is " + *encryptedKeyHex << endl;
// sgx_status_t status =
// bls_sign_message(eid, &errStatus, errMsg, encryptedKey,
// encryptedKeyHex->size() / 2, xStrArg, yStrArg, signature);
strncpy(signature, "8175162913343900215959836578795929492705714455632345516427532159927644835012:15265825550804683171644566522808807137117748565649051208189914766494241035855", 1024);
printf("---: %s\n", signature);
// if (status != SGX_SUCCESS) {
// gmp_printf("SGX enclave call to bls_sign_message failed: 0x%04x\n", status);
// BOOST_THROW_EXCEPTION(runtime_error("SGX enclave call to bls_sign_message failed"));
// }
// if (errStatus != 0) {
// BOOST_THROW_EXCEPTION(runtime_error("Enclave bls_sign_message failed:" + to_string(errStatus) + ":" + errMsg ));
// return nullptr;
// }
int sigLen;
if ((sigLen = strnlen(signature, 10)) < 10) {
BOOST_THROW_EXCEPTION(runtime_error("Signature too short:" + to_string(sigLen)));
}
std::string hint = BLSutils::ConvertToString(hash_with_hint.first.Y) + ":" +
hash_with_hint.second;
auto sig = make_shared<string>(signature);
sig->append(":");
sig->append(hint);
sig->append(hint);*/
std::string signature = signWithHelperSGXstr(hash_byte_arr, _signerIndex);
auto sig = make_shared<string>(signature);
//BLSSigShare* sig_test = new BLSSigShare(sig, _signerIndex, requiredSigners, totalSigners);
//std::string hello = "hello";
//std::cout << "HINT " << *((void**)&(sig_test->hint)) << std::endl;
//std::shared_ptr<BLSSigShare> s; s.reset( sig_test );//(sig, _signerIndex, requiredSigners,
//totalSigners);
auto s = make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners,
std::shared_ptr<BLSSigShare> s = std::make_shared<BLSSigShare>(sig, _signerIndex, requiredSigners,
totalSigners);
return s;
......
......@@ -41,8 +41,14 @@ public:
signWithHelperSGX(std::shared_ptr<std::array<uint8_t, 32>> _hash,
size_t _signerIndex);
std::string signWithHelperSGXstr(
std::shared_ptr<std::array<uint8_t, 32>> hash_byte_arr,
size_t _signerIndex);
BLSPrivateKeyShareSGX(std::shared_ptr<std::string> _encryptedKeyHex,
size_t _requiredSigners, size_t _totalSigners);
};
#endif // LIBBLS_BLSPRIVATEKEYSHARE_H
//
// Created by kladko on 10/3/19.
//
#include "DKGCrypto.h"
#include "BLSCrypto.h"
#include "sgxwallet.h"
#include <iostream>
#include <memory>
#include "SGXWalletServer.hpp"
std::vector<std::string> SplitString(const char* koefs, const char symbol){
std::string str(koefs);
std::string delim;
delim.push_back(symbol);
std::vector<std::string> G2_strings;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (!token.empty()) {
std::string koef(token.c_str());
G2_strings.push_back(koef);
}
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return G2_strings;
}
std::string gen_dkg_poly( int _t){
char *errMsg = (char *)calloc(1024, 1);
int err_status = 0;
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);;
uint32_t enc_len = 0;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, _t);
std::cerr << "gen_dkg_secret, status " << err_status << " err msg " << errMsg << std::endl;
/* std::cerr << "encr raw poly: " << std::endl;
for ( int i = 0 ; i < 3050; i++)
printf(" %d ", encrypted_dkg_secret[i] );*/
char *hexEncrPoly = (char *) calloc(DKG_MAX_SEALED_LEN * 2 + 1, 1);//(4*BUF_LEN, 1);
carray2Hex(encrypted_dkg_secret, DKG_MAX_SEALED_LEN, hexEncrPoly);
std::string result(hexEncrPoly);
std::cerr << "in DKGCrypto encr len is " << enc_len << std::endl;
free(errMsg);
free(encrypted_dkg_secret);
free(hexEncrPoly);
return result;
}
std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyHex, int n, int t){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
// std::cerr << "got encr poly " << encryptedPolyHex << std::endl;
std::cerr << "got encr poly size " << strlen(encryptedPolyHex) << std::endl;
char* public_shares = (char*)calloc(10000, 1);
uint64_t enc_len = 0;
uint8_t* encr_dkg_poly = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
hex2carray2(encryptedPolyHex, &enc_len, encr_dkg_poly, 6100);
std::cerr << "enc len " << enc_len << std::endl;
/*std::cerr << "encr raw poly: " << std::endl;
for ( int i = 0 ; i < 3050; i++)
printf(" %d ", encr_dkg_poly[i] );*/
uint32_t len;
status = get_public_shares(eid, &err_status, errMsg1, encr_dkg_poly, len, public_shares, t, n);
std::cerr << "err msg " << errMsg1 << std::endl;
std::cerr << "public_shares:" << std::endl;
std::cerr << public_shares << std::endl;
printf("\nget_public_shares status: %d error %s \n\n", err_status, errMsg1);
std::vector <std::string> G2_strings = SplitString( public_shares, ',');
std::vector <std::vector <std::string>> pub_shares_vect;
for ( int i = 0; i < G2_strings.size(); i++){
std::vector <std::string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
pub_shares_vect.push_back(koef_str);
}
free(errMsg1);
free(public_shares);
free(encr_dkg_poly);
return pub_shares_vect;
}
std::string get_secret_shares(const std::string& polyName, const char* encryptedPolyHex, const std::string& publicKeys, int n, int t){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
uint64_t enc_len = 0;
uint8_t* encr_dkg_poly = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
hex2carray2(encryptedPolyHex, &enc_len, encr_dkg_poly, 6100);
status = set_encrypted_dkg_poly(eid, &err_status, errMsg1, encr_dkg_poly);
std::string result;
char *hexEncrKey = (char *) calloc(2 * BUF_LEN, 1);
for ( int i = 0; i < n; i++){
uint8_t encrypted_skey[BUF_LEN];
uint32_t dec_len;
char cur_share[193];
std::string pub_keyB = publicKeys.substr(64*i, 64*i + 128);
char pubKeyB[129];
strncpy(pubKeyB, pub_keyB.c_str(),129);
get_encr_sshare(eid, &err_status, errMsg1, encrypted_skey, &dec_len,
cur_share, pubKeyB, t, n, i + 1 );
result += cur_share;
uint32_t enc_len = BUF_LEN;
carray2Hex(encrypted_skey, enc_len, hexEncrKey);
//std::cerr << "hexEncrKey: " << hexEncrKey << std::endl;
std::string name = "DKG_DH_KEY_" + polyName + "_" + std::to_string(i) + ":";
//writeDataToDB(name, hexEncrKey);
//std::cerr << errMsg1 << std::endl << std::endl;
//std::cerr << "iteration " << i <<" result length is " << result.length() << std::endl ;
//std::cerr << "iteration " << i <<" share length is " << strlen(cur_share) << std::endl;
//std::cerr << "iteration " << i <<" share is " << cur_share << std::endl;
}
//result += '\0';
free(encr_dkg_poly);
free(errMsg1);
free(hexEncrKey);
return result;
}
bool VerifyShares(const char* encryptedPolyHex, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind ){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
uint64_t poly_len = 0;
uint8_t* encr_dkg_poly = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
hex2carray2(encryptedPolyHex, &poly_len, encr_dkg_poly, 6100);
uint64_t dec_key_len ;
uint8_t encr_key[BUF_LEN];
hex2carray(encryptedKeyHex, &dec_key_len, encr_key);
//std::cerr << "encryptedKeyHex " << encryptedKeyHex << std::endl;
//std::cerr << "dec_key_len " << dec_key_len << std::endl;
int result ;
dkg_verification(eid, &err_status, errMsg1, encr_dkg_poly, encr_sshare, encr_key, dec_key_len, t, ind, &result);
std::cerr << "errMsg1: " << errMsg1 << std::endl;
free(errMsg1);
free(encr_dkg_poly);
std::cerr << "result is " << result << std::endl;
return result;
}
bool CreateBLSShare( const char * s_shares, const char * encryptedKeyHex){
char* errMsg1 = (char*) calloc(1024,1);
int err_status = 0;
uint64_t dec_key_len ;
uint8_t encr_bls_key[BUF_LEN];
uint8_t encr_key[BUF_LEN];
hex2carray(encryptedKeyHex, &dec_key_len, encr_key);
create_bls_key(eid, &err_status, errMsg1, s_shares, encr_key, dec_key_len, encr_bls_key);
if ( err_status != 0){
return false;
}
else return true;
}
\ No newline at end of file
//
// Created by kladko on 10/3/19.
//
#ifndef SGXD_DKGCRYPTO_H
#define SGXD_DKGCRYPTO_H
#include <string>
#include <vector>
std::string gen_dkg_poly( int _t);
std::vector <std::vector<std::string>> get_verif_vect(const char* encryptedPolyHex, int n, int t);
std::vector<std::string> SplitString(const char* koefs, const char symbol);
std::string get_secret_shares(const std::string& polyName, const char* encryptedPolyHex, const std::string& publicKeys, int n, int t);
bool VerifyShares(const char* encryptedPolyHex, const char* encr_sshare, const char * encryptedKeyHex, int t, int n, int ind);
bool CreateBLSShare( const char * s_shares, const char * encryptedKeyHex);
#endif //SGXD_DKGCRYPTO_H
......@@ -41,9 +41,9 @@ secure_enclave.edl: secure_enclave/secure_enclave.edl
## Additional automake variables
##
## AM_CPPFLAGS +=
## AM_CFLAGS =
## AM_CXXFLAGS =
#AM_CPPFLAGS += -g -Og
#AM_CFLAGS = -g -Og
#AM_CXXFLAGS = ${AM_CPPFLAGS}
AM_CPPFLAGS += -Wall -DSKALE_SGX=1 -DBINARY_OUTPUT=1 -Ileveldb/include -IlibBLS/bls -IlibBLS/libff -IlibBLS -fno-builtin-memset $(GMP_CPPFLAGS) -I.
......@@ -65,7 +65,8 @@ bin_PROGRAMS = sgxwallet testw
COMMON_SRC = sgx_stub.c sgx_detect_linux.c create_enclave.c oc_alloc.c
COMMON_ENCLAVE_SRC = secure_enclave_u.c secure_enclave_u.h
sgxwallet_SOURCES = sgxwallet.c SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ECDSACrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp $(COMMON_SRC)
sgxwallet_SOURCES = sgxwallet.c SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ECDSACrypto.cpp \
DKGCrypto.cpp ServerInit.cpp BLSPrivateKeyShareSGX.cpp LevelDB.cpp $(COMMON_SRC)
nodist_sgxwallet_SOURCES = $(COMMON_ENCLAVE_SRC)
......@@ -91,13 +92,13 @@ secure_enclave.signed.so: secure_enclave/secure_enclave.signed.so
sgxwallet_LDADD=-l$(SGX_URTS_LIB) -Lleveldb/build -LlibBLS/build -LlibBLS/build/libff/libff -l:libbls.a -l:libleveldb.a \
-l:libff.a -lgmp -ldl -l:libsgx_capable.a -l:libsgx_tprotected_fs.a -ljsonrpccpp-stub -lpthread -ljsonrpccpp-common \
-ljsonrpccpp-server -ljsonrpccpp-client -ljsoncpp -lcurl -lprocps intel-sgx-ssl/Linux/package/lib64/libsgx_usgxssl.a
-ljsonrpccpp-server -ljsonrpccpp-client -ljsoncpp -lcurl -lprocps intel-sgx-ssl/Linux/package/lib64/libsgx_usgxssl.a \
intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a
testw_SOURCES=testw.cpp stubclient.cpp SGXWalletServer.cpp RPCException.cpp BLSCrypto.cpp ServerInit.cpp LevelDB.cpp \
BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp $(COMMON_SRC)
DKGCrypto.cpp BLSPrivateKeyShareSGX.cpp ECDSACrypto.cpp $(COMMON_SRC)
nodist_testw_SOURCES=${nodist_sgxwallet_SOURCES}
EXTRA_testw_DEPENDENCIES=${EXTRA_sgxwallet_DEPENDENCIES}
testw_LDADD= ${sgxwallet_LDADD}
......@@ -24,6 +24,8 @@
#include "LevelDB.h"
#include "BLSCrypto.h"
#include "ECDSACrypto.h"
#include "DKGCrypto.h"
#include "SGXWalletServer.h"
#include "SGXWalletServer.hpp"
......@@ -35,6 +37,7 @@ SGXWalletServer::SGXWalletServer(AbstractServerConnector &connector,
HttpServer *hs = nullptr;
int init_server() {
hs = new HttpServer(1025);
s = new SGXWalletServer(*hs,
JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
......@@ -82,7 +85,7 @@ importBLSKeyShareImpl(int index, const std::string &_keyShare, const std::string
return result;
}
Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::string &messageHash) {
Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::string &messageHash,int n, int t, int signerIndex) {
Json::Value result;
result["status"] = -1;
result["errorMessage"] = "Unknown server error";
......@@ -113,7 +116,7 @@ Json::Value blsSignMessageHashImpl(const std::string &keyShareName, const std::s
}
try {
if (!sign(value->c_str(), messageHash.c_str(), 2, 2, 1, signature)) {
if (!sign(value->c_str(), messageHash.c_str(), t, n, signerIndex, signature)) {
result["status"] = -1;
result["errorMessage"] = "Could not sign";
return result;
......@@ -232,43 +235,235 @@ Json::Value getPublicECDSAKeyImpl(const std::string& keyName){
std::cerr << "PublicKey" << Pkey << std::endl;
result["PublicKey"] = Pkey;
//std::cerr << "in SGXWalletServer encr key x " << keys.at(0) << std::endl;
return result;
}
Json::Value generateDKGPolyImpl(const std::string& polyName, int t) {
std::cerr << " enter generateDKGPolyImpl" << std::endl;
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
//result["encryptedPoly"] = "";
std::string encrPolyHex;
try {
encrPolyHex = gen_dkg_poly(t);
writeDKGPoly(polyName, encrPolyHex);
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
//result["encryptedPoly"] = encrPolyHex;
return result;
}
Json::Value getVerificationVectorImpl(const std::string& polyName, int n, int t) {
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
std::vector <std::vector<std::string>> verifVector;
try {
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName, "DKGPoly:");
verifVector = get_verif_vect(encr_poly_ptr->c_str(), n, t);
std::cerr << "verif vect size " << verifVector.size() << std::endl;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["Verification Vector"] = "";
}
for ( int i = 0; i < t; i++){
std::vector<std::string> cur_coef = verifVector.at(i);
string num = std::to_string(i);
result["Verification Vector"][i][num]["X"]["c0"] = cur_coef.at(0);
result["Verification Vector"][i][num]["X"]["c1"] = cur_coef.at(1);
result["Verification Vector"][i][num]["Y"]["c0"] = cur_coef.at(2);
result["Verification Vector"][i][num]["Y"]["c1"] = cur_coef.at(3);
}
return result;
}
Json::Value getSecretShareImpl(const std::string& polyName, const std::string& publicKeys, int n, int t){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
std::shared_ptr<std::string> encr_poly_ptr = readFromDb(polyName, "DKGPoly:");
std::string s = get_secret_shares(polyName, encr_poly_ptr->c_str(), publicKeys, n, t);
//std::cerr << "result is " << s << std::endl;
result["SecretShare"] = s;
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["SecretShare"] = "";
}
return result;
}
Json::Value DKGVerificationImpl(const std::string& polyName, const std::string& EthKeyName,
const std::string& SecretShare, int t, int n, int ind){
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
result["result"] = true;
try {
std::shared_ptr<std::string> encryptedPolyHex_ptr = readFromDb(polyName, "DKGPoly:");
//std::string keyName = polyName + "_" + std::to_string(ind);
//std::shared_ptr<std::string> encryptedKeyHex_ptr = readFromDb(EthKeyName, "");
std::shared_ptr<std::string> encryptedKeyHex_ptr = readECDSAKey(EthKeyName);
if ( !VerifyShares(encryptedPolyHex_ptr->c_str(), SecretShare.c_str(), encryptedKeyHex_ptr->c_str(), t, n, ind )){
result["result"] = false;
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
result["result"] = false;
}
return result;
}
Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::string& EthKeyName, const Json::Value& SecretShare, int t, int n){
std::cerr << "CreateBLSPrivateKeyImpl entered" << std::endl;
Json::Value result;
result["status"] = 0;
result["errorMessage"] = "";
try {
if (SecretShare.size() != n){
result["errorMessage"] = "wrong number of secret shares";
return result;
}
std::vector<std::string> sshares_vect;
std::cerr << "sshares are " << std::endl;
char sshares[192 * n + 1];
for ( int i = 0; i < n ; i++){
sshares_vect.push_back(SecretShare[i].asString());
// std::cerr << sshares_vect[i] << " ";
strncpy(sshares + i * 192, SecretShare[i].asString().c_str(), 192);
}
sshares[192 * n ] = 0;
std::cerr << sshares << std::endl;
std::cerr << "length is " << strlen(sshares);
std::shared_ptr<std::string> encryptedKeyHex_ptr = readECDSAKey(EthKeyName);
bool res = CreateBLSShare(sshares, encryptedKeyHex_ptr->c_str());
if ( res){
std::cerr << "key created " << std::endl;
}
else {
std::cerr << "error " << std::endl;
}
} catch (RPCException &_e) {
std::cerr << " err str " << _e.errString << std::endl;
result["status"] = _e.status;
result["errorMessage"] = _e.errString;
}
return result;
}
Json::Value SGXWalletServer::generateDKGPoly(const std::string& polyName, int t){
lock_guard<recursive_mutex> lock(m);
return generateDKGPolyImpl(polyName, t);
}
Json::Value SGXWalletServer::getVerificationVector(const std::string& polyName, int n, int t){
lock_guard<recursive_mutex> lock(m);
return getVerificationVectorImpl(polyName, n, t);
}
Json::Value SGXWalletServer::getSecretShare(const std::string& polyName, const std::string& publicKeys, int n, int t){
lock_guard<recursive_mutex> lock(m);
return getSecretShareImpl(polyName, publicKeys, n, t);
}
Json::Value SGXWalletServer::DKGVerification( const std::string& polyName, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index){
lock_guard<recursive_mutex> lock(m);
return DKGVerificationImpl(polyName, EthKeyName, SecretShare, t, n, index);
}
Json::Value SGXWalletServer::CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const Json::Value& SecretShare, int t, int n){
lock_guard<recursive_mutex> lock(m);
return CreateBLSPrivateKeyImpl(BLSKeyName, EthKeyName, SecretShare, t, n);
}
Json::Value SGXWalletServer::generateECDSAKey(const std::string &_keyName) {
lock_guard<recursive_mutex> lock(m);
return generateECDSAKeyImpl(_keyName);
}
Json::Value SGXWalletServer::getPublicECDSAKey(const std::string &_keyName) {
lock_guard<recursive_mutex> lock(m);
return getPublicECDSAKeyImpl(_keyName);
}
Json::Value SGXWalletServer::ecdsaSignMessageHash(int base, const std::string &_keyName, const std::string &messageHash ) {
lock_guard<recursive_mutex> lock(m);
std::cerr << "entered ecdsaSignMessageHash" << std::endl;
std::cerr << "MessageHash first " << messageHash << std::endl;
return ecdsaSignMessageHashImpl(base,_keyName, messageHash);
}
Json::Value
SGXWalletServer::importBLSKeyShare(int index, const std::string &_keyShare, const std::string &_keyShareName, int n,
int t) {
lock_guard<recursive_mutex> lock(m);
return importBLSKeyShareImpl(index, _keyShare, _keyShareName, n, t);
}
Json::Value SGXWalletServer::blsSignMessageHash(const std::string &keyShareName, const std::string &messageHash) {
return blsSignMessageHashImpl(keyShareName, messageHash);
Json::Value SGXWalletServer::blsSignMessageHash(const std::string &keyShareName, const std::string &messageHash,int n,
int t, int signerIndex) {
lock_guard<recursive_mutex> lock(m);
return blsSignMessageHashImpl(keyShareName, messageHash, n,t, signerIndex);
}
Json::Value SGXWalletServer::importECDSAKey(const std::string &key, const std::string &keyName) {
lock_guard<recursive_mutex> lock(m);
return importECDSAKeyImpl(key, keyName);
}
shared_ptr<string> readFromDb(const string & name, const string & prefix) {
auto dataStr = levelDb->readString(prefix + name);
if (dataStr == nullptr) {
throw RPCException(KEY_SHARE_DOES_NOT_EXIST, "Data with this name does not exists");
}
return dataStr;
}
shared_ptr<string> readKeyShare(const string &_keyShareName) {
auto keyShareStr = levelDb->readString("BLSKEYSHARE:" + _keyShareName);
......@@ -296,7 +491,7 @@ void writeKeyShare(const string &_keyShareName, const string &value, int index,
auto key = "BLSKEYSHARE:" + _keyShareName;
if (levelDb->readString(_keyShareName) != nullptr) {
throw new RPCException(KEY_SHARE_DOES_NOT_EXIST, "Key share with this name already exists");
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Key share with this name already exists");
}
levelDb->writeString(key, value);
......@@ -322,7 +517,40 @@ void writeECDSAKey(const string &_keyName, const string &value) {
auto key = "ECDSAKEY:" + _keyName;
if (levelDb->readString(_keyName) != nullptr) {
throw new RPCException(KEY_SHARE_DOES_NOT_EXIST, "Key with this name already exists");
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Key with this name already exists");
}
levelDb->writeString(key, value);
}
void writeDKGPoly(const string &_polyName, const string &value) {
Json::Value val;
Json::FastWriter writer;
val["value"] = value;
std::string json = writer.write(val);
auto key = "DKGPoly:" + _polyName;
if (levelDb->readString(_polyName) != nullptr) {
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Poly with this name already exists");
}
levelDb->writeString(key, value);
}
void writeDataToDB(const string & Name, const string &value) {
Json::Value val;
Json::FastWriter writer;
val["value"] = value;
std::string json = writer.write(val);
auto key = Name;
if (levelDb->readString(Name) != nullptr) {
std::cerr << "already exists" << std::endl;
throw new RPCException(KEY_SHARE_ALREADY_EXISTS, "Data with this name already exists");
}
levelDb->writeString(key, value);
......
......@@ -5,6 +5,8 @@
#include "abstractstubserver.h"
#include <mutex>
using namespace jsonrpc;
using namespace std;
......@@ -13,36 +15,51 @@ class SGXWalletServer : public AbstractStubServer {
SGXWalletServer* server = nullptr;
std::recursive_mutex m;
public:
SGXWalletServer(AbstractServerConnector &connector, serverVersion_t type);
virtual Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t);
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash);
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int t, int signerIndex);
virtual Json::Value importECDSAKey(const std::string& key, const std::string& keyName);
virtual Json::Value generateECDSAKey(const std::string& keyName);
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyShareName, const std::string& messageHash );
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyShareName, const std::string& messageHash);
virtual Json::Value getPublicECDSAKey(const std::string& keyName);
virtual Json::Value generateDKGPoly(const std::string& polyName, int t);
virtual Json::Value getVerificationVector(const std::string& polyName, int n, int t);
virtual Json::Value getSecretShare(const std::string& polyName, const std::string& publicKeys, int n, int t);
virtual Json::Value DKGVerification(const std::string& polyName, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index);
virtual Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const Json::Value& SecretShare, int t, int n);
};
shared_ptr<string> readFromDb(const string & name, const string & prefix);
void writeDataToDB(const string & Name, const string &value);
void writeKeyShare(const string &_keyShareName, const string &value, int index, int n, int t);
shared_ptr<std::string> readKeyShare(const string& _keyShare);
void writeECDSAKey(const string& _keyName, const string& value);
shared_ptr<std::string> readECDSAKey(const string& _key);
void writeDKGPoly(const string &_polyName, const string &value);
Json::Value importBLSKeyShareImpl(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t);
Json::Value blsSignMessageHashImpl(const std::string& keyShareName, const std::string& messageHash);
Json::Value blsSignMessageHashImpl(const std::string& keyShareName, const std::string& messageHash, int n, int t, int signerIndex);
Json::Value importECDSAKeyImpl(const std::string& key, const std::string& keyName);
Json::Value generateECDSAKeyImpl(const std::string& keyName);
Json::Value ecdsaSignMessageHashImpl(int base, const std::string& keyName, const std::string& messageHash);
Json::Value getPublicECDSAKeyImpl(const std::string& keyName);
Json::Value generateDKGPolyImpl(const std::string& polyName, int t);
Json::Value getVerificationVectorImpl(const std::string& polyName, int n, int t);
Json::Value getSecretShareImpl(const std::string& polyName, const std::string& publicKeys, int n, int t);
Json::Value DKGVerificationImpl(const std::string& polyName, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index);
Json::Value CreateBLSPrivateKeyImpl(const std::string & BLSKeyName, const std::string& EthKeyName, const Json::Value& SecretShare, int t, int n);
#endif //SGXWALLET_SGXWALLETSERVER_HPP
\ No newline at end of file
......@@ -13,11 +13,18 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
AbstractStubServer(jsonrpc::AbstractServerConnector &conn, jsonrpc::serverVersion_t type = jsonrpc::JSONRPC_SERVER_V2) : jsonrpc::AbstractServer<AbstractStubServer>(conn, type)
{
this->bindAndAddMethod(jsonrpc::Procedure("importBLSKeyShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "index",jsonrpc::JSON_INTEGER,"keyShare",jsonrpc::JSON_STRING,"keyShareName",jsonrpc::JSON_STRING,"n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::importBLSKeyShareI);
this->bindAndAddMethod(jsonrpc::Procedure("blsSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyShareName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::blsSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("blsSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyShareName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING,"n",jsonrpc::JSON_INTEGER,"signerIndex",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::blsSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("importECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "key",jsonrpc::JSON_STRING,"keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::importECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("generateECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::generateECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("getPublicECDSAKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "keyName",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::getPublicECDSAKeyI);
this->bindAndAddMethod(jsonrpc::Procedure("ecdsaSignMessageHash", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "base",jsonrpc::JSON_INTEGER,"keyName",jsonrpc::JSON_STRING,"messageHash",jsonrpc::JSON_STRING, NULL), &AbstractStubServer::ecdsaSignMessageHashI);
this->bindAndAddMethod(jsonrpc::Procedure("generateDKGPoly", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::generateDKGPolyI);
this->bindAndAddMethod(jsonrpc::Procedure("getVerificationVector", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT,"polyName",jsonrpc::JSON_STRING, "n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getVerificationVectorI);
this->bindAndAddMethod(jsonrpc::Procedure("getSecretShare", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING,"publicKeys",jsonrpc::JSON_STRING,"n",jsonrpc::JSON_INTEGER,"t",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::getSecretShareI);
this->bindAndAddMethod(jsonrpc::Procedure("DKGVerification", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "polyName",jsonrpc::JSON_STRING, "EthKeyName",jsonrpc::JSON_STRING, "SecretShare",jsonrpc::JSON_STRING,"t",jsonrpc::JSON_INTEGER, "n",jsonrpc::JSON_INTEGER, "index",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::DKGVerificationI);
this->bindAndAddMethod(jsonrpc::Procedure("CreateBLSPrivateKey", jsonrpc::PARAMS_BY_NAME, jsonrpc::JSON_OBJECT, "BLSKeyName",jsonrpc::JSON_STRING, "EthKeyName",jsonrpc::JSON_STRING,"SecretShare",jsonrpc::JSON_ARRAY,"t", jsonrpc::JSON_INTEGER,"n",jsonrpc::JSON_INTEGER, NULL), &AbstractStubServer::CreateBLSPrivateKeyI);
}
inline virtual void importBLSKeyShareI(const Json::Value &request, Json::Value &response)
......@@ -26,7 +33,7 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
}
inline virtual void blsSignMessageHashI(const Json::Value &request, Json::Value &response)
{
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString());
response = this->blsSignMessageHash(request["keyShareName"].asString(), request["messageHash"].asString(), request["n"].asInt(), request["signerIndex"].asInt(), request["t"].asInt());
}
inline virtual void importECDSAKeyI(const Json::Value &request, Json::Value &response)
{
......@@ -44,12 +51,39 @@ class AbstractStubServer : public jsonrpc::AbstractServer<AbstractStubServer>
{
response = this->ecdsaSignMessageHash(request["base"].asInt(), request["keyName"].asString(), request["messageHash"].asString());
}
inline virtual void generateDKGPolyI(const Json::Value &request, Json::Value &response)
{
response = this->generateDKGPoly(request["polyName"].asString(), request["t"].asInt());
}
inline virtual void getVerificationVectorI(const Json::Value &request, Json::Value &response)
{
response = this->getVerificationVector(request["polyName"].asString(), request["n"].asInt(), request["t"].asInt());
}
inline virtual void getSecretShareI(const Json::Value &request, Json::Value &response)
{
response = this->getSecretShare(request["polyName"].asString(), request["publicKeys"].asString(), request["n"].asInt(),request["t"].asInt());
}
inline virtual void DKGVerificationI(const Json::Value &request, Json::Value &response)
{
response = this->DKGVerification(request["polyName"].asString(), request["EthKeyName"].asString(), request["SecretShare"].asString(), request["t"].asInt(), request["n"].asInt(), request["index"].asInt());
}
inline virtual void CreateBLSPrivateKeyI(const Json::Value &request, Json::Value &response)
{
response = this->CreateBLSPrivateKey(request["BLSKeyName"].asString(), request["EthKeyName"].asString(), request["SecretShare"],request["t"].asInt(), request["n"].asInt());
}
virtual Json::Value importBLSKeyShare(int index, const std::string& keyShare, const std::string& keyShareName, int n, int t) = 0;
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash) = 0;
virtual Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int signerIndex, int t) = 0;
virtual Json::Value importECDSAKey(const std::string& key, const std::string& keyName) = 0;
virtual Json::Value generateECDSAKey(const std::string& keyName) = 0;
virtual Json::Value getPublicECDSAKey(const std::string& keyName) = 0;
virtual Json::Value ecdsaSignMessageHash(int base, const std::string& keyName, const std::string& messageHash) = 0;
virtual Json::Value generateDKGPoly(const std::string& polyName, int t) = 0;
virtual Json::Value getVerificationVector(const std::string& polyName, int n, int t) = 0;
virtual Json::Value getSecretShare(const std::string& polyName, const std::string& publicKeys, int n, int t) = 0;
virtual Json::Value DKGVerification( const std::string& polyName, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index) = 0;
virtual Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const Json::Value& SecretShare, int t, int n) = 0;
};
#endif //JSONRPC_CPP_STUB_ABSTRACTSTUBSERVER_H_
File mode changed from 100755 to 100644
Subproject commit 2605d7b96d2b17b05c6bc5f5ec3d94d8ed61ae46
Subproject commit f69e2c2c3d022f60143e2bfb97eae4313abb34d1
DKGUtils.o: DKGUtils.cpp DKGUtils.h \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp \
../sgx-sdk-build/sgxsdk/include/libcxx/vector \
/home/kladko/sgxwallet/tgmp-build/include/sgx_tgmp.h \
../sgx-sdk-build/sgxsdk/include/libcxx/iosfwd \
../sgx-sdk-build/sgxsdk/include/libcxx/__config \
../sgx-sdk-build/sgxsdk/include/libcxx/__sgx \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/endian.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/assert.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/cdefs.h \
../sgx-sdk-build/sgxsdk/include/libcxx/iosfwd \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/wchar.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/_types.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/stdint.h \
../sgx-sdk-build/sgxsdk/include/libcxx/cstdio \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdio.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdarg.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stddef.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/limits.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/limits.h \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp \
../sgx-sdk-build/sgxsdk/include/libcxx/vector \
../sgx-sdk-build/sgxsdk/include/libcxx/__bit_reference \
../sgx-sdk-build/sgxsdk/include/libcxx/algorithm \
../sgx-sdk-build/sgxsdk/include/libcxx/initializer_list \
../sgx-sdk-build/sgxsdk/include/libcxx/cstddef \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stddef.h \
../sgx-sdk-build/sgxsdk/include/libcxx/type_traits \
../sgx-sdk-build/sgxsdk/include/libcxx/cstring \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/string.h \
......@@ -48,17 +54,12 @@ DKGUtils.o: DKGUtils.cpp DKGUtils.h \
../sgx-sdk-build/sgxsdk/include/libcxx/cstdlib \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdlib.h \
../sgx-sdk-build/sgxsdk/include/libcxx/climits \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/limits.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/limits.h \
../sgx-sdk-build/sgxsdk/include/libcxx/__split_buffer \
../trusted_libff/libff/common/utils.hpp \
../sgx-sdk-build/sgxsdk/include/libcxx/cassert \
../sgx-sdk-build/sgxsdk/include/libcxx/iostream \
../sgx-sdk-build/sgxsdk/include/libcxx/sstream \
../sgx-sdk-build/sgxsdk/include/libcxx/string \
../sgx-sdk-build/sgxsdk/include/libcxx/cstdio \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdio.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdarg.h \
../sgx-sdk-build/sgxsdk/include/libcxx/cwchar \
../sgx-sdk-build/sgxsdk/include/libcxx/cwctype \
../sgx-sdk-build/sgxsdk/include/libcxx/cctype \
......@@ -70,7 +71,6 @@ DKGUtils.o: DKGUtils.cpp DKGUtils.h \
../trusted_libff/libff/algebra/fields/fp.hpp \
../trusted_libff/libff/algebra/exponentiation/exponentiation.hpp \
../trusted_libff/libff/algebra/fields/bigint.hpp \
/home/kladko/sgxwallet/tgmp-build/include/sgx_tgmp.h \
../trusted_libff/libff/algebra/fields/bigint.tcc \
../sgx-sdk-build/sgxsdk/include/libcxx/random \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/sgx_trts.h \
......@@ -94,15 +94,14 @@ DKGUtils.o: DKGUtils.cpp DKGUtils.h \
../sgxwallet_common.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/unistd.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/types.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h \
DH_dkg.h
DKGUtils.h:
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp:
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp:
/home/kladko/sgxwallet/tgmp-build/include/sgx_tgmp.h:
../sgx-sdk-build/sgxsdk/include/libcxx/vector:
../sgx-sdk-build/sgxsdk/include/libcxx/iosfwd:
../sgx-sdk-build/sgxsdk/include/libcxx/__config:
......@@ -114,14 +113,30 @@ DKGUtils.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/cdefs.h:
../sgx-sdk-build/sgxsdk/include/libcxx/iosfwd:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/wchar.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/_types.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/stdint.h:
../sgx-sdk-build/sgxsdk/include/libcxx/cstdio:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdio.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdarg.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stddef.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/limits.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/limits.h:
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp:
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp:
../sgx-sdk-build/sgxsdk/include/libcxx/vector:
../sgx-sdk-build/sgxsdk/include/libcxx/__bit_reference:
../sgx-sdk-build/sgxsdk/include/libcxx/algorithm:
......@@ -130,8 +145,6 @@ DKGUtils.h:
../sgx-sdk-build/sgxsdk/include/libcxx/cstddef:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stddef.h:
../sgx-sdk-build/sgxsdk/include/libcxx/type_traits:
../sgx-sdk-build/sgxsdk/include/libcxx/cstring:
......@@ -196,10 +209,6 @@ DKGUtils.h:
../sgx-sdk-build/sgxsdk/include/libcxx/climits:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/limits.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/limits.h:
../sgx-sdk-build/sgxsdk/include/libcxx/__split_buffer:
../trusted_libff/libff/common/utils.hpp:
......@@ -212,12 +221,6 @@ DKGUtils.h:
../sgx-sdk-build/sgxsdk/include/libcxx/string:
../sgx-sdk-build/sgxsdk/include/libcxx/cstdio:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdio.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdarg.h:
../sgx-sdk-build/sgxsdk/include/libcxx/cwchar:
../sgx-sdk-build/sgxsdk/include/libcxx/cwctype:
......@@ -240,8 +243,6 @@ DKGUtils.h:
../trusted_libff/libff/algebra/fields/bigint.hpp:
/home/kladko/sgxwallet/tgmp-build/include/sgx_tgmp.h:
../trusted_libff/libff/algebra/fields/bigint.tcc:
../sgx-sdk-build/sgxsdk/include/libcxx/random:
......@@ -289,3 +290,5 @@ DKGUtils.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/types.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h:
DH_dkg.h:
......@@ -88,7 +88,8 @@ alt_bn128_init.o: \
../trusted_libff/libff/algebra/fields/fp2.hpp \
../trusted_libff/libff/algebra/fields/fp2.tcc \
../trusted_libff/libff/algebra/curves/curve_utils.hpp \
../trusted_libff/libff/algebra/curves/curve_utils.tcc
../trusted_libff/libff/algebra/curves/curve_utils.tcc \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp:
......@@ -267,3 +268,5 @@ alt_bn128_init.o: \
../trusted_libff/libff/algebra/curves/curve_utils.hpp:
../trusted_libff/libff/algebra/curves/curve_utils.tcc:
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp:
......@@ -27,7 +27,8 @@ secure_enclave.o: secure_enclave.c secure_enclave_t.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdio.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdarg.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h \
domain_parameters.h point.h signature.h curves.h ../sgxwallet_common.h \
domain_parameters.h point.h signature.h curves.h DH_dkg.h \
../sgxwallet_common.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/unistd.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/types.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/endian.h
......@@ -98,6 +99,8 @@ signature.h:
curves.h:
DH_dkg.h:
../sgxwallet_common.h:
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/unistd.h:
......
......@@ -10,7 +10,7 @@ signature.o: signature.c \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/sys/limits.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdbool.h \
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/assert.h \
domain_parameters.h point.h signature.h numbertheory.h random.h
domain_parameters.h point.h signature.h numbertheory.h
/home/kladko/sgxwallet/sgx-sdk-build/sgxsdk/include/tlibc/stdlib.h:
......@@ -41,5 +41,3 @@ point.h:
signature.h:
numbertheory.h:
random.h:
......@@ -185,4 +185,66 @@ void carray2Hex(const unsigned char *d, int _len, char* _hexArray) {
}
int char2int(char _input) {
if (_input >= '0' && _input <= '9')
return _input - '0';
if (_input >= 'A' && _input <= 'F')
return _input - 'A' + 10;
if (_input >= 'a' && _input <= 'f')
return _input - 'a' + 10;
return -1;
}
bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length ) {
int len = strnlen(_hex, _max_length);//2 * BUF_LEN);
if (len == 0 && len % 2 == 1)
return false;
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) {
int high = char2int((char)_hex[i * 2]);
int low = char2int((char)_hex[i * 2 + 1]);
if (high < 0 || low < 0) {
return false;
}
_bin[i] = (unsigned char) (high * 16 + low);
}
return true;
}
bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin ) {
int len = strnlen(_hex, 2 * BUF_LEN);
if (len == 0 && len % 2 == 1)
return false;
*_bin_len = len / 2;
for (int i = 0; i < len / 2; i++) {
int high = char2int((char)_hex[i * 2]);
int low = char2int((char)_hex[i * 2 + 1]);
if (high < 0 || low < 0) {
return false;
}
_bin[i] = (unsigned char) (high * 16 + low);
}
return true;
}
......@@ -13,6 +13,8 @@
#define EXTERNC
#endif
//#include <stdint.h>
EXTERNC void checkKey(int *err_status, char *err_string, const char* _keyString);
EXTERNC void check_key(int *err_status, char *err_string, const char* _keyString);
......@@ -21,14 +23,13 @@ EXTERNC void check_key(int *err_status, char *err_string, const char* _keyString
EXTERNC bool enclave_sign(const char *_keyString, const char* _hashXString, const char* _hashYString, char* _sig);
EXTERNC int char2int(char _input);
EXTERNC void carray2Hex(const unsigned char *d, int _len, char* _hexArray);
EXTERNC bool hex2carray(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin );
EXTERNC bool hex2carray2(const char * _hex, uint64_t *_bin_len,
uint8_t* _bin, const int _max_length );
EXTERNC void init();
......
//
// Created by kladko on 10/1/19.
//
#include <stdlib.h>
#include <../tgmp-build/include/sgx_tgmp.h>
#include <stdbool.h>
#include "domain_parameters.h"
#include "curves.h"
#include "point.h"
#include "numbertheory.h"
#include <stdint.h>
#include "BLSEnclave.h"
#include <string.h>
void gen_session_key(char *skey_str, char* pb_keyB, char* common_key){
char* pb_keyB_x = (char*)malloc(65);
strncpy(pb_keyB_x, pb_keyB, 64);
char* pb_keyB_y = (char*)malloc(65);
strncpy(pb_keyB_y, pb_keyB + 64, 64);
domain_parameters curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
mpz_t skey;
mpz_init(skey);
mpz_set_str(skey, skey_str, 16);
point pub_keyB = point_init();
point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y);
point session_key = point_init();
point_multiplication(session_key, skey, pub_keyB, curve);
char arr_x[mpz_sizeinbase (session_key->x, 16) + 2];
char* x = mpz_get_str(arr_x, 16, session_key->x);
//strncpy(common_key, arr_x, 64);
int n_zeroes = 64 - strlen(arr_x);
for ( int i = 0; i < n_zeroes; i++){
common_key[i] = '0';
}
strncpy(common_key + n_zeroes, arr_x, strlen(arr_x));
mpz_clear(skey);
point_clear(pub_keyB);
domain_parameters_clear(curve);
free(pb_keyB_x);
free(pb_keyB_y);
}
void session_key_recover(const char *skey_str, const char* sshare, char* common_key){
char* pb_keyB_x = (char*)malloc(65);
strncpy(pb_keyB_x, sshare + 64, 64);
char* pb_keyB_y = (char*)malloc(65);
strncpy(pb_keyB_y, sshare + 128, 64);
domain_parameters curve = domain_parameters_init();
domain_parameters_load_curve(curve, secp256k1);
mpz_t skey;
mpz_init(skey);
mpz_set_str(skey, skey_str, 16);
point pub_keyB = point_init();
point_set_hex(pub_keyB, pb_keyB_x, pb_keyB_y);
point session_key = point_init();
point_multiplication(session_key, skey, pub_keyB, curve);
char arr_x[mpz_sizeinbase (session_key->x, 16) + 2];
char* x = mpz_get_str(arr_x, 16, session_key->x);
//strncpy(common_key, arr_x, 64);
int n_zeroes = 64 - strlen(arr_x);
for ( int i = 0; i < n_zeroes; i++){
common_key[i] = '0';
}
strncpy(common_key + n_zeroes, arr_x, strlen(arr_x));
//strncpy(common_key , pb_keyB_x, 64);
mpz_clear(skey);
point_clear(pub_keyB);
domain_parameters_clear(curve);
free(pb_keyB_x);
free(pb_keyB_y);
}
void xor_encrypt(char* key, char* message, char* cypher){
uint8_t cypher_bin[33];
//uint8_t key_bin[33];
uint8_t* key_bin = (uint8_t*)malloc(33);
uint64_t key_length;
hex2carray(key, &key_length, key_bin);
uint64_t msg_length;
uint8_t msg_bin[33];//[ECDSA_BIN_LEN];
hex2carray(message, &msg_length, msg_bin);
for (int i = 0; i < 32; i++){
cypher_bin[i] = msg_bin[i] ^ key_bin[i];
}
carray2Hex(cypher_bin, 32, cypher);
free(key_bin);
}
void xor_decrypt(char* key, char* cypher, char* message){
uint8_t msg_bin[33];
//uint8_t key_bin[33];
uint8_t* key_bin = (uint8_t*)malloc(33);
uint64_t key_length;
hex2carray(key, &key_length, key_bin);
uint64_t cypher_length;
uint8_t cypher_bin[33];//[ECDSA_BIN_LEN];
hex2carray(cypher, &cypher_length, cypher_bin);
for (int i = 0; i < 32; i++){
msg_bin[i] = cypher_bin[i] ^ key_bin[i];
}
carray2Hex(msg_bin, 32, message);
free(key_bin);
}
//
// Created by kladko on 10/1/19.
//
#ifndef SGXD_DRIVE_KEY_DKG_H
#define SGXD_DRIVE_KEY_DKG_H
//void gen_session_keys(mpz_t skey, char* pub_key);
void gen_session_key(char* skey, char* pub_keyB, char* common_key);
void session_key_recover(const char *skey_str, const char* sshare, char* common_key);
void xor_encrypt(char* key, char* message, char* cypher);
void xor_decrypt(char* key, char* cypher, char* message);
#endif //SGXD_DRIVE_KEY_DKG_H
......@@ -3,6 +3,7 @@
//
#include "DKGUtils.h"
#include <sgx_tgmp.h>
#include <../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_pp.hpp>
#include <../trusted_libff/libff/algebra/fields/fp.hpp>
......@@ -14,6 +15,11 @@
#include <cstdio>
#include <stdio.h>
#include "DH_dkg.h"
std::string stringFromFr(libff::alt_bn128_Fr& _el) {
......@@ -31,15 +37,15 @@ std::string stringFromFr(libff::alt_bn128_Fr& _el) {
}
template<class T>
std::string ConvertToString(T field_elem) {
std::string ConvertToString(T field_elem, int base = 10) {
mpz_t t;
mpz_init(t);
field_elem.as_bigint().to_mpz(t);
char arr[mpz_sizeinbase (t, 10) + 2];
char arr[mpz_sizeinbase (t, base) + 2];
char * tmp = mpz_get_str(arr, 10, t);
char * tmp = mpz_get_str(arr, base, t);
mpz_clear(t);
std::string output = tmp;
......@@ -47,9 +53,10 @@ std::string ConvertToString(T field_elem) {
return output;
}
std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char* symbol){
std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char symbol){
std::string str(koefs);
std::string delim(symbol);
std::string delim;
delim.push_back(symbol);
std::vector<libff::alt_bn128_Fr> tokens;
size_t prev = 0, pos = 0;
do
......@@ -68,7 +75,7 @@ std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char*
return tokens;
}
void gen_dkg_poly( char* secret/*[BUF_LEN]*/, unsigned _t ){
void gen_dkg_poly( char* secret, unsigned _t ){
libff::init_alt_bn128_params();
std::string result;
for (size_t i = 0; i < _t; ++i) {
......@@ -80,7 +87,7 @@ void gen_dkg_poly( char* secret/*[BUF_LEN]*/, unsigned _t ){
result += stringFromFr(cur_coef);
result += ":";
}
strncpy(secret, result.c_str(), result.length());
strncpy(secret, result.c_str(), result.length() + 1);
}
libff::alt_bn128_Fr PolynomialValue(const std::vector<libff::alt_bn128_Fr>& pol, libff::alt_bn128_Fr point, unsigned _t) {
......@@ -99,28 +106,46 @@ libff::alt_bn128_Fr PolynomialValue(const std::vector<libff::alt_bn128_Fr>& pol,
return value;
}
void calc_secret_shares(const char* decrypted_koefs, char * secret_shares,
unsigned _t, unsigned _n) {
void calc_secret_shares(const char* decrypted_koefs, char * secret_shares, // calculates secret shares in base 10 to a string secret_shares,
unsigned _t, unsigned _n) { // separated by ":"
// calculate for each node a list of secret values that will be used for verification
std::string result;
char symbol = ':';
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, &symbol);
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, symbol);
for (size_t i = 0; i < _n; ++i) {
libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(i + 1), _t);
result += stringFromFr(secret_share);
result += ConvertToString(secret_share);//stringFromFr(secret_share);
result += ":";
}
strncpy(secret_shares, result.c_str(), 2000);//result.length());
strncpy(secret_shares, result.c_str(), result.length() + 1);
//strncpy(secret_shares, decrypted_koefs, 3650);
}
void calc_secret_share(const char* decrypted_koefs, char * s_share,
unsigned _t, unsigned _n, unsigned ind) {
libff::init_alt_bn128_params();
char symbol = ':';
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, symbol);
libff::alt_bn128_Fr secret_share = PolynomialValue(poly, libff::alt_bn128_Fr(ind), _t);
std::string cur_share = ConvertToString(secret_share, 16);//stringFromFr(secret_share);
int n_zeroes = 64 - cur_share.size();
cur_share.insert(0, n_zeroes, '0');
strncpy(s_share, cur_share.c_str(), cur_share.length() + 1);
}
void calc_public_shares(const char* decrypted_koefs, char * public_shares,
unsigned _t) {
libff::init_alt_bn128_params();
// calculate for each node a list of public shares
std::string result;
char symbol = ':';
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, &symbol);
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, symbol);
for (size_t i = 0; i < _t; ++i) {
libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one();
libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one() ;
pub_share.to_affine_coordinates();
result += ConvertToString(pub_share.X.c0);
result += ":";
......@@ -134,4 +159,34 @@ void calc_public_shares(const char* decrypted_koefs, char * public_shares,
strncpy(public_shares, result.c_str(), result.length());
}
int Verification (char * decrypted_koefs, mpz_t decr_secret_share, int _t, int ind ){
libff::init_alt_bn128_params();
char symbol = ':';
std::vector<libff::alt_bn128_Fr> poly = SplitStringToFr(decrypted_koefs, symbol);
std::vector<libff::alt_bn128_G2> pub_shares;
for (size_t i = 0; i < _t; ++i) {
libff::alt_bn128_G2 pub_share = poly.at(i) * libff::alt_bn128_G2::one();
pub_shares.push_back(pub_share);
}
libff::alt_bn128_G2 val = libff::alt_bn128_G2::zero();
for (int i = 0; i < _t; ++i) {
val = val + power(libff::alt_bn128_Fr(ind + 1), i) * pub_shares[i];
}
char arr[mpz_sizeinbase (decr_secret_share, 10) + 2];
char * tmp = mpz_get_str(arr, 10, decr_secret_share);
libff::alt_bn128_Fr sshare(tmp);
//strncpy(decrypted_koefs, ConvertToString(val.X.c0).c_str(), 1024);
libff::alt_bn128_G2 val2 = sshare * libff::alt_bn128_G2::one();
strncpy(decrypted_koefs, ConvertToString(val2.X.c0).c_str(), 1024);
return (val == sshare * libff::alt_bn128_G2::one());
}
......@@ -11,12 +11,20 @@
#define EXTERNC
#endif
#include <sgx_tgmp.h>
EXTERNC void gen_dkg_poly( char* secret, unsigned _t);
EXTERNC void calc_secret_shares(const char* decrypted_koefs, char * secret_shares,
unsigned _t, unsigned _n);
EXTERNC void calc_secret_share(const char* decrypted_koefs, char * s_share,
unsigned _t, unsigned _n, unsigned ind);
EXTERNC void calc_public_shares(const char* decrypted_koefs, char * public_shares,
unsigned _t);
EXTERNC int Verification (char * decrypted_koefs, mpz_t decr_secret_share, int _t, int ind );
#endif //SGXD_DKGUTILS_H
......@@ -85,7 +85,7 @@ CLEANFILES+= secure_enclave_t.c secure_enclave_t.h
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c DH_dkg.c \
DKGUtils.cpp BLSEnclave.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
......@@ -102,9 +102,9 @@ AM_LDFLAGS += $(TGMP_LDFLAGS)
## This line is REQUIRED. It can't be generically defined for
## automake, so you must specify it for your enclave. Note that you
## can't say $(ENCLAVE)_LDADD here: you must spell out the enclave name.../intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl.a
## can't say $(ENCLAVE)_LDADD here: you must spell out the enclave name.
## If you add flags to it, you MUST include @SGX_ENCLAVE_LDADD@ as part
## of the definition to make sure you pick up the right linker flags../intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl.a
## of the definition to make sure you pick up the right linker flags
## and SGX trusted libraries.
secure_enclave_LDADD = @SGX_ENCLAVE_LDADD@
......@@ -115,8 +115,7 @@ secure_enclave_LDADD = @SGX_ENCLAVE_LDADD@
## --startgroup and --endgroup flags. (This would be where you'd add
## SGXSSL libraries, and your trusted c++ library
SGX_EXTRA_TLIBS=-lsgx_tgmp -lsgx_tservice -lsgx_urts -lsgx_tcxx
SGX_EXTRA_TLIBS=-lsgx_tgmp -lsgx_tservice -lsgx_urts -lsgx_tcxx ../intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a
......
## This line must come first when building an Intel SGX enclave.
include $(top_srcdir)/build-aux/sgx_enclave.am
## It sets the following Automake variables:
##
## EXEEXT=.so
## AM_CPPFLAGS = -I$(SGXSDK_INCDIR)
## AM_LDFLAGS = -L$(SGXSDK_LIBDIR)
## libexec_PROGRAMS = $(ENCLAVE)
## CLEANFILES = $(ENCLAVE).signed.so
##
## and places required compiler flags in:
##
## AM_CFLAGS
## AM_CXXFLAGS
##
## It adds a pattern rule for building proxy functions from EDL files:
##
## %_u.h %_u.c: %.edl
##
## And creates build targets for a signed enclave, generating a
## temporary private signing key, and a basic enclave config file:
##
## $(ENCLAVE_CONFIG):
## $(ENCLAVE_KEY):
## $(ENCLAVE).signed$(EXEEXT): $(ENCLAVE)$(EXEEXT)
##
## And sets these Makefile variables:
##
## SGXSDK
## SGXSDK_BINDIR
## SGXSDK_INCDIR
## SGXSDK_LIBDIR
## SGXSSL
## SGXSSL_BINDIR
## SGXSSL_INCDIR
## SGXSSL_LIBDIR
## SGX_TRTS_LIB
## SGX_TSERVICE_LIB
## SGX_EDGER8R
## SGX_SIGN
## The name of your enclave, enclave config file, and private key
## file go in these variables. The ENCLAVE variable creates the
## following automake target defn:
##
## libexec_PROGRAMS=$(ENCLAVE)
ENCLAVE=secure_enclave
ENCLAVE_CONFIG=$(ENCLAVE).config.xml
ENCLAVE_KEY=$(ENCLAVE)_private.pem
## Provide additional flags to sgx_sign when signing the enclave.
## This is almost never necessary. If you don't know if you need
## this, you probably don't.
## SGX_SIGN_FLAGS =
## Additional Automake flags needed to build the enclave.
##
AM_CPPFLAGS += -Wall -Wno-implicit-function-declaration $(TGMP_CPPFLAGS) -I../trusted_libff -I../sgx-sdk-build/sgxsdk/include/libcxx \
-I../intel-sgx-ssl/Linux/package/include
AM_CXXFLAGS += -fno-builtin
## Additional files to remove with 'make clean'. This list needs
## to include your edger8r genreated files.
CLEANFILES+= secure_enclave_t.c secure_enclave_t.h
## Supply additional flags to edger8r here.
##
## SGX_EDGER8R_FLAGS=
## Put your sources here. Don't forget to list the _t.c and _t.h
## files. You can't use the $(ENCLAVE) variable in the build
## target name (i.e., $(ENCLAVE)_SOURCES will not work).
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \
<<<<<<< HEAD
DKGUtils.cpp BLSUtils.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
=======
BLSEnclave.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
>>>>>>> master
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
## Add additional linker flags to AM_LDFLAGS here. Don't put
## libraries flags here (see below).
##
## Be sure to use += to add to, and not replace, the default
## AM_LDFLAGS.
AM_LDFLAGS += $(TGMP_LDFLAGS)
## This line is REQUIRED. It can't be generically defined for
## automake, so you must specify it for your enclave. Note that you
## can't say $(ENCLAVE)_LDADD here: you must spell out the enclave name.
## If you add flags to it, you MUST include @SGX_ENCLAVE_LDADD@ as part
## of the definition to make sure you pick up the right linker flags
## and SGX trusted libraries.
secure_enclave_LDADD = @SGX_ENCLAVE_LDADD@
## Place any additional trusted libraries that your enclave may need in
## SGX_EXTRA_TLIBS. This will ensure they get place inside the
## --startgroup and --endgroup flags. (This would be where you'd add
## SGXSSL libraries, and your trusted c++ library
SGX_EXTRA_TLIBS=-lsgx_tgmp -lsgx_tservice -lsgx_urts -lsgx_tcxx ../intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a
## This line is OPTIONAL, and comes with a WARNING.
##
## In general, you shouldn't need to use the program-specific LDFLAGS
## instead of AM_LDFLAGS. But, if you need to, then you'll need to ensure
## @SGX_ENCLAVE_LDFLAGS@ is included in the definition as this will
## override AM_LDFLAGS.
##
## secure_enclave_LDFLAGS = @SGX_ENCLAVE_LDFLAGS@
##
......@@ -109,10 +109,10 @@ am__objects_1 =
am_secure_enclave_OBJECTS = secure_enclave_t.$(OBJEXT) \
secure_enclave.$(OBJEXT) curves.$(OBJEXT) \
domain_parameters.$(OBJEXT) numbertheory.$(OBJEXT) \
point.$(OBJEXT) signature.$(OBJEXT) DKGUtils.$(OBJEXT) \
BLSEnclave.$(OBJEXT) alt_bn128_init.$(OBJEXT) \
alt_bn128_g2.$(OBJEXT) alt_bn128_g1.$(OBJEXT) $(am__objects_1) \
$(am__objects_1)
point.$(OBJEXT) signature.$(OBJEXT) DH_dkg.$(OBJEXT) \
DKGUtils.$(OBJEXT) BLSEnclave.$(OBJEXT) \
alt_bn128_init.$(OBJEXT) alt_bn128_g2.$(OBJEXT) \
alt_bn128_g1.$(OBJEXT) $(am__objects_1) $(am__objects_1)
secure_enclave_OBJECTS = $(am_secure_enclave_OBJECTS)
secure_enclave_DEPENDENCIES =
@ENCLAVE_RELEASE_SIGN_FALSE@nodist_signed_enclave_debug_OBJECTS = \
......@@ -138,7 +138,7 @@ am__v_at_1 =
DEFAULT_INCLUDES = -I.@am__isrc@
depcomp = $(SHELL) $(top_srcdir)/depcomp
am__maybe_remake_depfiles = depfiles
am__depfiles_remade = ./$(DEPDIR)/BLSEnclave.Po \
am__depfiles_remade = ./$(DEPDIR)/BLSEnclave.Po ./$(DEPDIR)/DH_dkg.Po \
./$(DEPDIR)/DKGUtils.Po ./$(DEPDIR)/alt_bn128_g1.Po \
./$(DEPDIR)/alt_bn128_g2.Po ./$(DEPDIR)/alt_bn128_init.Po \
./$(DEPDIR)/curves.Po ./$(DEPDIR)/domain_parameters.Po \
......@@ -343,13 +343,13 @@ ENCLAVE_CONFIG = $(ENCLAVE).config.xml
ENCLAVE_KEY = $(ENCLAVE)_private.pem
secure_enclave_SOURCES = secure_enclave_t.c secure_enclave_t.h \
secure_enclave.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c \
curves.c domain_parameters.c numbertheory.c point.c signature.c DH_dkg.c \
DKGUtils.cpp BLSEnclave.cpp ../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_init.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g2.cpp \
../trusted_libff/libff/algebra/curves/alt_bn128/alt_bn128_g1.cpp $(ENCLAVE_KEY) $(ENCLAVE_CONFIG)
secure_enclave_LDADD = @SGX_ENCLAVE_LDADD@
SGX_EXTRA_TLIBS = -lsgx_tgmp -lsgx_tservice -lsgx_urts -lsgx_tcxx
SGX_EXTRA_TLIBS = -lsgx_tgmp -lsgx_tservice -lsgx_urts -lsgx_tcxx ../intel-sgx-ssl/Linux/package/lib64/libsgx_tsgxssl_crypto.a
all: all-am
.SUFFIXES:
......@@ -438,6 +438,7 @@ distclean-compile:
-rm -f *.tab.c
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/BLSEnclave.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DH_dkg.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/DKGUtils.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alt_bn128_g1.Po@am__quote@ # am--include-marker
@AMDEP_TRUE@@am__include@ @am__quote@./$(DEPDIR)/alt_bn128_g2.Po@am__quote@ # am--include-marker
......@@ -657,6 +658,7 @@ clean-am: clean-generic clean-libexecPROGRAMS mostlyclean-am
distclean: distclean-am
-rm -f ./$(DEPDIR)/BLSEnclave.Po
-rm -f ./$(DEPDIR)/DH_dkg.Po
-rm -f ./$(DEPDIR)/DKGUtils.Po
-rm -f ./$(DEPDIR)/alt_bn128_g1.Po
-rm -f ./$(DEPDIR)/alt_bn128_g2.Po
......@@ -716,6 +718,7 @@ installcheck-am:
maintainer-clean: maintainer-clean-am
-rm -f ./$(DEPDIR)/BLSEnclave.Po
-rm -f ./$(DEPDIR)/DH_dkg.Po
-rm -f ./$(DEPDIR)/DKGUtils.Po
-rm -f ./$(DEPDIR)/alt_bn128_g1.Po
-rm -f ./$(DEPDIR)/alt_bn128_g2.Po
......
#include <stdio.h>
#include <stdlib.h>
#include <../tgmp-build/include/sgx_tgmp.h>
#include "random.h"
/*Seeds the random state with information from /dev/random
*This may take time, but it's needed to ensure true randomness*/
void random_seeding(gmp_randstate_t r_state)
{
//Open the random device for reading
FILE* ran = fopen(RANDOM_DEVICE, "r");
//input variables
char i1, i2, i3, i4;
//Read 4 bytes, cause that's the most we can put in an unsigned long int
i1 = fgetc(ran);
if(i1 == EOF)
goto end;
i2 = fgetc(ran);
if(i2 == EOF)
goto end;
i3 = fgetc(ran);
if(i3 == EOF)
goto end;
i4 = fgetc(ran);
if(i4 == EOF)
goto end;
//abs() returns long (signed long), therefor there must be two, since DO NOT want to loose any randomness
gmp_randseed_ui(r_state, (unsigned long int)abs(i1)* (unsigned long int)abs(i2*i3*i4));
//Define end
end:
//Close file resources
fclose(ran);
}
/*Seeds the random state with information from /dev/random
*This may take time, but it's needed to ensure true randomness*/
void random_seeding(gmp_randstate_t r_state);
/*Operating system dependent random device, please use true random
*Linux has /dev/random as true RNG and /dev/urandom as pseudo random device
*Note: /dev/random may be slow, whereas /dev/urandom is not as secure*/
#define RANDOM_DEVICE "/dev/urandom"
/*Time spent reading from random device is not included in benchmark and other timings.
*To see difference between real execution time and execution time use Unix "time" command*/
......@@ -31,14 +31,6 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*#include <openssl/ecdsa.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "tSgxSSL_api.h"*/
#include "secure_enclave_t.h"
#include "sgx_tcrypto.h"
#include "sgx_tseal.h"
......@@ -54,12 +46,14 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "point.h"
#include "signature.h"
#include "curves.h"
#include <string.h>
#include "DH_dkg.h"
#include <sgx_tcrypto.h>
#include "../sgxwallet_common.h"
uint8_t Decrypted_dkg_poly[DKG_BUFER_LENGTH] ;
void *(*gmp_realloc_func)(void *, size_t, size_t);
......@@ -151,7 +145,7 @@ void generate_ecdsa_key(int *err_status, char *err_string,
//mpz_set_str(skey, "4160780231445160889237664391382223604184857153814275770598791864649971919844", 10);
//mpz_set_str(skey, "1", 10);
//mpz_set_str(skey, "ebb2c082fd7727890a28ac82f6bdf97bad8de9f5d7c9028692de1a255cad3e0f", 16);
//mpz_set_str(skey, "D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759", 16);
// mpz_set_str(skey, "D30519BCAE8D180DBFCC94FE0B8383DC310185B0BE97B4365083EBCECCD75759", 16);
//Public key
point Pkey = point_init();
......@@ -430,31 +424,58 @@ void gen_dkg_secret (int *err_status, char *err_string, uint8_t *encrypted_dkg_s
free(dkg_secret);
}
void decrypt_dkg_secret (int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint8_t* decrypted_dkg_secret, uint32_t enc_len){
void decrypt_dkg_secret (int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint8_t* decrypted_dkg_secret, uint32_t* dec_len){
//uint32_t dec_size = DKG_BUFER_LENGTH;//sgx_get_encrypt_txt_len( ( sgx_sealed_data_t *)encrypted_dkg_secret);
uint32_t decr_len;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, decrypted_dkg_secret, &enc_len);
(const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, decrypted_dkg_secret, &decr_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
*dec_len = decr_len;
}
void get_secret_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t enc_len, char* secret_shares,
void get_secret_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t* dec_len, char* secret_shares,
unsigned _t, unsigned _n){
char* decrypted_dkg_secret = (char*)malloc(DKG_MAX_SEALED_LEN);
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, enc_len);
char* decrypted_dkg_secret = (char*)malloc(DKG_BUFER_LENGTH);
//char decrypted_dkg_secret[DKG_MAX_SEALED_LEN];
uint32_t decr_len ;
//uint32_t* decr_len_test = (char*)malloc(1);
decrypt_dkg_secret(err_status, err_string, encrypted_dkg_secret, (uint8_t*)decrypted_dkg_secret, &decr_len);
//sgx_status_t status = sgx_unseal_data(
// (const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, (uint8_t*)decrypted_dkg_secret, &decr_len);
if (*err_status != 0) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", *err_status);
return;
}
*dec_len = decr_len;
// strncpy(err_string, decrypted_dkg_secret, 1024);
calc_secret_shares(decrypted_dkg_secret, secret_shares, _t, _n);
free(decrypted_dkg_secret);
}
void get_public_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t enc_len, char* public_shares,
unsigned _t, unsigned _n){
char* decrypted_dkg_secret = (char*)malloc(DKG_MAX_SEALED_LEN);
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, enc_len);
uint32_t decr_len ;
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, &decr_len);
if( *err_status != 0 ){
snprintf(err_string, BUF_LEN,"decrypt_dkg_secret failed with status %d", *err_status);
return;
}
//strncpy(err_string, decrypted_dkg_secret, 1024);
// strncpy(err_string, "before calc_public_shares ", 1024);
calc_public_shares(decrypted_dkg_secret, public_shares, _t);
free(decrypted_dkg_secret);
}
void ecdsa_sign1(int *err_status, char *err_string, uint8_t *encrypted_key, uint32_t dec_len,
......@@ -493,7 +514,6 @@ void ecdsa_sign1(int *err_status, char *err_string, uint8_t *encrypted_key, uint
signature sign = signature_init();
signature_sign( sign, msg_mpz, skey_mpz, curve);
point Pkey = point_init();
......@@ -531,3 +551,193 @@ void ecdsa_sign1(int *err_status, char *err_string, uint8_t *encrypted_key, uint
}
void set_encrypted_dkg_poly(int *err_status, char *err_string, uint8_t* encrypted_poly){
uint32_t decr_len;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_poly, NULL, 0, Decrypted_dkg_poly, &decr_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
}
void get_encr_sshare(int *err_status, char *err_string, uint8_t *encrypted_skey, uint32_t* dec_len,
char* result_str, char* pub_keyB, uint8_t _t, uint8_t _n, uint8_t ind ){
char skey[ECDSA_SKEY_LEN];
char *pub_key_x = (char *)calloc(1024, 1);
char *pub_key_y = (char *)calloc(1024, 1);
uint32_t enc_len;
generate_ecdsa_key(err_status, err_string, encrypted_skey, &enc_len, pub_key_x, pub_key_y);
snprintf(err_string, BUF_LEN,"pub_key_x is %s", pub_key_x);
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_skey, NULL, 0, (uint8_t *)skey, &enc_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
char * common_key = (char *)malloc(65);
gen_session_key(skey, pub_keyB, common_key);
//snprintf(err_string, BUF_LEN,"common key is %s", common_key);
char* s_share = (char *)malloc(65);
//char s_share[65];
calc_secret_share(Decrypted_dkg_poly, s_share, _t, _n, ind);
//snprintf(err_string, BUF_LEN,"secret share is %s", s_share);
char* cypher = (char *)malloc(65);
xor_encrypt(common_key, s_share, cypher);
//snprintf(err_string, BUF_LEN,"cypher is %s length is %d", cypher, strlen(cypher));
strncpy(result_str, cypher, strlen(cypher));
strncpy(result_str + strlen(cypher), pub_key_x, strlen(pub_key_x));
strncpy(result_str + strlen(pub_key_x) + strlen(pub_key_y), pub_key_y, strlen(pub_key_y));
//snprintf(err_string, BUF_LEN,"s_share is %s length is %d", result_str, strlen(result_str));
//mpz_clear(skey);
//free(skey);
free(common_key);
free(pub_key_x);
free(pub_key_y);
free(s_share);
free(cypher);
}
void dkg_verification(int *err_status, char* err_string, const uint8_t * encrypted_dkg_secret, const char* s_share,
uint8_t* encrypted_key, uint64_t key_len, unsigned _t, int _ind, int * result){
char* decrypted_dkg_secret = (char*)malloc(DKG_BUFER_LENGTH);
uint32_t decr_len ;
decrypt_dkg_secret(err_status, err_string, encrypted_dkg_secret, (uint8_t*)decrypted_dkg_secret, &decr_len);
if (*err_status != 0) {
snprintf(err_string, BUF_LEN,"sgx_unseal_poly failed with status %d", *err_status);
return;
}
//uint32_t dec_len = 625;
char skey[ECDSA_SKEY_LEN];
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_key, NULL, 0, (uint8_t*)skey, &key_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_key failed with status %d", status);
return;
}
char encr_sshare[65];
strncpy(encr_sshare, s_share, 64);
encr_sshare[64] = 0;
char common_key[65];
char decr_sshare[65];
session_key_recover(skey, s_share, common_key);
common_key[64] = 0;
xor_decrypt(common_key, encr_sshare, decr_sshare);
//snprintf(err_string, BUF_LEN,"sshare is %s", decr_sshare);
//snprintf(err_string, BUF_LEN,"encr_share is %s", encr_sshare);
//snprintf(err_string, BUF_LEN,"common_key is %s", common_key);
mpz_t s;
mpz_init(s);
mpz_set_str(s, decr_sshare, 16);
*result = Verification(decrypted_dkg_secret, s, _t, _ind);
//snprintf(err_string, BUF_LEN,"val is %s", decrypted_dkg_secret);
free(decrypted_dkg_secret);
}
void create_bls_key(int *err_status, char* err_string, const char* s_shares,
uint8_t* encrypted_key, uint64_t key_len, uint8_t * encr_bls_key){
//uint32_t dec_len = 625;
char skey[ECDSA_SKEY_LEN];
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_key, NULL, 0, (uint8_t*)skey, &key_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_key failed with status %d", status);
return;
}
int num_shares = strlen(s_shares)/192;
mpz_t sum;
mpz_init(sum);
mpz_set_ui(sum, 0);
for ( int i = 0; i < num_shares; i++) {
char encr_sshare[65];
strncpy(encr_sshare, s_shares + 192 * i, 64);
encr_sshare[64] = 0;
char s_share[193];
strncpy(s_share, s_share + 192 * i, 192);
s_share[192] = 0;
char common_key[65];
session_key_recover(skey, s_share, common_key);
common_key[64] = 0;
char decr_sshare[65];
xor_decrypt(common_key, encr_sshare, decr_sshare);
mpz_t decr_secret_share;
mpz_init(decr_secret_share);
mpz_set_str(decr_secret_share, decr_sshare, 16);
mpz_addmul_ui(sum, decr_secret_share, 1);
mpz_clear(decr_secret_share);
}
mpz_t q;
mpz_init(q);
mpz_set_str(q, "21888242871839275222246405745257275088696311157297823662689037894645226208583", 10);
mpz_t bls_key;
mpz_init(bls_key);
mpz_mod(bls_key, sum, q);
char arr[mpz_sizeinbase(bls_key, 10) + 2];
char *key = mpz_get_str(arr, 10, bls_key);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, ECDSA_SKEY_LEN);
status = sgx_seal_data(0, NULL, ECDSA_SKEY_LEN, (uint8_t *)key, sealedLen,(sgx_sealed_data_t*)encr_bls_key);
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"seal bls private key failed");
return;
}
//snprintf(err_string, BUF_LEN,"sshare is %s", decr_sshare);
//snprintf(err_string, BUF_LEN,"encr_share is %s", encr_sshare);
//snprintf(err_string, BUF_LEN,"common_key is %s", common_key);
// mpz_t s;
// mpz_init(s);
// mpz_set_str(s, decr_sshare, 16);
//snprintf(err_string, BUF_LEN,"val is %s", decrypted_dkg_secret);
mpz_clear(bls_key);
mpz_clear(sum);
}
/*
Copyright 2018 Intel Corporation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "secure_enclave_t.h"
#include "sgx_tcrypto.h"
#include "sgx_tseal.h"
#include <sgx_tgmp.h>
#include <sgx_trts.h>
#include <math.h>
#include <string.h>
#include <stdio.h>
#include <openssl/ec.h>
#include <openssl/bn.h>
#include <openssl/evp.h>
#include <openssl/err.h>
#include <openssl/rand.h>
#include "tSgxSSL_api.h"
#include "../sgxwallet_common.h"
void *(*gmp_realloc_func)(void *, size_t, size_t);
void *(*oc_realloc_func)(void *, size_t, size_t);
void (*gmp_free_func)(void *, size_t);
void (*oc_free_func)(void *, size_t);
void *reallocate_function(void *, size_t, size_t);
void free_function(void *, size_t);
void tgmp_init() {
oc_realloc_func = &reallocate_function;
oc_free_func = &free_function;
mp_get_memory_functions(NULL, &gmp_realloc_func, &gmp_free_func);
mp_set_memory_functions(NULL, oc_realloc_func, oc_free_func);
}
void free_function(void *ptr, size_t sz) {
if (sgx_is_within_enclave(ptr, sz))
gmp_free_func(ptr, sz);
else {
sgx_status_t status;
status = oc_free(ptr, sz);
if (status != SGX_SUCCESS)
abort();
}
}
void *reallocate_function(void *ptr, size_t osize, size_t nsize) {
uint64_t nptr;
sgx_status_t status;
if (sgx_is_within_enclave(ptr, osize)) {
return gmp_realloc_func(ptr, osize, nsize);
}
status = oc_realloc(&nptr, ptr, osize, nsize);
if (status != SGX_SUCCESS)
abort();
/*
* If the entire range of allocated memory is not outside the enclave
* then something truly terrible has happened. In theory, we could
* free() and try again, but would you trust the OS at this point?
*/
if (!sgx_is_outside_enclave((void *) ptr, nsize))
abort();
return (void *) nptr;
}
void e_mpz_add(mpz_t *c_un, mpz_t *a_un, mpz_t *b_un) {}
void e_mpz_mul(mpz_t *c_un, mpz_t *a_un, mpz_t *b_un) {}
void e_mpz_div(mpz_t *c_un, mpz_t *a_un, mpz_t *b_un) {}
void e_mpf_div(mpf_t *c_un, mpf_t *a_un, mpf_t *b_un) {}
void generate_ecdsa_key(int *err_status, char *err_string,
uint8_t *encrypted_key, uint32_t *enc_len) {
}
void encrypt_key(int *err_status, char *err_string, char *key,
uint8_t *encrypted_key, uint32_t *enc_len) {
init();
*err_status = UNKNOWN_ERROR;
memset(err_string, 0, BUF_LEN);
checkKey(err_status, err_string, key);
if (*err_status != 0) {
snprintf(err_string + strlen(err_string), BUF_LEN, "check_key failed");
return;
}
uint32_t sealedLen = sgx_calc_sealed_data_size(0, MAX_KEY_LENGTH);
if (sealedLen > BUF_LEN) {
*err_status = ENCRYPTED_KEY_TOO_LONG;
snprintf(err_string, BUF_LEN, "sealedLen > MAX_ENCRYPTED_KEY_LENGTH");
return;
}
memset(encrypted_key, 0, BUF_LEN);
if (sgx_seal_data(0, NULL, MAX_KEY_LENGTH, (uint8_t *) key, sealedLen, (sgx_sealed_data_t *) encrypted_key) !=
SGX_SUCCESS) {
*err_status = SEAL_KEY_FAILED;
snprintf(err_string, BUF_LEN, "SGX seal data failed");
return;
}
*enc_len = sealedLen;
char decryptedKey[BUF_LEN];
memset(decryptedKey, 0, BUF_LEN);
decrypt_key(err_status, err_string, encrypted_key, sealedLen, decryptedKey);
if (*err_status != 0) {
snprintf(err_string + strlen(err_string), BUF_LEN, ":decrypt_key failed");
return;
}
uint64_t decryptedKeyLen = strnlen(decryptedKey, MAX_KEY_LENGTH);
if (decryptedKeyLen == MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "Decrypted key is not null terminated");
return;
}
*err_status = -8;
if (strncmp(key, decryptedKey, MAX_KEY_LENGTH) != 0) {
snprintf(err_string, BUF_LEN, "Decrypted key does not match original key");
return;
}
*err_status = 0;
}
void decrypt_key(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, char *key) {
init();
uint32_t decLen;
*err_status = -9;
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *) encrypted_key, NULL, 0, (uint8_t *) key, &decLen);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN, "sgx_unseal_data failed with status %d", status);
return;
}
if (decLen != MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "decLen != MAX_KEY_LENGTH");
return;
}
*err_status = -10;
uint64_t keyLen = strnlen(key, MAX_KEY_LENGTH);
if (keyLen == MAX_KEY_LENGTH) {
snprintf(err_string, BUF_LEN, "Key is not null terminated");
return;
}
// check that key is padded with 0s
for (int i = keyLen; i < MAX_KEY_LENGTH; i++) {
if (key[i] != 0) {
snprintf(err_string, BUF_LEN, "Unpadded key");
return;
}
}
*err_status = 0;
return;
}
void bls_sign_message(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, char *_hashX,
char *_hashY, char *signature) {
char key[BUF_LEN];
char* sig = (char*) calloc(BUF_LEN, 1);
init();
decrypt_key(err_status, err_string, encrypted_key, enc_len, key);
if (*err_status != 0) {
return;
}
enclave_sign(key, _hashX, _hashY, sig);
strncpy(signature, sig, BUF_LEN);
if (strnlen(signature, BUF_LEN) < 10) {
*err_status = -1;
return;
}
}
void ecdsa_sign_message(int *err_status, char *err_string, uint8_t *encrypted_key,
uint32_t enc_len, uint8_t *message, char *signature) {
*err_status = -1;
char key[BUF_LEN];
decrypt_key(err_status, err_string, encrypted_key, enc_len, key);
if (err_status != 0) {
return;
}
<<<<<<< HEAD
//strncpy(signature, ecdsaSig, MAX_SIG_LEN);
=======
>>>>>>> master
//strncpy(signature, ecdsaSig, MAX_SIG_LEN);
unsigned char entropy_buf[ADD_ENTROPY_SIZE] = {0};
RAND_add(entropy_buf, sizeof(entropy_buf), ADD_ENTROPY_SIZE);
RAND_seed(entropy_buf, sizeof(entropy_buf));
// Initialize SGXSSL crypto
OPENSSL_init_crypto(0, NULL);
RAND_add(entropy_buf, sizeof(entropy_buf), ADD_ENTROPY_SIZE);
RAND_seed(entropy_buf, sizeof(entropy_buf));
EC_KEY *ec = NULL;
int eccgroup;
eccgroup = OBJ_txt2nid("secp384r1");
ec = EC_KEY_new_by_curve_name(eccgroup);
if (ec == NULL) {
return;
}
EC_KEY_set_asn1_flag(ec, OPENSSL_EC_NAMED_CURVE);
int ret = EC_KEY_generate_key(ec);
if (!ret) {
return;
}
EVP_PKEY *ec_pkey = EVP_PKEY_new();
if (ec_pkey == NULL) {
return;
}
EVP_PKEY_assign_EC_KEY(ec_pkey, ec);
// DONE
char buffer[100];
unsigned char sig;
unsigned int siglen;
int i;
for (i = 0; i < 1000; i++) {
// Add context
EVP_MD_CTX *context = EVP_MD_CTX_new();
// Init, update, final
EVP_SignInit_ex(context, EVP_sha1(), NULL);
EVP_SignUpdate(context, &buffer, 100);
EVP_SignFinal(context, &sig, &siglen, ec_pkey);
}
*err_status = 0;
}
void gen_dkg_secret (int *err_status, char *err_string, uint8_t *encrypted_dkg_secret, uint32_t* enc_len, size_t _t){
char* dkg_secret = (char*)malloc(DKG_BUFER_LENGTH);
gen_dkg_poly(dkg_secret, _t);
uint32_t sealedLen = sgx_calc_sealed_data_size(0, DKG_BUFER_LENGTH);//sizeof(sgx_sealed_data_t) + sizeof(dkg_secret);
sgx_status_t status = sgx_seal_data(0, NULL, DKG_BUFER_LENGTH, (uint8_t*)dkg_secret, sealedLen,(sgx_sealed_data_t*)encrypted_dkg_secret);
if( status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"SGX seal data failed");
}
*enc_len = sealedLen;
}
void decrypt_dkg_secret (int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint8_t* decrypted_dkg_secret, uint32_t enc_len){
//uint32_t dec_size = DKG_BUFER_LENGTH;//sgx_get_encrypt_txt_len( ( sgx_sealed_data_t *)encrypted_dkg_secret);
sgx_status_t status = sgx_unseal_data(
(const sgx_sealed_data_t *)encrypted_dkg_secret, NULL, 0, decrypted_dkg_secret, &enc_len);
if (status != SGX_SUCCESS) {
snprintf(err_string, BUF_LEN,"sgx_unseal_data failed with status %d", status);
return;
}
}
void get_secret_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t enc_len, char* secret_shares,
unsigned _t, unsigned _n){
char* decrypted_dkg_secret = (char*)malloc(DKG_MAX_SEALED_LEN);
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, enc_len);
calc_secret_shares(decrypted_dkg_secret, secret_shares, _t, _n);
}
void get_public_shares(int *err_status, char* err_string, uint8_t* encrypted_dkg_secret, uint32_t enc_len, char* public_shares,
unsigned _t, unsigned _n){
char* decrypted_dkg_secret = (char*)malloc(DKG_MAX_SEALED_LEN);
decrypt_dkg_secret(err_status, err_string, (uint8_t*)encrypted_dkg_secret, decrypted_dkg_secret, enc_len);
calc_public_shares(decrypted_dkg_secret, public_shares, _t);
}
......@@ -3,7 +3,8 @@
<ISVSVN>0</ISVSVN>
<StackMaxSize>0x100000</StackMaxSize>
<HeapMaxSize>0x1000000</HeapMaxSize>
<TCSNum>1</TCSNum>
<TCSNum>16</TCSNum>
<TCSMaxNum>16</TCSMaxNum>
<TCSPolicy>1</TCSPolicy>
<!-- Recommend changing 'DisableDebug' to 1 to make the enclave undebuggable for enclave release -->
<DisableDebug>0</DisableDebug>
......
enclave {
from "sgx_tsgxssl.edl" import *;
trusted {
include "sgx_tgmp.h"
......@@ -43,7 +41,8 @@ from "sgx_tsgxssl.edl" import *;
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 1024] char* key,
[out, count = 1024] uint8_t* encrypted_key, [user_check] uint32_t *enc_len);
[out, count = 1024] uint8_t* encrypted_key,
[user_check] uint32_t *enc_len);
public void decrypt_key (
[user_check] int *err_status,
......@@ -64,32 +63,32 @@ from "sgx_tsgxssl.edl" import *;
public void gen_dkg_secret (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[out, count = 2000] uint8_t* encrypted_dkg_secret,
[out, count = 3050] uint8_t* encrypted_dkg_secret,
[user_check] uint32_t * enc_len,
size_t _t);
public void decrypt_dkg_secret (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 2000] uint8_t* encrypted_dkg_secret,
[out, count = 2000] uint8_t* decrypted_dkg_secret,
uint32_t enc_len);
[in, count = 3050] uint8_t* encrypted_dkg_secret,
[out, count = 2490] uint8_t* decrypted_dkg_secret,
[user_check] uint32_t* dec_len);
public void get_secret_shares (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 2000] uint8_t* encrypted_dkg_secret,
uint32_t enc_len,
[out, count = 2000] char* secret_shares,
[in, count = 3050] uint8_t* encrypted_dkg_secret,
[user_check] uint32_t* dec_len,
[out, count = 2490] char* secret_shares,
unsigned _t,
unsigned _n);
public void get_public_shares (
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 2000] uint8_t* decrypted_dkg_secret,
[in, count = 3050] uint8_t* encrypted_dkg_secret,
uint32_t enc_len,
[out, count = 4000] char* public_shares,
[out, count = 10000] char* public_shares,
unsigned _t,
unsigned _n);
......@@ -103,6 +102,40 @@ from "sgx_tsgxssl.edl" import *;
[out, count = 1024] char* sig_s,
[user_check] uint8_t* sig_v,
int base);
public void set_encrypted_dkg_poly( [user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 3050] uint8_t* encrypted_poly);
public void get_encr_sshare(
[user_check]int *err_status,
[out, count = 1024] char *err_string,
[out, count = 1024] uint8_t *encrypted_skey,
[user_check] uint32_t* dec_len,
[out, count = 193] char* result_str,
[in, count = 129] char* pub_keyB,
uint8_t _t,
uint8_t _n,
uint8_t ind);
public void dkg_verification(
[user_check] int *err_status,
[out, count = 1024] char* err_string,
[in, count = 3050] const uint8_t* encrypted_dkg_secret,
[in, count = 129] const char* s_share,
[in, count = 1024] uint8_t* encrypted_key,
uint64_t key_len,
unsigned _t,
int _ind,
[user_check] int* result);
public void create_bls_key(
[user_check]int *err_status,
[out, count = 1024] char* err_string,
[in, count = 6145] const char* s_shares,
[in, count = 1024] uint8_t* encrypted_key,
uint64_t key_len,
[out, count = 1024] uint8_t * encr_bls_key);
};
......
......@@ -7,7 +7,6 @@
#include "point.h"
#include "signature.h"
#include "numbertheory.h"
#include "random.h"
/*Initialize a signature*/
signature signature_init()
......
......@@ -26,12 +26,13 @@
#define ADD_ENTROPY_SIZE 32
#define DKG_BUFER_LENGTH 1250
#define DKG_MAX_SEALED_LEN 2000
#define DKG_BUFER_LENGTH 2490//3060
#define DKG_MAX_SEALED_LEN 3050
#define ECDSA_SKEY_LEN 65
#define ECDSA_SKEY_BASE 16
#define ECDSA_ENCR_LEN 625
#define ECDSA_BIN_LEN 33
#define UNKNOWN_ERROR -1
#define PLAINTEXT_KEY_TOO_LONG -2
......
......@@ -19,7 +19,10 @@
"name": "blsSignMessageHash",
"params": {
"keyShareName": "key1",
"messageHash": "1122334455"
"messageHash": "1122334455",
"n": 2,
"t": 2,
"signerIndex": 1
},
"returns": {
"status": 0,
......@@ -42,7 +45,6 @@
}
},
{
"name": "generateECDSAKey",
"params": {
......@@ -82,5 +84,79 @@
"signature_r": "12345",
"signature_s": "12345"
}
},
{
"name": "generateDKGPoly",
"params": {
"polyName": "key1",
"t": 3
},
"returns": {
"status": 0,
"errorMessage": "12345"
}
},
{
"name": "getVerificationVector",
"params": {
"polyName": "key1",
"n": 3,
"t": 3
},
"returns": {
"status": 0,
"errorMessage": "12345",
"Verification Vector": [{},{}]
}
},
{
"name": "getSecretShare",
"params": {
"polyName": "key1",
"publicKeys": "123",
"n": 3,
"t": 3
},
"returns": {
"status": 0,
"errorMessage": "12345",
"SecretShare": "123"
}
},
{
"name": "DKGVerification",
"params": {
"polyName": "p2",
"EthKeyName":"key1",
"SecretShare": "123",
"n": 3,
"t": 3,
"index" : 2
},
"returns": {
"status": 0,
"errorMessage": "12345",
"result": true
}
},
{
"name": "CreateBLSPrivateKey",
"params": {
"BLSKeyName": "key",
"EthKeyName":"key1",
"SecretShare": ["122","1222"],
"n": 3,
"t": 3
},
"returns": {
"status": 0,
"errorMessage": "12345",
"BLSKeyName": "key"
}
}
]
\ No newline at end of file
......@@ -26,11 +26,14 @@ class StubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash) throw (jsonrpc::JsonRpcException)
Json::Value blsSignMessageHash(const std::string& keyShareName, const std::string& messageHash, int n, int signerIndex, int t) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["keyShareName"] = keyShareName;
p["messageHash"] = messageHash;
p["n"] = n;
p["signerIndex"] = signerIndex;
p["t"] = t;
Json::Value result = this->CallMethod("blsSignMessageHash",p);
if (result.isObject())
return result;
......@@ -80,6 +83,71 @@ class StubClient : public jsonrpc::Client
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value generateDKGPoly(const std::string& polyName, int t) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["polyName"] = polyName;
p["t"] = t;
Json::Value result = this->CallMethod("generateDKGPoly",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getVerificationVector(const std::string& polyName, int n, int t) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["polyName"] = polyName;
p["n"] = n;
p["t"] = t;
Json::Value result = this->CallMethod("getVerificationVector",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value getSecretShare(const std::string& polyName, const std::string& publicKeys, int n, int t) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["polyName"] = polyName;
p["publicKeys"] = publicKeys;
p["n"] = n;
p["t"] = t;
Json::Value result = this->CallMethod("getSecretShare",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value DKGVerification(const std::string& polyName, const std::string& EthKeyName, const std::string& SecretShare, int t, int n, int index) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["EthKeyName"] = EthKeyName;
p["SecretShare"] = SecretShare;
p["index"] = index;
p["n"] = n;
p["polyName"] = polyName;
p["t"] = t;
Json::Value result = this->CallMethod("DKGVerification",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
Json::Value CreateBLSPrivateKey(const std::string & BLSKeyName, const std::string& EthKeyName, const Json::Value& SecretShare, int n, int t) throw (jsonrpc::JsonRpcException)
{
Json::Value p;
p["BLSKeyName"] = BLSKeyName;
p["EthKeyName"] = EthKeyName;
p["SecretShare"] = SecretShare;
p["n"] = n;
p["t"] = t;
Json::Value result = this->CallMethod("CreateBLSPrivateKey",p);
if (result.isObject())
return result;
else
throw jsonrpc::JsonRpcException(jsonrpc::Errors::ERROR_CLIENT_INVALID_RESPONSE, result.toStyledString());
}
};
#endif //JSONRPC_CPP_STUB_STUBCLIENT_H_
......@@ -56,6 +56,7 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "BLSCrypto.h"
#include "ServerInit.h"
#include "DKGCrypto.h"
#include "RPCException.h"
#include "LevelDB.h"
......@@ -125,14 +126,6 @@ char* encryptTestKey() {
}
class StartFromScratch {
public:
StartFromScratch() {
}
};
TEST_CASE("BLS key encrypt", "[bls-key-encrypt]") {
......@@ -188,23 +181,25 @@ TEST_CASE("BLS key import", "[bls-key-import]") {
TEST_CASE("BLS sign test", "[bls-sign]") {
init_all();
//init_all();
init_enclave();
char* encryptedKeyHex = encryptTestKey();
char* encryptedKeyHex ="04000200000000000406ffffff02000000000000000000000b000000000000ff0000000000000000813f8390f6228a568e181a4dadb6508e3e66f5247175d65dbd0d8c7fbfa4df45000000f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000008000000000000000000000000000000000dc044ae0cd79faaf41e8a7abb412790476738a98b5b6ce95fa1a32db5551b0a0d867305f4de558c64fee730a1f62394633c7d4ca65e3a40b7883e89c2801c61918b01c5de8624a52963df6f4de8581bcbdd2f9b69720d4cc764e03a04c7a99314bfdb5d2d55deda2ca40cd691f093fb2ecbae24cdacdd4d5de93189c6dfd6792d7b95bd5e330aec3538e7a85d15793"; //encryptTestKey();
REQUIRE(encryptedKeyHex != nullptr);
const char *hexHash = "001122334455667788" "001122334455667788" "001122334455667788" "001122334455667788";
// const char *hexHash = "001122334455667788" "001122334455667788" "001122334455667788" "001122334455667788";
const char *hexHash = "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F";
char* hexHashBuf = (char*) calloc(BUF_LEN, 1);
strncpy(hexHashBuf, hexHash, BUF_LEN);
char sig[BUF_LEN];
auto result = sign(encryptedKeyHex, hexHashBuf, 2, 2, 1, sig);
REQUIRE(sign(encryptedKeyHex, hexHashBuf, 2, 2, 1, sig));
REQUIRE(result == true);
printf("Signature is: %s \n", sig );
}
......@@ -223,7 +218,7 @@ TEST_CASE("Server BLS sign test", "[bls-server-sign]") {
const char *hexHash = "001122334455667788" "001122334455667788" "001122334455667788" "001122334455667788";
REQUIRE_NOTHROW(result = blsSignMessageHashImpl(TEST_BLS_KEY_NAME, hexHash));
REQUIRE_NOTHROW(result = blsSignMessageHashImpl(TEST_BLS_KEY_NAME, hexHash,2,2,1));
if (result["status"] != 0) {
printf("Error message: %s", result["errorMessage"].asString().c_str());
......@@ -266,28 +261,31 @@ TEST_CASE("KeysDB test", "[keys-db]") {
TEST_CASE( "DKG gen test", "[dkg-gen]" ) {
init_all();
//init_all();
init_enclave();
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
char* errMsg = (char*) calloc(1024,1);
int err_status = 0;
uint32_t enc_len = 0;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 16);
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 32);
REQUIRE(status == SGX_SUCCESS);
printf("gen_dkg_secret completed with status: %d %s \n", err_status, errMsg);
printf("\n Length: %d \n", enc_len);
char* secret = (char*)calloc(DKG_MAX_SEALED_LEN, sizeof(char));
char* secret = (char*)calloc(DKG_BUFER_LENGTH, sizeof(char));
char* errMsg1 = (char*) calloc(1024,1);
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, enc_len);
uint32_t dec_len;
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, &dec_len);
REQUIRE(status == SGX_SUCCESS);
printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1);
printf("decrypted secret %s \n\n", secret);
printf ("secret length %d \n", strlen(secret));
printf ("decr length %d \n", dec_len);
free(errMsg);
free(errMsg1);
......@@ -297,9 +295,10 @@ TEST_CASE( "DKG gen test", "[dkg-gen]" ) {
sgx_destroy_enclave(eid);
}
std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char* symbol){
std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char symbol){
std::string str(koefs);
std::string delim(symbol);
std::string delim;
delim.push_back(symbol);
std::vector<libff::alt_bn128_Fr> tokens;
size_t prev = 0, pos = 0;
do
......@@ -318,46 +317,89 @@ std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char*
return tokens;
}
std::vector<std::string> SplitStringTest(const char* koefs, const char symbol){
libff::init_alt_bn128_params();
std::string str(koefs);
std::string delim;
delim.push_back(symbol);
std::vector<std::string> G2_strings;
size_t prev = 0, pos = 0;
do
{
pos = str.find(delim, prev);
if (pos == std::string::npos) pos = str.length();
std::string token = str.substr(prev, pos-prev);
if (!token.empty()) {
std::string koef(token.c_str());
G2_strings.push_back(koef);
}
prev = pos + delim.length();
}
while (pos < str.length() && prev < str.length());
return G2_strings;
}
libff::alt_bn128_G2 VectStringToG2(const std::vector<std::string>& G2_str_vect){
libff::init_alt_bn128_params();
libff::alt_bn128_G2 koef = libff::alt_bn128_G2::zero();
koef.X.c0 = libff::alt_bn128_Fq(G2_str_vect.at(0).c_str());
koef.X.c1 = libff::alt_bn128_Fq(G2_str_vect.at(1).c_str());
koef.Y.c0 = libff::alt_bn128_Fq(G2_str_vect.at(2).c_str());
koef.Y.c1 = libff::alt_bn128_Fq(G2_str_vect.at(3).c_str());
koef.Z.c0 = libff::alt_bn128_Fq::one();
koef.Z.c1 = libff::alt_bn128_Fq::zero();
return koef;
}
TEST_CASE( "DKG secret shares test", "[dkg-s_shares]" ) {
//init_all();
init_enclave();
libff::init_alt_bn128_params();
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
char* errMsg = (char*) calloc(1024,1);
int err_status = 0;
uint32_t enc_len = 0;
unsigned t = 3, n = 4;
unsigned t = 32, n = 32;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, n);
REQUIRE(status == SGX_SUCCESS);
printf("gen_dkg_secret completed with status: %d %s \n", err_status, errMsg);
printf("\n Length: %d \n", enc_len);
/* printf("encr_dkg_secret: \n");
for ( int i = 0 ; i < enc_len; i++)
printf(" %d ", encrypted_dkg_secret[i]);*/
char* errMsg1 = (char*) calloc(1024,1);
char colon = ':';
char* secret_shares = (char*)calloc(DKG_MAX_SEALED_LEN, 1);
printf("BEFORE get_secret_shares\n");
status = get_secret_shares(eid, &err_status, errMsg1, encrypted_dkg_secret, enc_len, secret_shares, t, n);
char* secret_shares = (char*)calloc(DKG_BUFER_LENGTH, sizeof(char));
uint32_t dec_len = enc_len;
// status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret_shares, &dec_len);
status = get_secret_shares(eid, &err_status, errMsg1, encrypted_dkg_secret, &dec_len, secret_shares, t, n);
REQUIRE(status == SGX_SUCCESS);
printf("\nget_secret_shares: %d %s \n", err_status, errMsg1);
printf("\nget_secret_shares status: %d %s \n", err_status, errMsg1);
printf("secret shares %s \n\n", secret_shares);
std::vector <libff::alt_bn128_Fr> s_shares = SplitStringToFr( secret_shares, &colon);
std::vector <libff::alt_bn128_Fr> s_shares = SplitStringToFr( secret_shares, colon);
char* secret = (char*)calloc(DKG_MAX_SEALED_LEN, sizeof(char));
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, enc_len);
char* secret = (char*)calloc(DKG_BUFER_LENGTH, sizeof(char));
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, &dec_len);
REQUIRE(status == SGX_SUCCESS);
printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1);
printf("decrypted secret %s \n\n", secret);
//printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1);
signatures::Dkg dkg_obj(t,n);
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, &colon);
std::vector < libff::alt_bn128_Fr> s_shares_dkg = dkg_obj.SecretKeyContribution(SplitStringToFr((char*)secret, &colon));
printf("calculated secret: \n");
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
std::vector < libff::alt_bn128_Fr> s_shares_dkg = dkg_obj.SecretKeyContribution(SplitStringToFr((char*)secret, colon));
printf("calculated secret length %d : \n", s_shares_dkg.size());
for ( int i = 0; i < s_shares_dkg.size(); i++){
libff::alt_bn128_Fr cur_share = s_shares_dkg.at(i);
mpz_t(sshare);
......@@ -369,7 +411,7 @@ std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char*
mpz_clear(sshare);
}
// REQUIRE(s_shares == s_shares_dkg);
REQUIRE(s_shares == s_shares_dkg);
free(errMsg);
free(errMsg1);
......@@ -379,6 +421,154 @@ std::vector<libff::alt_bn128_Fr> SplitStringToFr(const char* koefs, const char*
sgx_destroy_enclave(eid);
}
TEST_CASE( "DKG public shares test", "[dkg-pub_shares]" ) {
//init_all();
libff::init_alt_bn128_params();
init_enclave();
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
char* errMsg = (char*) calloc(1024,1);
int err_status = 0;
uint32_t enc_len = 0;
unsigned t = 32, n = 32;
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, n);
REQUIRE(status == SGX_SUCCESS);
//printf("gen_dkg_public completed with status: %d %s \n", err_status, errMsg);
char* errMsg1 = (char*) calloc(1024,1);
char colon = ':';
char* public_shares = (char*)calloc(10000, 1);
status = get_public_shares(eid, &err_status, errMsg1, encrypted_dkg_secret, enc_len, public_shares, t, n);
REQUIRE(status == SGX_SUCCESS);
printf("\nget_public_shares status: %d error %s \n\n", err_status, errMsg1);
printf(" LEN: %d \n", strlen(public_shares));
printf(" result: %s \n", public_shares);
std::vector <std::string> G2_strings = SplitString( public_shares, ',');
std::vector <libff::alt_bn128_G2> pub_shares_G2;
for ( int i = 0; i < G2_strings.size(); i++){
std::vector <std::string> koef_str = SplitString(G2_strings.at(i).c_str(), ':');
libff::alt_bn128_G2 el = VectStringToG2(koef_str);
//std::cerr << "pub_share G2 " << i+1 << " : " << std::endl;
//el.print_coordinates();
pub_shares_G2.push_back(VectStringToG2(koef_str));
}
char* secret = (char*)calloc(DKG_MAX_SEALED_LEN, sizeof(char));
status = decrypt_dkg_secret(eid, &err_status, errMsg1, encrypted_dkg_secret, (uint8_t*)secret, &enc_len);
REQUIRE(status == SGX_SUCCESS);
printf("\ndecrypt_dkg_secret completed with status: %d %s \n", err_status, errMsg1);
signatures::Dkg dkg_obj(t,n);
std::vector < libff::alt_bn128_Fr> poly = SplitStringToFr((char*)secret, colon);
std::vector < libff::alt_bn128_G2> pub_shares_dkg = dkg_obj.VerificationVector(poly);
printf("calculated public shares (X.c0): \n");
for ( int i = 0; i < pub_shares_dkg.size(); i++){
libff::alt_bn128_G2 el = pub_shares_dkg.at(i);
el.to_affine_coordinates();
libff::alt_bn128_Fq x_c0_el = el.X.c0;
mpz_t x_c0;
mpz_init(x_c0);
x_c0_el.as_bigint().to_mpz(x_c0);
char arr[mpz_sizeinbase (x_c0, 10) + 2];
char* share_str = mpz_get_str(arr, 10, x_c0);
printf(" %s \n", share_str);
mpz_clear(x_c0);
}
bool res = (pub_shares_G2 == pub_shares_dkg);
REQUIRE( res == true);
free(errMsg);
free(errMsg1);
free(encrypted_dkg_secret);
free(public_shares);
sgx_destroy_enclave(eid);
}
TEST_CASE( "DKG encrypted secret shares test", "[dkg-encr_sshares]" ) {
// init_all();
init_enclave();
uint8_t *encrypted_key = (uint8_t *) calloc(BUF_LEN, 1);
char *errMsg = (char *)calloc(1024, 1);
char *result = (char *)calloc(130, 1);
int err_status = 0;
uint32_t enc_len = 0;
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly generated" << std::endl;
status = set_encrypted_dkg_poly(eid, &err_status, errMsg, encrypted_dkg_secret);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly set" << std::endl;
uint8_t *encr_pr_DHkey = (uint8_t *)calloc(1024, 1);
char *pub_key_x = (char *)calloc(1024, 1);
char *pub_key_y = (char *)calloc(1024, 1);
char *pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
status = get_encr_sshare(eid, &err_status, errMsg, encr_pr_DHkey, &enc_len, result,
pub_keyB, 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg);
std::cerr << "secret share is " << result << std::endl;
}
TEST_CASE( "DKG verification test", "[dkg-verify]" ) {
// init_all();
init_enclave();
uint8_t *encrypted_key = (uint8_t *) calloc(BUF_LEN, 1);
char *errMsg = (char *)calloc(1024, 1);
char *result = (char *)calloc(130, 1);
int err_status = 0;
uint32_t enc_len = 0;
uint8_t* encrypted_dkg_secret = (uint8_t*) calloc(DKG_MAX_SEALED_LEN, 1);
status = gen_dkg_secret (eid, &err_status, errMsg, encrypted_dkg_secret, &enc_len, 2);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly generated" << std::endl;
status = set_encrypted_dkg_poly(eid, &err_status, errMsg, encrypted_dkg_secret);
REQUIRE(status == SGX_SUCCESS);
std::cerr << " poly set" << std::endl;
uint8_t *encr_pr_DHkey = (uint8_t *)calloc(1024, 1);
char *pub_key_x = (char *)calloc(1024, 1);
char *pub_key_y = (char *)calloc(1024, 1);
char *pub_keyB = "c0152c48bf640449236036075d65898fded1e242c00acb45519ad5f788ea7cbf9a5df1559e7fc87932eee5478b1b9023de19df654395574a690843988c3ff475";
status = get_encr_sshare(eid, &err_status, errMsg, encr_pr_DHkey, &enc_len, result,
pub_keyB, 2, 2, 1);
REQUIRE(status == SGX_SUCCESS);
printf(" get_encr_sshare completed with status: %d %s \n", err_status, errMsg);
std::cerr << "secret share is " << result << std::endl;
}
TEST_CASE("ECDSA keygen and signature test", "[ecdsa_test]") {
......@@ -404,8 +594,8 @@ TEST_CASE("ECDSA keygen and signature test", "[ecdsa_test]") {
for ( int i = 0; i < 1024 ; i++)
printf("%u ", encr_pr_key[i]);*/
// char* hex = "4b688df40bcedbe641ddb16ff0a1842d9c67ea1c3bf63f3e0471baa664531d1a";
char* hex = "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
char* hex = "3F891FDA3704F0368DAB65FA81EBE616F4AA2A0854995DA4DC0B59D2CADBD64F";
// char* hex = "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db";
printf("hash length %d ", strlen(hex));
char* signature_r = (char *)calloc(1024, 1);
char* signature_s = (char *)calloc(1024, 1);
......@@ -440,22 +630,15 @@ TEST_CASE("Test test", "[test_test]") {
REQUIRE(status == SGX_SUCCESS);
//printf("\nwas pub_key_x %s: \n", pub_key_x);
//printf("\nwas pub_key_y %s: \n", pub_key_y);
//printf("\nencr priv_key %s: \n");
//for ( int i = 0; i < 1024 ; i++)
// printf("%u ", encr_pr_key[i]);
//printf( "haha");
//free(errMsg);
sgx_destroy_enclave(eid);
......@@ -510,10 +693,9 @@ using namespace std;
TEST_CASE("API test", "[api_test]") {
cerr << "API test started" << endl;
init_all();
//HttpServer httpserver(1025);
//SGXWalletServer s(httpserver,
// JSONRPC_SERVER_V1); // hybrid server (json-rpc 1.0 & 2.0)
// JSONRPC_SERVER_V2); // hybrid server (json-rpc 1.0 & 2.0)
// s.StartListening();
cerr << "Server inited" << endl;
HttpClient client("http://localhost:1025");
......@@ -522,9 +704,39 @@ TEST_CASE("API test", "[api_test]") {
cerr << "Client inited" << endl;
try {
// cout << c.generateECDSAKey("known_key1") << endl;
//cout<<c.getPublicECDSAKey("test_key");
cout << c.ecdsaSignMessageHash(16, "known_key1","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
// cout << c.generateECDSAKey("test_key2") << endl;
//cout<<c.getPublicECDSAKey("test_key1");
//cout << c.ecdsaSignMessageHash(16, "known_key1","0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db" );
// cout << c.blsSignMessageHash(TEST_BLS_KEY_NAME, "0x09c6137b97cdf159b9950f1492ee059d1e2b10eaf7d51f3a97d61f2eee2e81db", 2,2,1 );
// cout << c.generateDKGPoly("p2", 2);
//cout << c.getVerificationVector("polyy", 5, 5);
// cout << c.getSecretShare("p2",
// "505f55a38f9c064da744f217d1cb993a17705e9839801958cda7c884e08ab4dad7fd8d22953d3ac7f0913de24fd67d7ed36741141b8a3da152d7ba954b0f14e232d69c361f0bc9e05f1cf8ef387122dc1d2f7cee7b6cda3537fc9427c02328b01f02fd94ec933134dc795a642864f8cb41ae263e11abaf992e21fcf9be732deb",
// 2,2);
// cout << c.getSecretShare("p2",
// "669aa790e1c5f5199af82ab0b6f1965c382d23a2ebdda581454adba3fd082a30edab62b545f78f1e402ceef7340a0364a7046633d6151fe7e657d8b8a6352378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25e6e",
// 2,2);
// cout << c.generateDKGPoly("p3", 3);
// cout << c.getSecretShare("p3",
// "669aa790e1c5f5199af82ab0b6f1965c382d23a2ebdda581454adba3fd082a30edab62b545f78f1e402ceef7340a0364a7046633d6151fe7e657d8b8a6352378b3e6fdfe2633256ae1662fcd23466d02ead907b5d4366136341cea5e46f5a7bb67d897d6e35f619810238aa143c416f61c640ed214eb9c67a34c4a31b7d25e6e9d43f1c88581f53af993da1654c9f91829c1fe5344c4452ef8d2d8675c6a051c19029f6e4f82b035fb3552058cf22c5bbafd9e6456d579634987281765d130b0",
// 3,3);
std::string share_big0 = "501e364a6ea516f4812b013bcc150cbb435a2c465c9fd525951264969d8441a986798fd3317c1c3e60f868bb26c4cff837d9185f4be6015d8326437cb5b69480495859cd5a385430ece51252acdc234d8dbde75708b600ac50b2974e813ee26bd87140d88647fcc44df7262bbba24328e8ce622cd627a15b508ffa0db9ae81e0e110fab42cfe40da66b524218ca3c8e5aa3363fbcadef748dc3523a7ffb95b8f5d8141a5163db9f69d1ab223494ed71487c9bb032a74c08a222d897a5e49a617";
std::string share_big = "03f749e2fcc28021895d757ec16d1636784446f5effcd3096b045136d8ab02657b32adc577f421330b81f5b7063df3b08a0621a897df2584b9046ca416e50ecc27e8c3277e981f7e650f8640289be128eecf0105f89a20e5ffb164744c45cf191d627ce9ab6c44e2ef96f230f2a4de742ea43b6f74b56849138026610b2d965605ececba527048a0f29f46334b1cec1d23df036248b24eccca99057d24764acee66c1a3f2f44771d0d237bf9d18c4177277e3ce3dc4e83686a2647fce1565ee0";
std::string share = share_big.substr(0, 192);
//cout << c.DKGVerification("p2", "test_key1", share, 2, 2, 0);
Json::Value SecretShare;
SecretShare.append(share_big0);
SecretShare.append(share_big);
cout << c.CreateBLSPrivateKey( "test_bls_key","test_key1", SecretShare, 2, 2 );
} catch (JsonRpcException &e) {
cerr << e.what() << endl;
}
......
......@@ -6,6 +6,7 @@
*****************************************************************************/
#include <libff/algebra/curves/alt_bn128/alt_bn128_g1.hpp>
#include <libff/algebra/curves/alt_bn128/alt_bn128_g2.hpp>
#include <libff/algebra/curves/alt_bn128/alt_bn128_init.hpp>
namespace libff {
......@@ -166,6 +167,16 @@ void init_alt_bn128_params()
// window 22 is unbeaten in [34552892.20, inf]
alt_bn128_G1::fixed_base_exp_window_table.push_back(34552892);
alt_bn128_G2::G2_zero = alt_bn128_G2(alt_bn128_Fq2::zero(),
alt_bn128_Fq2::one(),
alt_bn128_Fq2::zero());
alt_bn128_G2::G2_one = alt_bn128_G2(alt_bn128_Fq2(alt_bn128_Fq("10857046999023057135944570762232829481370756359578518086990519993285655852781"),
alt_bn128_Fq("11559732032986387107991004021392285783925812861821192530917403151452391805634")),
alt_bn128_Fq2(alt_bn128_Fq("8495653923123431417604973247489272438418190587263600148770280649306958101930"),
alt_bn128_Fq("4082367875863433681332203403145435568316851327593401208105741076214120093531")),
alt_bn128_Fq2::one());
/* pairing parameters */
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment