EVP_PKEY* SecurityKey::getEVP() const { EVP_PKEY* ret = EVP_PKEY_new(); FILE * pkey_file = fopen(file.getPath().c_str(), "r"); switch (type) { case KEY_PRIVATE: { ret = PEM_read_PrivateKey(pkey_file, &ret, NULL, NULL); break; } case KEY_PUBLIC: { ret = PEM_read_PUBKEY(pkey_file, &ret, NULL, NULL); break; } default: ret = NULL; break; } fclose(pkey_file); return ret; }
int evp_open_public(EVP_PKEY** evp, const char* path, password_callback callback) { FILE* path_fp; password_request req; path_fp = fopen(path, "rb"); if (path_fp == NULL) { return 0; } req.path = path; req.callback = callback; *evp = PEM_read_PUBKEY(path_fp, NULL, pass_cb, &req); if (*evp == NULL) { fclose(path_fp); return 0; } fclose(path_fp); return 1; }
static EVP_PKEY * read_public_key (const char *keyfile, GError **error) { EVP_PKEY *ret = NULL; FILE *infile; infile = fopen (keyfile, "r"); if (infile == NULL) { g_set_error_literal (error, G_FILE_ERROR, g_file_error_from_errno (errno), strerror (errno)); } else { ret = PEM_read_PUBKEY (infile, NULL, /* optional pre-allocated key struct */ NULL, /* optional password callback */ NULL /* data for callback */); if (ret == NULL) g_set_error_literal (error, CRYPT_ERROR, CRYPT_ERROR_READ_KEY, "Error reading the public key"); fclose (infile); } return ret; }
static bool verifyRSASignature(const unsigned char *originalMessage, unsigned int messageLength, const unsigned char *signature, unsigned int sigLength) { if(nullptr == originalMessage) { return errorMessage(_("Message is empty")); } if(nullptr == signature) { return errorMessage(_("Signature is empty")); } const char *settingsPath = CPLGetConfigOption("NGS_SETTINGS_PATH", nullptr); std::string keyFilePath = File::formFileName(settingsPath, KEY_FILE, ""); FILE *file = VSIFOpen( keyFilePath.c_str(), "r" ); if( file == nullptr ) { return errorMessage(_("Failed open file %s"), keyFilePath.c_str()); } EVP_PKEY *evp_pubkey = PEM_read_PUBKEY(file, nullptr, nullptr, nullptr); VSIFClose( file ); if (!evp_pubkey) { return errorMessage(_("Failed PEM_read_PUBKEY")); } EVP_MD_CTX *ctx = EVP_MD_CTX_create(); if (!ctx) { EVP_PKEY_free(evp_pubkey); return errorMessage(_("Failed PEM_read_PUBKEY")); } if(!EVP_VerifyInit(ctx, EVP_sha256())) { EVP_MD_CTX_destroy(ctx); EVP_PKEY_free(evp_pubkey); return errorMessage(_("Failed EVP_VerifyInit")); } if(!EVP_VerifyUpdate(ctx, originalMessage, messageLength)) { EVP_MD_CTX_destroy(ctx); EVP_PKEY_free(evp_pubkey); return errorMessage(_("Failed EVP_VerifyUpdate")); } int result = EVP_VerifyFinal(ctx, signature, sigLength, evp_pubkey); EVP_MD_CTX_destroy(ctx); EVP_PKEY_free(evp_pubkey); outMessage(result == 1 ? COD_SUCCESS : COD_UNEXPECTED_ERROR, "Signature is %s", result == 1 ? "valid" : "invalid"); return result == 1; }
EVP_PKEY * crypto_load_key(const char *key, const bool is_private) { EVP_PKEY *pkey; char *tmpname; int keyfd; FILE *keyfp; mode_t oldumask; /* create tempfile and store key into it */ tmpname = strdup("/tmp/chaosvpn.tmp.XXXXXX"); oldumask = umask(077); keyfd = mkstemp(tmpname); umask(oldumask); if (keyfd == -1) { free(tmpname); log_err("crypto_load_key: error creating tempfile\n"); return NULL; } unlink(tmpname); free(tmpname); if (write(keyfd, key, strlen(key)) != strlen(key)) { close(keyfd); log_err("crypto_load_key: tempfile write error\n"); return NULL; } keyfp = fdopen(keyfd, "rw"); if (keyfp == NULL) { close(keyfd); log_err("crypto_load_key: tempfile fdopen() failed\n"); return NULL; } fseek(keyfp, 0, SEEK_SET); /* read and parse key */ if (is_private) { pkey = PEM_read_PrivateKey(keyfp, NULL, NULL, NULL); } else { pkey = PEM_read_PUBKEY(keyfp, NULL, NULL, NULL); } fclose(keyfp); close(keyfd); if (pkey == NULL) { log_err("crypto_load_key: loading and parsing key failed\n"); ERR_print_errors_fp(stderr); return NULL; } return pkey; }
int RSAfileToPubKey(EVP_PKEY** pubKey, char* fname){ FILE * f = NULL; if(pubKey == NULL || fname == NULL || strlen(fname)<1) return 0; f = fopen(fname, "r"); if (f == NULL) return 0; *pubKey = EVP_PKEY_new(); if(*pubKey == NULL){ printf("ERR EVP_PKEY_new\n"); return 0; } PEM_read_PUBKEY(f, pubKey, NULL, NULL); fclose(f); if(*pubKey == NULL) return 0; return 1; }
EVP_PKEY* retrieve_pubkey(const char* file_name) { FILE* file; EVP_PKEY* pubkey; file = fopen(file_name, "r"); if(file == NULL){ fprintf(stderr, "Error: cannot read PEM file '%s'\n", file_name); return NULL; } pubkey = PEM_read_PUBKEY(file, NULL, NULL, NULL); fclose(file); if(pubkey == NULL){ fprintf(stderr, "Error: PEM_read_PUBKEY returned NULL\n"); return NULL; } return pubkey; }
EVP_PKEY * load_public_key( const char * fname ) { FILE * fp; EVP_PKEY * pkey; fp = fopen (fname, "r"); if (fp == NULL) return NULL; pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); fclose (fp); if (pkey == NULL) ERR_print_errors_fp (stderr); return pkey; }
int load_and_print_pubkey(FILE* pemFile, int version) { assert(pemFile); EVP_PKEY* pubkey = PEM_read_PUBKEY(pemFile, NULL, NULL, NULL); if (!pubkey) { fprintf(stderr, "error: PEM_read_PUBKEY() failed.\n"); return 1; } if (EVP_PKEY_type(pubkey->type) != EVP_PKEY_EC) { fprintf(stderr, "error: PEM does not contain an EC key.\n"); EVP_PKEY_free(pubkey); return 1; } int result = extract_and_print_eckey(pubkey, version); EVP_PKEY_free(pubkey); return result; }
extern void * crypto_read_public_key(const char *path) { FILE *fp = NULL; EVP_PKEY *pk = NULL; xassert(path != NULL); if ((fp = fopen(path, "r")) == NULL) return NULL; if (!PEM_read_PUBKEY(fp, &pk, NULL, NULL)) { fclose(fp); return NULL; } fclose(fp); return (void *) pk; }
EVP_PKEY * isns_dsasig_load_public_pem(isns_security_t *ctx, const char *filename) { EVP_PKEY *pkey; FILE *fp; if (!(fp = fopen(filename, "r"))) { isns_error("Unable to open DSA keyfile %s: %m\n", filename); return 0; } pkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); if (pkey == NULL) { isns_dsasig_report_errors("Error loading DSA public key", isns_error); } fclose(fp); return pkey; }
void SWU_CryptoInit_PEM(char *configuration_dir, char *pem_file) { OpenSSL_add_all_digests(); ERR_load_CRYPTO_strings(); char pem_file_name[1024] = ""; strcat(pem_file_name, configuration_dir); strcat(pem_file_name, "/"); strcat(pem_file_name, pem_file); FILE *pubKeyFile = fopen(pem_file_name, "r"); if (pubKeyFile == NULL) { printf("Error: Can't open PEM file %s\n", pem_file); exit(1); } EVP_PKEY *gpPubKey = PEM_read_PUBKEY(pubKeyFile, NULL, NULL, NULL); _gpPubKey = gpPubKey; if (_gpPubKey == NULL) { printf("Error: Can't read PEM signature from file %s\n", pem_file); fclose(pubKeyFile); exit(1); } fclose(pubKeyFile); ERR_clear_error(); }
uint32 CRegProtocol::GetPublicKey(char *Name, EVP_PKEY **key) { TU_RET err; FILE *fp; err = TU_ERROR_CRYPTO_FAILED; fp = fopen(NAME_BUF, "r"); if(!fp) { err = TU_ERROR_FILEOPEN; goto EXIT; } if(!(*key = PEM_read_PUBKEY(fp, NULL, NULL, NULL))) { ERR_print_errors_fp(stdout); //If we can't read the Public key, try reading the pvt key. //The above function might give an error if we use it to //read a private key file rewind(fp); if(!(*key = PEM_read_PrivateKey(fp, NULL, NULL, NULL))) { ERR_print_errors_fp(stdout); goto EXIT_FILE; } } err = TU_SUCCESS; EXIT_FILE: if(fp) fclose(fp); EXIT: return err; }
int generate_rsa(void) { int iRet = EXIT_SUCCESS; EVP_PKEY* pPrivKey = NULL; EVP_PKEY* pPubKey = NULL; FILE* pFile = NULL; const EVP_CIPHER* pCipher = NULL; init_openssl(); pPrivKey = create_rsa_key(); pPubKey = create_rsa_key(); if(pPrivKey && pPubKey) {/* Save the keys */ if((pFile = fopen("privkey.pem","wt")) && (pCipher = EVP_aes_256_cbc())) { if(!PEM_write_PrivateKey(pFile,pPrivKey,pCipher, (unsigned char*)pcszPassphrase, (int)strlen(pcszPassphrase),NULL,NULL)) { fprintf(stderr,"PEM_write_PrivateKey failed.\n"); handle_openssl_error(); iRet = EXIT_FAILURE; } fclose(pFile); pFile = NULL; if(iRet == EXIT_SUCCESS) { if((pFile = fopen("pubkey.pem","wt")) && PEM_write_PUBKEY(pFile,pPubKey)) fprintf(stderr,"Both keys saved.\n"); else { handle_openssl_error(); iRet = EXIT_FAILURE; } if(pFile) { fclose(pFile); pFile = NULL; } } } else { fprintf(stderr,"Cannot create \"privkey.pem\".\n"); handle_openssl_error(); iRet = EXIT_FAILURE; if(pFile) { fclose(pFile); pFile = NULL; } } if(iRet == EXIT_SUCCESS) {/* Read the keys */ EVP_PKEY_free(pPrivKey); pPrivKey = NULL; EVP_PKEY_free(pPubKey); pPubKey = NULL; if((pFile = fopen("privkey.pem","rt")) && (pPrivKey = PEM_read_PrivateKey(pFile,NULL,passwd_callback,(void*)pcszPassphrase))) { fprintf(stderr,"Private key read.\n"); } else { fprintf(stderr,"Cannot read \"privkey.pem\".\n"); handle_openssl_error(); iRet = EXIT_FAILURE; } if(pFile) { fclose(pFile); pFile = NULL; } if((pFile = fopen("pubkey.pem","rt")) && (pPubKey = PEM_read_PUBKEY(pFile,NULL,NULL,NULL))) { fprintf(stderr,"Public key read.\n"); } else { fprintf(stderr,"Cannot read \"pubkey.pem\".\n"); handle_openssl_error(); iRet = EXIT_FAILURE; } char msg[2048/8]; // Get rid of the newline int session_seed = rand(); sprintf(msg, "%d", session_seed); // Encrypt the message } } if(pPrivKey) { EVP_PKEY_free(pPrivKey); pPrivKey = NULL; } if(pPubKey) { EVP_PKEY_free(pPubKey); pPubKey = NULL; } cleanup_openssl(); return iRet; }
int main(int argc, char * argv[]) { unsigned char st[BUFFER_SIZE]; // sifrovany text unsigned char * key; // klic pro sifrovani unsigned char iv[EVP_MAX_IV_LENGTH]; // inicializacni vektor unsigned char readBuffer[BUFFER_SIZE]; const char * filename = argv[1]; const char * outfilename = argv[3]; const char * keyfile = argv[2]; if(argc != 4){ fprintf(stderr, "Error shoud be: pem soubor_s_daty soubor_s_verejnym_klicem vystupni_soubor \n" ); exit(1); } int stLength = 0; int tmpLength = 0; int readlen = 0; int keyLength = 0; FILE * fplainin = fopen(filename,"rb"); FILE * fcyphedout = fopen(outfilename,"w+b"); EVP_PKEY * pubkey; EVP_CIPHER_CTX ctx; FILE * fpubkey = fopen(keyfile,"rb"); pubkey = PEM_read_PUBKEY(fpubkey, NULL, NULL, NULL); //No password protection of the key itself fclose(fpubkey); // printf("Reading pubkey\n"); //EVP_PKEY_CTX * ctx = EVP_PKEY_CTX_new(pubkey,NULL); keyLength = EVP_PKEY_size(pubkey); key = (unsigned char*) malloc(keyLength); EVP_SealInit(&ctx, EVP_des_cbc(), &key, &keyLength, iv, &pubkey, 1); /* printf("Key length: %d\n",keyLength); for(int i=0 ; i < keyLength ; i++){ printf("%x",key[i]); } printf("\n"); */ // printf("Seal Init\n"); int nid = EVP_CIPHER_CTX_nid(&ctx); fwrite(&nid,sizeof(nid),1,fcyphedout); writeData(fcyphedout,(void*)iv,EVP_MAX_IV_LENGTH); fwrite(&keyLength,sizeof(keyLength),1,fcyphedout); writeData(fcyphedout,(void*)key,keyLength); printf("NID: %d\n",nid); while((readlen =fread(readBuffer,1,BUFFER_SIZE,fplainin))!=0){ EVP_SealUpdate(&ctx, st,&stLength, readBuffer, readlen); fwrite(st,1,stLength,fcyphedout); // printf("Seal update\n"); } EVP_SealFinal(&ctx, st, &tmpLength); //printf("Seal final\n"); fwrite(st,1,tmpLength,fcyphedout); fclose(fplainin); fclose(fcyphedout); /* Encrypting end */ //EVP_CIPHER_CTX ctx; free(key); }
int read_key_pem(FILE *fp, PyObject **py_private_key_ndn, PyObject **py_public_key_ndn, PyObject **py_public_key_digest, int *public_key_digest_len, char *password) { struct ndn_pkey *private_key = NULL; PyObject *py_private_key = NULL, *py_public_key = NULL; unsigned long err, reason; fpos_t fpos; int r; int public_only; r = fgetpos(fp, &fpos); JUMP_IF_NEG(r, errno_error); private_key = (struct ndn_pkey *)PEM_read_PrivateKey(fp, NULL, NULL, password); if (private_key) { public_only = 0; goto success; } err = ERR_get_error(); reason = ERR_GET_REASON(err); /* 108 was meaning that start line isn't recognized */ if (reason == 108) { r = fsetpos(fp, &fpos); JUMP_IF_NEG(r, errno_error); private_key = (struct ndn_pkey *)PEM_read_PUBKEY (fp, NULL, NULL, NULL); if (private_key) { public_only = 1; goto success; } err = ERR_get_error(); reason = ERR_GET_REASON(err); } { char buf[256]; ERR_error_string_n(err, buf, sizeof(buf)); PyErr_Format(g_PyExc_NDNKeyError, "Unable to read Private Key: %s", buf); goto error; } success: r = ndn_keypair(public_only, private_key, py_private_key_ndn, py_public_key_ndn); JUMP_IF_NEG(r, error); r = create_public_key_digest(private_key, py_public_key_digest, public_key_digest_len); JUMP_IF_NEG(r, error); return 0; errno_error: PyErr_SetFromErrno(PyExc_IOError); error: Py_XDECREF(py_private_key); Py_XDECREF(py_public_key); if (private_key) EVP_PKEY_free((EVP_PKEY *)private_key); return -1; }
struct uwsgi_subscribe_node *uwsgi_add_subscribe_node(struct uwsgi_subscribe_slot **slot, struct uwsgi_subscribe_req *usr) { struct uwsgi_subscribe_slot *current_slot = uwsgi_get_subscribe_slot(slot, usr->key, usr->keylen), *old_slot = NULL, *a_slot; struct uwsgi_subscribe_node *node, *old_node = NULL; if (usr->address_len > 0xff || usr->address_len == 0) return NULL; #ifdef UWSGI_SSL if (uwsgi.subscriptions_sign_check_dir) { if (usr->sign_len == 0 || usr->base_len == 0) return NULL; } #endif if (current_slot) { #ifdef UWSGI_SSL if (uwsgi.subscriptions_sign_check_dir && !uwsgi_subscription_sign_check(current_slot, usr)) { return NULL; } #endif node = current_slot->nodes; while (node) { if (!uwsgi_strncmp(node->name, node->len, usr->address, usr->address_len)) { #ifdef UWSGI_SSL // this should avoid sending sniffed packets... if (uwsgi.subscriptions_sign_check_dir && usr->unix_check <= node->unix_check) { uwsgi_log("[uwsgi-subscription for pid %d] invalid (sniffed ?) packet sent for slot: %.*s node: %.*s unix_check: %lu\n", (int) uwsgi.mypid, usr->keylen, usr->key, usr->address_len, usr->address, (unsigned long) usr->unix_check); return NULL; } #endif // remove death mark and update cores and load node->death_mark = 0; node->last_check = uwsgi_now(); node->cores = usr->cores; node->load = usr->load; node->weight = usr->weight; if (!node->weight) node->weight = 1; node->last_requests = 0; return node; } old_node = node; node = node->next; } #ifdef UWSGI_SSL if (uwsgi.subscriptions_sign_check_dir && usr->unix_check < (uwsgi_now() - (time_t) uwsgi.subscriptions_sign_check_tolerance)) { uwsgi_log("[uwsgi-subscription for pid %d] invalid (sniffed ?) packet sent for slot: %.*s node: %.*s unix_check: %lu\n", (int) uwsgi.mypid, usr->keylen, usr->key, usr->address_len, usr->address, (unsigned long) usr->unix_check); return NULL; } #endif node = uwsgi_malloc(sizeof(struct uwsgi_subscribe_node)); node->len = usr->address_len; node->modifier1 = usr->modifier1; node->modifier2 = usr->modifier2; node->requests = 0; node->last_requests = 0; node->transferred = 0; node->reference = 0; node->death_mark = 0; node->failcnt = 0; node->cores = usr->cores; node->load = usr->load; node->weight = usr->weight; node->unix_check = usr->unix_check; if (!node->weight) node->weight = 1; node->wrr = 0; node->last_check = uwsgi_now(); node->slot = current_slot; memcpy(node->name, usr->address, usr->address_len); if (old_node) { old_node->next = node; } node->next = NULL; uwsgi_log("[uwsgi-subscription for pid %d] %.*s => new node: %.*s\n", (int) uwsgi.mypid, usr->keylen, usr->key, usr->address_len, usr->address); return node; } else { #ifdef UWSGI_SSL FILE *kf = NULL; if (uwsgi.subscriptions_sign_check_dir) { if (usr->unix_check < (uwsgi_now() - (time_t) uwsgi.subscriptions_sign_check_tolerance)) { uwsgi_log("[uwsgi-subscription for pid %d] invalid (sniffed ?) packet sent for slot: %.*s node: %.*s unix_check: %lu\n", (int) uwsgi.mypid, usr->keylen, usr->key, usr->address_len, usr->address, (unsigned long) usr->unix_check); return NULL; } char *keyfile = uwsgi_sanitize_cert_filename(uwsgi.subscriptions_sign_check_dir, usr->key, usr->keylen); kf = fopen(keyfile, "r"); free(keyfile); if (!kf) return NULL; } #endif current_slot = uwsgi_malloc(sizeof(struct uwsgi_subscribe_slot)); uint32_t hash = djb33x_hash(usr->key, usr->keylen); int hash_key = hash % 0xffff; current_slot->hash = hash_key; #ifdef UWSGI_SSL if (uwsgi.subscriptions_sign_check_dir) { current_slot->sign_public_key = PEM_read_PUBKEY(kf, NULL, NULL, NULL); fclose(kf); if (!current_slot->sign_public_key) { uwsgi_log("unable to load public key for %.*s\n", usr->keylen, usr->key); free(current_slot); return NULL; } current_slot->sign_ctx = EVP_MD_CTX_create(); if (!current_slot->sign_ctx) { uwsgi_log("unable to initialize EVP context for %.*s\n", usr->keylen, usr->key); EVP_PKEY_free(current_slot->sign_public_key); free(current_slot); return NULL; } if (!uwsgi_subscription_sign_check(current_slot, usr)) { EVP_PKEY_free(current_slot->sign_public_key); EVP_MD_CTX_destroy(current_slot->sign_ctx); free(current_slot); return NULL; } } #endif current_slot->keylen = usr->keylen; memcpy(current_slot->key, usr->key, usr->keylen); current_slot->key[usr->keylen] = 0; current_slot->hits = 0; current_slot->nodes = uwsgi_malloc(sizeof(struct uwsgi_subscribe_node)); current_slot->nodes->slot = current_slot; current_slot->nodes->len = usr->address_len; current_slot->nodes->reference = 0; current_slot->nodes->requests = 0; current_slot->nodes->last_requests = 0; current_slot->nodes->transferred = 0; current_slot->nodes->death_mark = 0; current_slot->nodes->failcnt = 0; current_slot->nodes->modifier1 = usr->modifier1; current_slot->nodes->modifier2 = usr->modifier2; current_slot->nodes->cores = usr->cores; current_slot->nodes->load = usr->load; current_slot->nodes->weight = usr->weight; current_slot->nodes->unix_check = usr->unix_check; if (!current_slot->nodes->weight) current_slot->nodes->weight = 1; current_slot->nodes->wrr = 0; memcpy(current_slot->nodes->name, usr->address, usr->address_len); current_slot->nodes->last_check = uwsgi_now(); current_slot->nodes->next = NULL; a_slot = slot[hash_key]; while (a_slot) { old_slot = a_slot; a_slot = a_slot->next; } if (old_slot) { old_slot->next = current_slot; } current_slot->prev = old_slot; current_slot->next = NULL; if (!slot[hash_key] || current_slot->prev == NULL) { slot[hash_key] = current_slot; } uwsgi_log("[uwsgi-subscription for pid %d] new pool: %.*s (hash key: %d)\n", (int) uwsgi.mypid, usr->keylen, usr->key, current_slot->hash); uwsgi_log("[uwsgi-subscription for pid %d] %.*s => new node: %.*s\n", (int) uwsgi.mypid, usr->keylen, usr->key, usr->address_len, usr->address); return current_slot->nodes; } }
int ca_validate_pubkey(struct iked *env, struct iked_static_id *id, void *data, size_t len) { BIO *rawcert = NULL; RSA *peerrsa = NULL, *localrsa = NULL; EVP_PKEY *peerkey = NULL, *localkey = NULL; int ret = -1; FILE *fp = NULL; char idstr[IKED_ID_SIZE]; char file[PATH_MAX]; struct iked_id idp; if (len == 0 && data == NULL) return (-1); switch (id->id_type) { case IKEV2_ID_IPV4: case IKEV2_ID_FQDN: case IKEV2_ID_UFQDN: case IKEV2_ID_IPV6: break; default: /* Some types like ASN1_DN will not be mapped to file names */ return (-1); } bzero(&idp, sizeof(idp)); if ((idp.id_buf = ibuf_new(id->id_data, id->id_length)) == NULL) goto done; idp.id_type = id->id_type; idp.id_offset = id->id_offset; if (ikev2_print_id(&idp, idstr, sizeof(idstr)) == -1) goto done; if (len == 0) { /* Data is already an public key */ peerkey = (EVP_PKEY *)data; } else { if ((rawcert = BIO_new_mem_buf(data, len)) == NULL) goto done; if ((peerrsa = d2i_RSAPublicKey_bio(rawcert, NULL)) == NULL) goto sslerr; if ((peerkey = EVP_PKEY_new()) == NULL) goto sslerr; if (!EVP_PKEY_set1_RSA(peerkey, peerrsa)) goto sslerr; } lc_string(idstr); if (strlcpy(file, IKED_PUBKEY_DIR, sizeof(file)) >= sizeof(file) || strlcat(file, idstr, sizeof(file)) >= sizeof(file)) goto done; if ((fp = fopen(file, "r")) == NULL) goto done; localkey = PEM_read_PUBKEY(fp, NULL, NULL, NULL); if (localkey == NULL) { /* reading PKCS #8 failed, try PEM */ rewind(fp); localrsa = PEM_read_RSAPublicKey(fp, NULL, NULL, NULL); fclose(fp); if (localrsa == NULL) goto sslerr; if ((localkey = EVP_PKEY_new()) == NULL) goto sslerr; if (!EVP_PKEY_set1_RSA(localkey, localrsa)) goto sslerr; } else { fclose(fp); } if (localkey == NULL) goto sslerr; if (!EVP_PKEY_cmp(peerkey, localkey)) goto done; log_debug("%s: valid public key in file %s", __func__, file); ret = 0; sslerr: if (ret != 0) ca_sslerror(__func__); done: ibuf_release(idp.id_buf); if (peerkey != NULL) EVP_PKEY_free(peerkey); if (localkey != NULL) EVP_PKEY_free(localkey); if (peerrsa != NULL) RSA_free(peerrsa); if (localrsa != NULL) RSA_free(localrsa); if (rawcert != NULL) BIO_free(rawcert); return (ret); }
void pki_evp::fload(const QString fname) { pass_info p(XCA_TITLE, qApp->translate("MainWindow", "Please enter the password to decrypt the private key: '%1'"). arg(fname)); pem_password_cb *cb = MainWindow::passRead; FILE *fp = fopen(QString2filename(fname), "r"); EVP_PKEY *pkey; pki_ign_openssl_error(); if (!fp) { fopen_error(fname); return; } pkey = PEM_read_PrivateKey(fp, NULL, cb, &p); if (!pkey) { if (ERR_get_error() == 0x06065064) { fclose(fp); pki_ign_openssl_error(); throw errorEx(tr("Failed to decrypt the key (bad password) ") + fname, class_name); } } if (!pkey) { pki_ign_openssl_error(); rewind(fp); pkey = d2i_PrivateKey_fp(fp, NULL); } if (!pkey) { pki_ign_openssl_error(); rewind(fp); pkey = d2i_PKCS8PrivateKey_fp(fp, NULL, cb, &p); } if (!pkey) { PKCS8_PRIV_KEY_INFO *p8inf; pki_ign_openssl_error(); rewind(fp); p8inf = d2i_PKCS8_PRIV_KEY_INFO_fp(fp, NULL); if (p8inf) { pkey = EVP_PKCS82PKEY(p8inf); PKCS8_PRIV_KEY_INFO_free(p8inf); } } if (!pkey) { pki_ign_openssl_error(); rewind(fp); pkey = PEM_read_PUBKEY(fp, NULL, cb, &p); } if (!pkey) { pki_ign_openssl_error(); rewind(fp); pkey = d2i_PUBKEY_fp(fp, NULL); } fclose(fp); if (pki_ign_openssl_error()) { if (pkey) EVP_PKEY_free(pkey); throw errorEx(tr("Unable to load the private key in file %1. Tried PEM and DER private, public and PKCS#8 key types.").arg(fname)); } if (pkey){ if (pkey->type == EVP_PKEY_EC) search_ec_oid(pkey->pkey.ec); if (key) EVP_PKEY_free(key); key = pkey; if (EVP_PKEY_isPrivKey(key)) bogusEncryptKey(); setIntName(rmslashdot(fname)); } }
int main(int argc, char *argv[]) { FILE *rsapub_key_fp; unsigned char *cam128_key, *cam128_iv; unsigned char *cipher_of_secret_text, *cipher_of_signed_key, *signed_key, *secret_text, *clobbered_key; EVP_PKEY *rsapub_key; unsigned char *rc4_40_key; const EVP_CIPHER *cam128_cfb8, *rc4_40; const EVP_MD *sha; EVP_MD_CTX sha_ctx; int cam128_cfb8_keylen, cam128_cfb8_ivlen, rc4_40_keylen, signed_key_size; int ret, count; long cipher_of_signed_key_size, clobbered_key_size, cipher_of_secret_text_size, secret_text_size; // get the parameters for CAMELLIA128_cfb8 cam128_cfb8 = EVP_camellia_128_cfb8(); cam128_cfb8_keylen = EVP_CIPHER_key_length(cam128_cfb8); cam128_cfb8_ivlen = EVP_CIPHER_iv_length(cam128_cfb8); // get the parameters for RC4_40 rc4_40 = EVP_rc4_40(); rc4_40_keylen = EVP_CIPHER_key_length(rc4_40); // get the parameters for sha sha = EVP_sha(); // read the s67766-clobbered-key.bin and store the key and iv for CAMELLIA128-cfb8 cam128_key = malloc(cam128_cfb8_keylen); cam128_iv = malloc(cam128_cfb8_ivlen); clobbered_key_size = read_file(clobbered_key_file, &clobbered_key); if(clobbered_key_size != cam128_cfb8_keylen+cam128_cfb8_ivlen) { printf("reading file %s returned not enough Bytes: %ld, instead of: %d\n", clobbered_key_file, clobbered_key_size, cam128_cfb8_keylen+cam128_cfb8_ivlen); perror(""); } memcpy(cam128_key, clobbered_key, cam128_cfb8_keylen); memcpy(cam128_iv, clobbered_key+cam128_cfb8_keylen, cam128_cfb8_ivlen); // read the s67766-cipher-of-signed-key.bin cipher_of_signed_key_size = read_file(cipher_of_signed_key_file, &cipher_of_signed_key); // read the public key from rsapub.pem rsapub_key_fp = fopen(rsapub_key_file, "r"); if (!rsapub_key_fp) { printf("opening file %s returned error\n", rsapub_key_file); perror(""); } rsapub_key = PEM_read_PUBKEY(rsapub_key_fp, NULL, NULL, NULL); if (!rsapub_key) { printf("PEM_read_PUBKEY returned error for RSA\n"); } if(fclose(rsapub_key_fp) != 0) { printf("closing file %s returned error\n", rsapub_key_file); perror(""); } // restore the clobbered key with bruteforce signed_key = malloc(cipher_of_signed_key_size); for(count = 0; count<=255; count++) { memset(cam128_key, count, 1); //decrypt the cipher with guessed key signed_key_size = decrypt(cam128_cfb8, &signed_key, cipher_of_signed_key, cipher_of_signed_key_size, cam128_key, cam128_iv); if(signed_key_size==-1) { return -1; } if(EVP_VerifyInit(&sha_ctx, sha) == 0) { printf("EVP_VerifyInit returned error for SHA\n"); } if(EVP_VerifyUpdate(&sha_ctx, signed_key, rc4_40_keylen) == 0) { printf("EVP_VerifyUpdate returned error for SHA\n"); } ret = EVP_VerifyFinal(&sha_ctx, signed_key+rc4_40_keylen, signed_key_size-rc4_40_keylen, rsapub_key); switch(ret) { case -1: printf("EVP_VerifyFinal returned error for SHA\n"); break; case 0: break; case 1: count = 255; break; } } // extract the key for RC-4 40 rc4_40_key = malloc(rc4_40_keylen); memcpy(rc4_40_key, signed_key, rc4_40_keylen); // read the s67766-cipher-of-secret-text.bin cipher_of_secret_text_size = read_file(cipher_of_secret_text_file, &cipher_of_secret_text); // decrypt s67766-cipher-of-secret-text.bin secret_text = malloc(cipher_of_secret_text_size); secret_text_size = 0; secret_text_size = decrypt(rc4_40, &secret_text, cipher_of_secret_text, cipher_of_secret_text_size, rc4_40_key, NULL); // write the s67766-plain.bin if(write_file(plain_file, secret_text, secret_text_size)==-1) { return -1; } return 0; }
int main(int argc, char *argv[]) { FILE *fin, *fkey; u_int16_t siglen; u_int32_t magic; long nread, ndata; char *sigbuf, *inbuf; EVP_PKEY *pkey; EVP_MD_CTX ctx; int err, retval; if (argc != 3) usage(); ERR_load_crypto_strings(); /* open file and check for magic */ fin = fopen(argv[2], "r+"); if (fin == NULL) { fprintf(stderr, "unable to open file '%s'\n", argv[2]); exit(4); } fseek(fin, -(sizeof(magic)), SEEK_END); fread(&magic, sizeof(magic), 1, fin); if (magic != SIG_MAGIC) { fclose(fin); exit(2); } /* magic is good; get signature length */ fseek(fin, -(sizeof(magic) + sizeof(siglen)), SEEK_END); fread(&siglen, sizeof(siglen), 1, fin); /* read public key */ fkey = fopen(argv[1], "r"); if (fkey == NULL) { fprintf(stderr, "unable to open public key file '%s'\n", argv[1]); exit(4); } pkey = PEM_read_PUBKEY(fkey, NULL, NULL, NULL); fclose(fkey); if (pkey == NULL) { ERR_print_errors_fp(stderr); exit(4); } /* check if siglen is sane */ if ((siglen == 0) || (siglen > EVP_PKEY_size(pkey))) exit(3); /* got signature length; read signature */ sigbuf = malloc(siglen); if (sigbuf == NULL) exit(4); fseek(fin, -(sizeof(magic) + sizeof(siglen) + siglen), SEEK_END); if (fread(sigbuf, 1, siglen, fin) != siglen) exit(4); /* signature read; truncate file to remove sig */ fseek(fin, 0, SEEK_END); ndata = ftell(fin) - (sizeof(magic) + sizeof(siglen) + siglen); ftruncate(fileno(fin), ndata); /* verify the signature now */ EVP_VerifyInit(&ctx, EVP_sha1()); /* allocate data buffer */ inbuf = malloc(SIG_INBUFLEN); if (inbuf == NULL) exit(4); rewind(fin); while (!feof(fin)) { nread = fread(inbuf, 1, SIG_INBUFLEN, fin); if (nread != SIG_INBUFLEN) { if (ferror(fin)) { fprintf(stderr, "read error in file '%s'\n", argv[2]); exit(4); } } EVP_VerifyUpdate(&ctx, inbuf, nread); } err = EVP_VerifyFinal(&ctx, sigbuf, siglen, pkey); EVP_PKEY_free(pkey); if (err == 1) retval = 0; /* correct signature */ else if (err == 0) retval = 1; /* invalid signature */ else retval = 3; /* error */ free(inbuf); free(sigbuf); fclose(fin); return retval; }
int verify(const char* keypath, BIGNUM* nonce, const uint8_t* sig, size_t slen){ // Nonce uint8_t* N; size_t Nlen; // Context and key EVP_PKEY_CTX *verctx; FILE* vkeyfh; EVP_PKEY *vkey=NULL; // Return codes and errors int err_code, ret_val=1; unsigned long vererr; /* * Open the public key of the client for verification */ vkeyfh = fopen(keypath,"r"); if(!vkeyfh) { fprintf(stderr, "%s: Cannot open the key file\n", __func__); ret_val = 0; goto exit_verify; } vkey = PEM_read_PUBKEY(vkeyfh, &vkey, NULL, NULL); if(!vkey){ fprintf(stderr,"Cannot read verification key from file %s\n", keypath); ret_val = 0; fclose(vkeyfh); goto exit_verify; } verctx = EVP_PKEY_CTX_new(vkey, NULL); if (!verctx){ fprintf(stderr,"Cannot create a verify context\n"); ret_val = 0; fclose(vkeyfh); EVP_PKEY_free(vkey); goto exit_verify; } if (EVP_PKEY_verify_init(verctx) <= 0){ fprintf(stderr,"Cannot initialize a verify context\n"); ret_val = 0; goto cleanup_verify; } /* * Convert the nonce in a string so that it can be verified */ N = malloc(BN_num_bytes(nonce)); if (N == NULL) { fprintf(stderr, "%s: Out of memory\n", __func__); ret_val = 0; goto cleanup_verify; } Nlen = BN_bn2bin(nonce, N); /* Perform actual verify operation */ err_code = EVP_PKEY_verify(verctx, sig, slen, N, Nlen); if( err_code != 1 ){ ERR_load_crypto_strings(); vererr = ERR_get_error(); fprintf(stderr,"The verify operation on the nonce has failed with code %lu. RET=%d\n",vererr,err_code); fprintf(stderr,"%s\n", ERR_error_string(vererr, NULL)); ERR_free_strings(); ret_val = 0; } free(N); cleanup_verify: EVP_PKEY_CTX_free(verctx); EVP_PKEY_free(vkey); fclose(vkeyfh); exit_verify: return ret_val; }
int main(int argc, char *argv[]) { int ret; struct stat sbuf; unsigned char databuff[65535]; /* data read work buffer */ unsigned char datahash[20]; /* hash of data file */ unsigned char digest[20]; SHA_CTX sha; FILE *datafile; const char *datafilename = NULL; FILE *sigfile; const char *sigfilename = NULL; FILE *keyfile; const char *kfilename = NULL; EVP_PKEY *pkey; RSA *rsa; uint16_t sigscheme = TPM_SS_RSASSAPKCS1v15_SHA1; int plain; unsigned char padded[4096]; unsigned char plainarray[4096]; TPM_SIGN_INFO tsi; STACK_TPM_BUFFER(tsi_ser); STACK_TPM_BUFFER(signature); int i; for (i=1 ; i<argc ; i++) { if (!strcmp(argv[i], "-ss")) { i++; if (i < argc) { if (!strcmp(argv[i], "info")) { sigscheme = TPM_SS_RSASSAPKCS1v15_INFO; } else if (!strcmp(argv[i], "der")) { sigscheme = TPM_SS_RSASSAPKCS1v15_DER; } else { printf("Bad parameter for -ss\n"); printUsage(); } } else { printf("Missing parameter for -ss\n"); printUsage(); } } else if (strcmp(argv[i],"-if") == 0) { i++; if (i < argc) { datafilename = argv[i]; } else { printf("-if option needs a value\n"); printUsage(); exit(2); } } else if (strcmp(argv[i],"-is") == 0) { i++; if (i < argc) { sigfilename = argv[i]; } else { printf("-is option needs a value\n"); printUsage(); } } else if (strcmp(argv[i],"-ik") == 0) { i++; if (i < argc) { kfilename = argv[i]; } else { printf("-ik option needs a value\n"); printUsage(); exit(2); } } else if (!strcmp(argv[i], "-h")) { printUsage(); } else if (!strcmp(argv[i], "-v")) { TPM_setlog(1); } else { printf("\n%s is not a valid option\n", argv[i]); printUsage(); } } if ((datafilename == NULL) || (sigfilename == NULL) || (kfilename == NULL)) { printf("Missing parameter\n"); printUsage(); } /* ** read and hash the data file */ datafile = fopen(datafilename,"rb"); if (datafile == NULL) { printf("Unable to open data file '%s'\n",datafilename); exit(2); } SHA1_Init(&sha); for (;;) { ret = fread(databuff,1,sizeof databuff,datafile); if (ret < 0) { printf("I/O Error while reading data file '%s'\n",datafilename); exit(3); } SHA1_Update(&sha,databuff,ret); if (ret < (int)sizeof(databuff)) break; } fclose(datafile); SHA1_Final(datahash,&sha); /* ** get size of signature file */ stat(sigfilename,&sbuf); signature.used = (int)sbuf.st_size; sigfile = fopen(sigfilename,"rb"); if (sigfile == NULL) { printf("Unable to open signature file '%s'\n",sigfilename); exit(4); } /* ** read the signature file */ ret = fread(signature.buffer,1,signature.used,sigfile); if (ret != (int)signature.used) { printf("I/O Error while reading signature file '%s'\n",sigfilename); exit(5); } fclose(sigfile); /* ** read the key file */ keyfile = fopen(kfilename,"rb"); if (keyfile == NULL) { printf("Unable to open public key file '%s'\n",kfilename); exit(6); } pkey = PEM_read_PUBKEY(keyfile,NULL,NULL,NULL); if (pkey == NULL) { printf("I/O Error while reading public key file '%s'\n",kfilename); exit(7); } rsa = EVP_PKEY_get1_RSA(pkey); if (rsa == NULL) { printf("Error while converting public key \n"); exit(8); } switch (sigscheme) { default: case TPM_SS_RSASSAPKCS1v15_SHA1: ret = RSA_verify(NID_sha1,datahash,20, signature.buffer,signature.used, rsa); if (ret != 1) { printf("Verification Failed\n"); exit(100); } break; case TPM_SS_RSASSAPKCS1v15_DER: plain = RSA_public_decrypt(signature.used, signature.buffer, plainarray, rsa, RSA_NO_PADDING); if (plain == -1) { printf("Verification (DER) had an error\n"); exit(100); } ret = RSA_padding_add_PKCS1_type_1(padded,plain,datahash,sizeof(datahash)); if (ret != 1) { printf("Could not add the padding.\n"); exit(100); } if (memcmp(padded, plainarray, plain) != 0) { printf("Verfication (DER) failed.\n"); exit(100); } break; case TPM_SS_RSASSAPKCS1v15_INFO: // the nonce is the digest of the hashed data!! TSS_sha1(datahash, 20, digest); tsi.tag = TPM_TAG_SIGNINFO; memcpy(tsi.fixed,"SIGN",4); tsi.data.size = TPM_HASH_SIZE; tsi.data.buffer = datahash; memcpy(tsi.replay, digest, TPM_HASH_SIZE); /* need to calcualte the digest of the TPM_SIGN_INFO structure */ ret = TPM_WriteSignInfo(&tsi_ser, &tsi); if ((ret & ERR_MASK)) { printf("Could not serialize TPM_SIGN_INFO structure.\n"); exit(100); } ret = TPM_ValidateSignature(sigscheme, &tsi_ser, &signature, rsa); if (ret != 0) { printf("Verification (INFO) failed.\n"); exit(-1); } break; } RSA_free(rsa); EVP_PKEY_free(pkey); exit(0); }
int main(int argc, char *argv[]) { int i; int ret; RSA *rsa; EVP_PKEY *pkey; FILE *dfile; FILE *ofile; FILE *kfile; unsigned char blob[4096]; unsigned int bloblen; unsigned int datlen; struct tcpa_bound_data { unsigned char version[4]; unsigned char type; unsigned char data[256]; } bound; struct stat sbuf; if (argc < 4) { fprintf(stderr, "Usage: bindfile <pubkey file> <data file> <output file>\n"); exit(1); } TPM_setlog(0); /* ** get size of data file */ stat(argv[2], &sbuf); datlen = (int) sbuf.st_size; /* ** read the data file */ dfile = fopen(argv[2], "r"); if (dfile == NULL) { fprintf(stderr, "Unable to open data file '%s'\n", argv[2]); exit(2); } memset(bound.data, 0, 256); ret = fread(bound.data, 1, datlen, dfile); fclose(dfile); if (ret != datlen) { fprintf(stderr, "Unable to read data file\n"); exit(3); } /* ** read the key file */ kfile = fopen(argv[1], "r"); if (kfile == NULL) { fprintf(stderr, "Unable to open public key file '%s'\n", argv[1]); exit(4); } pkey = PEM_read_PUBKEY(kfile, NULL, NULL, NULL); fclose(kfile); if (pkey == NULL) { fprintf(stderr, "I/O Error while reading public key file '%s'\n", argv[1]); exit(5); } rsa = EVP_PKEY_get1_RSA(pkey); if (rsa == NULL) { fprintf(stderr, "Error while converting public key \n"); exit(6); } /* get the TPM version and put into the bound structure */ ret = TPM_GetCapability(0x00000006, NULL, 0, &(bound.version[0]), &i); if (ret != 0) { fprintf(stderr, "Error '%s' from TPM_GetCapability\n", TPM_GetErrMsg(ret)); exit(7); } bound.type = 2; ret = TSS_Bind(rsa, (unsigned char *) &bound, 5 + datlen, blob, &bloblen); if (ret != 0) { fprintf(stderr, "Error '%s' from TSS_Bind\n", TPM_GetErrMsg(ret)); exit(8); } ofile = fopen(argv[3], "w"); if (ofile == NULL) { fprintf(stderr, "Unable to open output file '%s'\n", argv[3]); exit(9); } i = fwrite(blob, 1, bloblen, ofile); if (i != bloblen) { fprintf(stderr, "Error writing output file '%s'\n", argv[3]); fclose(ofile); exit(10); } fclose(ofile); exit(0); }
uint8_t* encrypt(const char* keypath, const uint8_t* p, const size_t plen, size_t* clen, uint8_t** iv, size_t* ivlen, uint8_t** ek, size_t* ekl){ // Context and key FILE* ckeyfh; EVP_PKEY *ckey=NULL; // Return codes and errors unsigned long encerr; /* The buffer with the ciphertext */ uint8_t* c; /* Variables related to the symmetric enc of the envelope */ EVP_CIPHER_CTX *encctx = NULL; const EVP_CIPHER* type = EVP_aes_256_cbc(); // Type of encryption int outl, outf; int eklint; /* * Open a public key for encryption */ ckeyfh = fopen(keypath,"r"); if (!ckeyfh) { fprintf(stderr, "%s: Cannot open key file\n", __func__); c = NULL; goto exit_encrypt; } ckey = PEM_read_PUBKEY(ckeyfh, &ckey, NULL, NULL); if (!ckey){ fprintf(stderr,"Cannot read encryption key from file %s\n", keypath); fclose(ckeyfh); c = NULL; goto exit_encrypt; } /* EVP_Seal* need a CIPHER_CTX */ encctx = malloc(sizeof(EVP_CIPHER_CTX)); if (encctx == NULL) { fprintf(stderr, "%s: Out of memory\n", __func__); fclose(ckeyfh); EVP_PKEY_free(ckey); c = NULL; goto exit_encrypt; } EVP_CIPHER_CTX_init(encctx); if (!encctx){ fprintf(stderr,"Cannot inizialize an encryption context\n"); c = NULL; goto cleanup_encrypt; } /* Start the encryption process - generate IV and key */ *ivlen = EVP_CIPHER_iv_length(type); *iv = malloc(*ivlen); if (iv == NULL) { fprintf(stderr, "%s: Out of memory allocating of IV\n", __func__); c = NULL; goto cleanup_encrypt; } *ek = malloc(EVP_PKEY_size(ckey)); if (*ek == NULL) { fprintf(stderr, "%s: Out of memory allocating ek\n", __func__); free(iv); c = NULL; goto cleanup_encrypt; } c = malloc(plen + EVP_CIPHER_block_size(type)); if (c == NULL) { fprintf(stderr, "%s: Out of memory for \n", __func__); free(iv); free(*ek); goto cleanup_encrypt; } if (EVP_SealInit(encctx, type, ek, &eklint, *iv, &ckey, 1) != 1){ ERR_load_crypto_strings(); encerr = ERR_get_error(); fprintf(stderr,"Encrypt failed\n"); printf("%s\n", ERR_error_string(encerr, NULL)); ERR_free_strings(); free(iv); free(*ek); free(c); c = NULL; goto cleanup_encrypt; } *ekl = eklint; /* Encrypt data, then finalize */ if (EVP_SealUpdate(encctx, c, &outl, p, plen) != 1){ ERR_load_crypto_strings(); encerr = ERR_get_error(); fprintf(stderr,"Encrypt failed\n"); printf("%s\n", ERR_error_string(encerr, NULL)); ERR_free_strings(); free(iv); free(*ek); free(c); c = NULL; goto cleanup_encrypt; } if (EVP_SealFinal(encctx, &c[outl], &outf) != 1){ ERR_load_crypto_strings(); encerr = ERR_get_error(); fprintf(stderr,"Encrypt failed\n"); printf("%s\n", ERR_error_string(encerr, NULL)); ERR_free_strings(); free(c); c = NULL; outl = outf = 0; } *clen = outl + outf; cleanup_encrypt: EVP_CIPHER_CTX_cleanup(encctx); free(encctx); fclose(ckeyfh); EVP_PKEY_free(ckey); exit_encrypt: return c; }