int main(int argc, char *argv[]) { unsigned char* signature; unsigned int slen; RSA *private_key = NULL; BIO *priv_bio; unsigned char buffer[SIG_LEN]; if (argc < 3) { printf("Usage: %s image_file signed_file\n", argv[0]); exit(-1); } raw_file = fopen(argv[1], "r"); new_file = fopen(argv[2], "w"); if (!raw_file || !new_file) { fprintf(stderr, "Open file error\n"); exit(-1); } priv_bio = BIO_new_mem_buf(priv_key, -1); if(priv_bio == NULL) { fprintf(stderr, "priv_bio is null\n"); exit(-1); } private_key = PEM_read_bio_RSAPrivateKey(priv_bio, NULL, NULL, NULL); if(private_key == NULL) { fprintf(stderr, "private_key is null\n"); exit(-1); } signature = (unsigned char*) malloc(RSA_size(private_key)); if (calc_sha256() != 0) { fprintf(stderr, "calc_sha256 error\n"); exit(-1); } if(RSA_sign(NID_sha256, (unsigned char*) calc_hash, strlen(calc_hash), signature, &slen, private_key) != 1) { fprintf(stderr, "RSA_sign error\n"); } fwrite(signature, SIG_LEN, 1, new_file); int bytesRead = 0; while((bytesRead = fread(buffer, 1, SIG_LEN, raw_file))) { fwrite(buffer, bytesRead, 1, new_file); } /* free resouces */ return 0; }
int rsautl_verify(const char *pubKey, const char *inFile, const char *inSig) { int ret = SourceSec_PubKeyNotFound; FILE *fpPubKey = fopen(pubKey, "rt"); if(!fpPubKey) return ret; // Set file as public key source (must be in PEM format) RSA *rsa_pub = PEM_read_RSA_PUBKEY(fpPubKey, NULL, NULL, NULL); // Try to open signature file FILE *fpSigFile = fopen(inSig, "rb"); if(!fpSigFile) { fclose(fpPubKey); return SourceSec_SigNotFound; } // Calculate hash of input file unsigned char hash[SHA256_DIGEST_LENGTH]; calc_sha256(inFile, hash); // Get size of signature file fseek(fpSigFile, 0L, SEEK_END); size_t lenSig = ftell(fpSigFile); fseek(fpSigFile, 0L, SEEK_SET); // Signature size is suspiciously high, cancel process if(lenSig > 1024) { fclose(fpPubKey); fclose(fpSigFile); return SourceSec_SigTooBig; } // Read content into memory unsigned char *signature = (unsigned char*)malloc(lenSig); size_t rv = fread(signature, sizeof(unsigned char), lenSig, fpSigFile); // Check if full content was loaded if(rv != lenSig) { fclose(fpPubKey); fclose(fpSigFile); return SourceSec_SigIncomplete; } // Verify signature integrity ret = RSA_verify(NID_sha256, hash, SHA256_DIGEST_LENGTH, (const unsigned char*)signature, lenSig, rsa_pub); // Free resources fclose(fpPubKey); fclose(fpSigFile); free(signature); return ret; }
int main(int argc, char *argv[]) { FILE *fp; PE_FILE pe; unsigned char *data; size_t pesize = 0; if (argc < 2) { usage(); exit(1); } parse_options(argc, argv); if ((fp = fopen(argv[argc-1], "rb")) == NULL) EXIT_ERROR("file not found or unreadable"); pe_init(&pe, fp); fseek(pe.handle, 0, SEEK_END); pesize = ftell(pe.handle); rewind(pe.handle); data = (unsigned char *) xmalloc(pesize + 1); fread(data, pesize, 1, pe.handle); if (config.md5 || config.all) { char md5_sum[(MD5_DIGEST_LENGTH*2) + 1]; calc_md5(data, pesize, md5_sum); output("md5", md5_sum); } if (config.sha1 || config.all) { char sha1_sum[((SHA_DIGEST_LENGTH*2)+1)]; calc_sha1(data, pesize, sha1_sum); output("sha-1", sha1_sum); } if (config.sha256 || config.all) { char sha256_sum[((SHA256_DIGEST_LENGTH*2)+1)]; calc_sha256(data, pesize, sha256_sum); output("sha-256", sha256_sum); } pe_deinit(&pe); free(data); return 0; }
int main () { unsigned char hash[SHA256_DIGEST_LENGTH]; int i; calc_sha256("/home/quad/Benchmark/hi", hash); for(i=0; i<32; i++) { printf("%02x", hash[i]); } }
static int lua_calc_sha256(lua_State *L) { if (lua_gettop(L) != 1) { return 0; } if (lua_type(L, 1) != LUA_TSTRING) { return 0; } size_t size; const char* text = lua_tolstring(L, 1, &size); unsigned char sha256sum[32]; calc_sha256(sha256sum, text, size); lua_pushlstring(L, sha256sum, 32); return 1; }
cell_t dgst_sha256(IPluginContext *pContext, const cell_t *params) { char *path; char buffer[PLATFORM_MAX_PATH]; // Get input file to calculate pContext->LocalToString(params[3], &path); unsigned char hash[SHA256_DIGEST_LENGTH]; char output[65]; // Open file and calculate hash smutils->BuildPath(Path_Game, buffer, PLATFORM_MAX_PATH, path); if(calc_sha256(buffer, hash) == -1) return -1; // Convert digest into human readable hex string sha256_hash_string(hash, output); // Set return buffer pContext->StringToLocalUTF8(params[1], params[2], output, NULL); return 0; }
void zktest() { /* # Given the public key of B (remote_pub), shows that the shared secret # between A and B was generated by A. # Returns zero-knowledge proof of shared Diffie-Hellman secret between A & B. def prove_shared_secret(self, remote_pub): G = self.G; prover_pub = self.public; phi = self. P - 1; secret = self.get_shared_secret(remote_pub) # Random key in the group Z_q randKey = DiffieHellman() # random secret commit1 = randKey.public commit2 = randKey.get_shared_secret(remote_pub) */ void fdifference_backwards(uint64_t *out, const uint64_t *in); // output = in - output void fmul(uint64_t *output,const uint64_t *in,const uint64_t *in2); void fcontract(uint8_t *output, const uint64_t *input); void fexpand(uint64_t *output, const uint8_t *in); bits256 curve25519(bits256,bits256); static uint8_t _basepoint[32] = {9}; bits320 randsecret,challenge,product,response,selfsecret,secret; bits256 remote_pub,basepoint,remote_secret,randkey,commit1,commit2,_secret,tmp,buf[8]; int32_t n = 0; tmp = GENESIS_PRIVKEY; _secret = curve25519(tmp,remote_pub); fexpand(secret.ulongs,_secret.bytes); randombytes(randkey.bytes,sizeof(randkey)), randkey.bytes[0] &= 248, randkey.bytes[31] &= 127, randkey.bytes[31] |= 64; randombytes(remote_secret.bytes,sizeof(remote_secret)), remote_secret.bytes[0] &= 248, remote_secret.bytes[31] &= 127, remote_secret.bytes[31] |= 64; memcpy(basepoint.bytes,_basepoint,sizeof(basepoint)); remote_pub = curve25519(remote_secret,basepoint); fexpand(randsecret.ulongs,randkey.bytes); curve25519_donna(commit1.bytes,randkey.bytes,_basepoint); commit2 = curve25519(randkey,remote_pub); /* # shift and hash concat = str(G) + str(prover_pub) + str(remote_pub) + str(secret) + str(commit1) + str(commit2) h = hashlib.md5() h.update(concat.encode("utf-8")) challenge = int(h.hexdigest(), 16) product = (self.secret * challenge) % phi response = (randKey.secret - product) % phi return (secret, challenge, response)*/ buf[n++] = GENESIS_PRIVKEY, buf[n++] = GENESIS_PUBKEY; buf[n++] = remote_pub, buf[n++] = _secret, buf[n++] = commit1, buf[n++] = commit2; memset(challenge.bytes,0,sizeof(challenge)); calc_sha256(0,tmp.bytes,buf[0].bytes,n*sizeof(buf[0])); fexpand(challenge.ulongs,tmp.bytes); tmp = GENESIS_PRIVKEY; fexpand(selfsecret.ulongs,tmp.bytes); fmul(product.ulongs,selfsecret.ulongs,challenge.ulongs); response = product; fdifference_backwards(product.ulongs,randsecret.ulongs); /* # Verifies proof generated above. Verifier c is showing that # shared secret between A and B was generated by A. # returns 0 if if verification fails; returns shared secret otherwise def verify_shared_secret(self, prover_pub, remote_pub, secret, challenge, response): P = self.P; G = self.G ; public = self.public # g^r * (a's public key)^challenge commit1 = (pow(G, response, P) * pow(public, challenge, P)) % P # (b's public key)^response * (secret)^challenge commit2 = (pow(remote_pub, response, P) * pow(secret, challenge, P)) % P */ bits256 _commit1b,_commit2b,_tmp2,_challenge,_response; bits320 Tmp,Tmp2,commit2b; fcontract(_challenge.bytes,challenge.ulongs); fcontract(_response.bytes,response.ulongs); tmp = curve25519(_secret,_challenge); _tmp2 = curve25519(remote_pub,_response); fexpand(Tmp.ulongs,tmp.bytes); fexpand(Tmp2.ulongs,_tmp2.bytes); fmul(commit2b.ulongs,Tmp.ulongs,Tmp2.ulongs); fcontract(_commit2b.bytes,commit2b.ulongs); printf("commits %llx %llx vs %llx %llx\n",commit1.txid,commit2.txid,_commit1b.txid,_commit2b.txid); /* # Shift and hash hasher = hashlib.md5() concat = str(G) + str(prover_pub) + str(remote_pub) + str(secret) + str(commit1) + str(commit2) hasher.update(concat.encode("utf-8")) check = int(hasher.hexdigest(), 16) if challenge == check: return secret else: return 0 def main(): a = DiffieHellman() b = DiffieHellman() results = a.prove_shared_secret(b.public) assert a.verify_shared_secret(a.public, b.public, results[0], \ results[1], results[2]) */ }
// If encr, encrypts, otherwise decrypts // Lua arguments: // string text (may be cleartext or encrypted text) // string password // sha256(password) is used as key for twofish // returns cleartext or encrypted text static int twofish_twoways(lua_State *L, int encr) { if (lua_gettop(L) != 2) { return 0; } if (lua_type(L, 1) != LUA_TSTRING) { return 0; } if (lua_type(L, 2) != LUA_TSTRING) { return 0; } size_t text_s; const char* text = lua_tolstring(L, 1, &text_s); size_t password_s; const char* password = lua_tolstring(L, 2, &password_s); // sha256 unsigned char sha256sum[32]; calc_sha256(sha256sum, password, password_s); // twofish - prepare key u32 *S; u32 K[40]; int k; keySched(sha256sum, 256, &S, K, &k); u32 QF[4][256]; fullKey(S, k, QF); free(S); // allocate output string // nonce is stored in the beginning int result_bytes; if (encr) { result_bytes = text_s + BLOCK_BYTES; } else { result_bytes = text_s - BLOCK_BYTES; } if (result_bytes <= 0) { return 0; } char* result = malloc(result_bytes); // twofish - make nonce (~IV) for CTR mode const char* nonce; const char* input; // points to first block of data char* output; // points to first block of data int normal_blocks; if (encr) { char* nonce_mut = result; nonce = nonce_mut; get_random_bytes(nonce_mut, BLOCK_BYTES); input = text; output = result + BLOCK_BYTES; normal_blocks = text_s / BLOCK_BYTES; } else { nonce = text; input = text + BLOCK_BYTES; output = result; normal_blocks = (text_s / BLOCK_BYTES) - 1; } int i; for (i = 0; i < normal_blocks; i++) { const char* b_in = input + i * BLOCK_BYTES; char* b_out = output + i * BLOCK_BYTES; memcpy(b_out, nonce, BLOCK_BYTES); xor_ctr(b_out, i); encrypt(K, QF, b_out); xor_block(b_out, b_in, BLOCK_BYTES); } int last_block_size = text_s % BLOCK_BYTES; if (last_block_size) { const char* b_in = input + normal_blocks * BLOCK_BYTES; char* b_out = output + normal_blocks * BLOCK_BYTES; char block[BLOCK_BYTES]; memcpy(block, nonce, BLOCK_BYTES); xor_ctr(block, normal_blocks); encrypt(K, QF, block); memcpy(b_out, block, last_block_size); xor_block(b_out, b_in, last_block_size); } lua_pushlstring(L, result, result_bytes); free(result); return 1; }
int mediafirefs_flush(const char *path, struct fuse_file_info *file_info) { printf("FUNCTION: flush. path: %s\n", path); FILE *fh; char *file_name; char *dir_name; const char *folder_key; char *upload_key; char *temp1; char *temp2; int retval; struct mediafirefs_context_private *ctx; struct mediafirefs_openfile *openfile; struct mfconn_upload_check_result check_result; unsigned char bhash[SHA256_DIGEST_LENGTH]; char *hash; uint64_t size; openfile = (struct mediafirefs_openfile *)(uintptr_t) file_info->fh; if (openfile->is_flushed) { return 0; } ctx = fuse_get_context()->private_data; // zero out check result to prevent spurious results later memset(&check_result,0,sizeof(check_result)); pthread_mutex_lock(&(ctx->mutex)); if (openfile->is_readonly) { /* nothing to do here */ pthread_mutex_unlock(&(ctx->mutex)); return 0; } // if the file only exists locally, an initial upload has to be done if (openfile->is_local) { // pass a copy because dirname and basename may modify their argument temp1 = strdup(openfile->path); file_name = basename(temp1); temp2 = strdup(openfile->path); dir_name = dirname(temp2); fh = fdopen(openfile->fd, "r"); rewind(fh); folder_key = folder_tree_path_get_key(ctx->tree, ctx->conn, dir_name); size = -1; retval = calc_sha256(fh, bhash, &size); rewind(fh); if (retval != 0) { fprintf(stderr, "failed to calculate hash\n"); free(temp1); free(temp2); pthread_mutex_unlock(&(ctx->mutex)); return -EACCES; } hash = binary2hex(bhash, SHA256_DIGEST_LENGTH); retval = mfconn_api_upload_check(ctx->conn, file_name, hash, size, folder_key, &check_result); if (retval != 0) { free(temp1); free(temp2); free(hash); fprintf(stderr, "mfconn_api_upload_check failed\n"); fprintf(stderr, "file_name: %s\n",file_name); fprintf(stderr, "hash: %s\n",hash); fprintf(stderr, "size: %jd\n",size); fprintf(stderr, "folder_key: %s\n",folder_key); pthread_mutex_unlock(&(ctx->mutex)); return -EACCES; } if (check_result.hash_exists) { // hash exists, so use upload/instant retval = mfconn_api_upload_instant(ctx->conn, file_name, hash, size, folder_key); free(temp1); free(temp2); free(hash); if (retval != 0) { fprintf(stderr, "mfconn_api_upload_instant failed\n"); pthread_mutex_unlock(&(ctx->mutex)); return -EACCES; } } else { // hash does not exist, so do full upload upload_key = NULL; retval = mfconn_api_upload_simple(ctx->conn, folder_key, fh, file_name, true, &upload_key); free(temp1); free(temp2); free(hash); if (retval != 0 || upload_key == NULL) { fprintf(stderr, "mfconn_api_upload_simple failed\n"); fprintf(stderr, "file_name: %s\n",file_name); fprintf(stderr, "hash: %s\n",hash); fprintf(stderr, "size: %jd\n",size); fprintf(stderr, "folder_key: %s\n",folder_key); pthread_mutex_unlock(&(ctx->mutex)); return -EACCES; } // poll for completion retval = mfconn_upload_poll_for_completion(ctx->conn, upload_key); free(upload_key); if (retval != 0) { fprintf(stderr, "mfconn_upload_poll_for_completion failed\n"); pthread_mutex_unlock(&(ctx->mutex)); return -1; } else { account_add_state_flags(ctx->account, ACCOUNT_FLAG_DIRTY_SIZE); } } folder_tree_update(ctx->tree, ctx->conn, true); openfile->is_flushed = true; pthread_mutex_unlock(&(ctx->mutex)); return 0; } // the file was not opened readonly and also existed on the remote // thus, we have to check whether any changes were made and if yes, upload // a patch retval = folder_tree_upload_patch(ctx->tree, ctx->conn, openfile->path); if (retval != 0) { fprintf(stderr, "folder_tree_upload_patch failed\n"); pthread_mutex_unlock(&(ctx->mutex)); return -EACCES; } else { account_add_state_flags(ctx->account, ACCOUNT_FLAG_DIRTY_SIZE); } folder_tree_update(ctx->tree, ctx->conn, true); openfile->is_flushed = true; pthread_mutex_unlock(&(ctx->mutex)); return 0; }
/* Application entry */ int SGX_CDECL main(int argc, char *argv[]) { sgx_status_t sgx_ret = SGX_SUCCESS; sgx_status_t enclave_ret = SGX_SUCCESS; uint32_t sealed_log_size = 1024; uint8_t sealed_log[1024] = {0}; sgx_sealed_data_t * sealed_data = 0; (void)(argc); (void)(argv); /* Initialize the enclave */ if(initialize_enclave() < 0){ printf("Enter a character before exit ...\n"); getchar(); return -1; } // SHA-256 test case comes from // https://tools.ietf.org/html/rfc4634 // TEST1 const char* str = "abc"; size_t len = strlen(str); uint8_t * output_hash = (uint8_t *) malloc (32 + 1); printf("[+] sha256 input string is %s\n", str); printf("[+] Expected SHA256 hash: %s\n", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"); sgx_ret = calc_sha256(global_eid, &enclave_ret, (const uint8_t *) str, len, output_hash); if(sgx_ret != SGX_SUCCESS) { print_error_message(sgx_ret); return -1; } if(enclave_ret != SGX_SUCCESS) { print_error_message(enclave_ret); return -1; } printf("[+] SHA256 result is "); int i; for(i = 0; i < 32; i ++) { printf("%02x", output_hash[i]); } printf("\n"); printf("[+] calc_sha256 success ...\n"); // AES-GCM-128 test case comes from // http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf // Test case 2 printf("[+] Starting aes-gcm-128 encrypt calculation\n"); uint8_t aes_gcm_plaintext[16] = {0}; uint8_t aes_gcm_key[16] = {0}; uint8_t aes_gcm_iv[12] = {0}; uint8_t aes_gcm_ciphertext[16] = {0}; uint8_t aes_gcm_mac[16] = {0}; printf("[+] aes-gcm-128 args prepared!\n"); printf("[+] aes-gcm-128 expected ciphertext: %s\n", "0388dace60b6a392f328c2b971b2fe78"); sgx_ret = aes_gcm_128_encrypt(global_eid, &enclave_ret, aes_gcm_key, aes_gcm_plaintext, 16, aes_gcm_iv, aes_gcm_ciphertext, aes_gcm_mac); printf("[+] aes-gcm-128 returned from enclave!\n"); if(sgx_ret != SGX_SUCCESS) { print_error_message(sgx_ret); return -1; } if(enclave_ret != SGX_SUCCESS) { print_error_message(enclave_ret); return -1; } printf("[+] aes-gcm-128 ciphertext is: "); for(i = 0; i < 16; i ++) { printf("%02x", aes_gcm_ciphertext[i]); } printf("\n"); printf("[+] aes-gcm-128 result mac is: "); for(i = 0; i < 16; i ++) { printf("%02x", aes_gcm_mac[i]); } printf("\n"); printf("[+] Starting aes-gcm-128 decrypt calculation\n"); printf("[+] aes-gcm-128 expected plaintext: %s", aes_gcm_plaintext); uint8_t aes_gcm_decrypted_text[16] = {0}; sgx_ret = aes_gcm_128_decrypt(global_eid, &enclave_ret, aes_gcm_key, aes_gcm_ciphertext, 16, aes_gcm_iv, aes_gcm_mac, aes_gcm_decrypted_text); if(sgx_ret != SGX_SUCCESS) { print_error_message(sgx_ret); return -1; } if(enclave_ret != SGX_SUCCESS) { print_error_message(enclave_ret); return -1; } printf("[+] aes-gcm-128 decrypted plaintext is: "); for(i = 0; i < 16; i ++) { printf("%02x", aes_gcm_decrypted_text[i]); } printf("\n"); printf("[+] aes-gcm-128 decrypt complete \n"); // AES-CMAC test case comes from // https://tools.ietf.org/html/rfc4493 // Example 3 printf("[+] Starting aes-cmac test \n"); printf("[+] aes-cmac expected digest: %s\n", "51f0bebf7e3b9d92fc49741779363cfe"); uint8_t cmac_key[] = { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c }; uint8_t cmac_msg[] = { 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10 }; uint8_t cmac_result[16] = {0}; sgx_ret = aes_cmac(global_eid, &enclave_ret, cmac_msg, sizeof(cmac_msg), cmac_key, cmac_result); if(sgx_ret != SGX_SUCCESS) { print_error_message(sgx_ret); return -1; } if(enclave_ret != SGX_SUCCESS) { print_error_message(enclave_ret); return -1; } printf("[+] aes-cmac result is: "); for(i = 0; i < 16; i ++){ printf("%02x", cmac_result[i]); } printf("\n"); /* Destroy the enclave */ sgx_destroy_enclave(global_eid); return 0; }