Задать вопрос
  • Как собрать приложение c++ с openssl?

    Slavenin999
    @Slavenin999 Автор вопроса
    g++ function.cpp main.cpp -o my_openssl_use -I -L/lib> -lssl -lcrypt

    сделал так:
    g++ function.cpp main.cpp -o my_openssl_use -I/usr/local/ssl/include/openssl/ -L/usr/local/ssl/lib/ -lssl -lcrypt

    ошибки
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x1f): undefined reference to `ERR_load_crypto_strings'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x24): undefined reference to `OPENSSL_add_all_algorithms_noconf'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x30): undefined reference to `OPENSSL_config'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x92): undefined reference to `BIO_dump_fp'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0xef): undefined reference to `EVP_cleanup'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0xf4): undefined reference to `ERR_free_strings'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x110): undefined reference to `EVP_CIPHER_CTX_new'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x128): undefined reference to `EVP_aes_256_cbc'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x14d): undefined reference to `EVP_EncryptInit_ex'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x183): undefined reference to `EVP_EncryptUpdate'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x1b8): undefined reference to `EVP_EncryptFinal_ex'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x1d8): undefined reference to `EVP_CIPHER_CTX_free'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x1f2): undefined reference to `EVP_CIPHER_CTX_new'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x20a): undefined reference to `EVP_aes_256_cbc'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x22f): undefined reference to `EVP_DecryptInit_ex'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x265): undefined reference to `EVP_DecryptUpdate'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x29a): undefined reference to `EVP_DecryptFinal_ex'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x2ba): undefined reference to `EVP_CIPHER_CTX_free'
    /tmp/ccRPqfPB.o:function.cpp:(.text+0x2df): undefined reference to `ERR_print_errors_fp'
    /usr/lib/gcc/i686-pc-cygwin/4.8.2/../../../../i686-pc-cygwin/bin/ld: /tmp/ccRPqfPB.o: неправильный адрес перемещения 0x13 в разделе «.eh_frame»
    /usr/lib/gcc/i686-pc-cygwin/4.8.2/../../../../i686-pc-cygwin/bin/ld: final link failed: Неверная операция
    collect2: ошибка: выполнение ld завершилось с кодом возврата 1


    Может что-то собралось не верно? Запускаю всё из консоли cygwin
    Openssl собирал как
    ./config
    make
    make install
  • Как собрать приложение c++ с openssl?

    Slavenin999
    @Slavenin999 Автор вопроса
    netbeans генерит make файлы и потом по ним собирает проект
  • Как собрать приложение c++ с openssl?

    Slavenin999
    @Slavenin999 Автор вопроса
    g++ -m32 -o my_encrypt_app -L c:/cygwin/usr/local/ssl/lib/ -lssl -lcrypt   -c -g -I/cygdrive/c/cygwin/usr/local/ssl/include/ -MMD -MP -MF "build/Debug/Cygwin_4.x-Windows/function.o.d" -o build/Debug/Cygwin_4.x-Windows/function.o function.cpp
    cc1plus: fatal error: build/Debug/Cygwin_4.x-Windows/function.d: No such file or directory
  • Как собрать приложение c++ с openssl?

    Slavenin999
    @Slavenin999 Автор вопроса
    1) Убедись что openssl у тебя на машине установлен. Вместе с заголовочными файлами и библиотеками

    Установлен. В текущий момент собран через cygwin c помощью make
    (может нужно было какие-то флаги добавить?)
    2) Для того что бы собрать твой проект тебе нужно, что-то вроде этого

    после смены флагов:
    g++ -m32 -o my_encrypt_app -L c:/cygwin/usr/local/ssl/lib/ -lssl -lcrypt   -c -g -include /cygdrive/c/cygwin/usr/local/ssl/include/ -MMD -MP -MF "build/Debug/Cygwin_4.x-Windows/function.o.d" -o build/Debug/Cygwin_4.x-Windows/function.o function.cpp
    cc1plus: fatal error: build/Debug/Cygwin_4.x-Windows/function.d: No such file or directory
    compilation terminated.
  • Как собрать приложение c++ с openssl?

    Slavenin999
    @Slavenin999 Автор вопроса
    function.h
    #ifndef FUNCTION_H
    #define	FUNCTION_H
    #endif	/* FUNCTION_H */
    #include <openssl/conf.h>
    #include <openssl/evp.h>
    #include <openssl/err.h>
    #include <openssl/ssl.h>
    #include "openssl/bio.h"
    #include <string>
    
    using namespace std ;
    
    int encript_scring(string &);
    int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
      unsigned char *iv, unsigned char *ciphertext);
    int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
      unsigned char *iv, unsigned char *plaintext);
    void handleErrors(void);
    function.cpp
    #include "function.h"
    #include <string.h>
    
    #define BUFSIZE 1024
    
    using namespace std;
    
    int encript_scring(string &data)
    {
    	/* Set up the key and iv. Do I need to say to not hard code these in a
    	 * real application? :-)
    	 */
    
    	/* A 256 bit key */
    	unsigned char *key = (unsigned char *)"01234567890123456789012345678901";
    
    	/* A 128 bit IV */
    	unsigned char *iv = (unsigned char *)"01234567890123456";
    
    	/* Message to be encrypted */
    	unsigned char *plaintext =
    			(unsigned char *)"The quick brown fox jumps over the lazy dog";
    
    	/* Buffer for ciphertext. Ensure the buffer is long enough for the
    	 * ciphertext which may be longer than the plaintext, dependant on the
    	 * algorithm and mode
    	 */
    	unsigned char ciphertext[128];
    
    	/* Buffer for the decrypted text */
    	unsigned char decryptedtext[128];
    
    	int decryptedtext_len, ciphertext_len;
    
    	/* Initialise the library */
    	ERR_load_crypto_strings();
    	OpenSSL_add_all_algorithms();
    	OPENSSL_config(NULL);
    
    	/* Encrypt the plaintext */
    	ciphertext_len = encrypt(plaintext, strlen((char *)plaintext), key, iv,
    			ciphertext);
    
    	/* Do something useful with the ciphertext here */
    	printf("Ciphertext is:\n");
    	BIO_dump_fp(stdout, (char *)ciphertext, ciphertext_len);
    
    	/* Decrypt the ciphertext */
    	decryptedtext_len = decrypt(ciphertext, ciphertext_len, key, iv,
    			decryptedtext);
    
    	/* Add a NULL terminator. We are expecting printable text */
    	decryptedtext[decryptedtext_len] = '\0';
    
    	/* Show the decrypted text */
    	printf("Decrypted text is:\n");
    	printf("%s\n", decryptedtext);
    
    	/* Clean up */
    	EVP_cleanup();
    	ERR_free_strings();
    
    
    	return 0;
    }
    
    int encrypt(unsigned char *plaintext, int plaintext_len, unsigned char *key,
      unsigned char *iv, unsigned char *ciphertext)
    {
      EVP_CIPHER_CTX *ctx;
    
      int len;
    
      int ciphertext_len;
    
      /* Create and initialise the context */
      if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
    
      /* Initialise the encryption operation. IMPORTANT - ensure you use a key
       * and IV size appropriate for your cipher
       * In this example we are using 256 bit AES (i.e. a 256 bit key). The
       * IV size for *most* modes is the same as the block size. For AES this
       * is 128 bits */
      if(1 != EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();
    
      /* Provide the message to be encrypted, and obtain the encrypted output.
       * EVP_EncryptUpdate can be called multiple times if necessary
       */
      if(1 != EVP_EncryptUpdate(ctx, ciphertext, &len, plaintext, plaintext_len))
        handleErrors();
      ciphertext_len = len;
    
      /* Finalise the encryption. Further ciphertext bytes may be written at
       * this stage.
       */
      if(1 != EVP_EncryptFinal_ex(ctx, ciphertext + len, &len)) handleErrors();
      ciphertext_len += len;
    
      /* Clean up */
      EVP_CIPHER_CTX_free(ctx);
    
      return ciphertext_len;
    }
    
    int decrypt(unsigned char *ciphertext, int ciphertext_len, unsigned char *key,
      unsigned char *iv, unsigned char *plaintext)
    {
      EVP_CIPHER_CTX *ctx;
    
      int len;
    
      int plaintext_len;
    
      /* Create and initialise the context */
      if(!(ctx = EVP_CIPHER_CTX_new())) handleErrors();
    
      /* Initialise the decryption operation. IMPORTANT - ensure you use a key
       * and IV size appropriate for your cipher
       * In this example we are using 256 bit AES (i.e. a 256 bit key). The
       * IV size for *most* modes is the same as the block size. For AES this
       * is 128 bits */
      if(1 != EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv))
        handleErrors();
    
      /* Provide the message to be decrypted, and obtain the plaintext output.
       * EVP_DecryptUpdate can be called multiple times if necessary
       */
      if(1 != EVP_DecryptUpdate(ctx, plaintext, &len, ciphertext, ciphertext_len))
        handleErrors();
      plaintext_len = len;
    
      /* Finalise the decryption. Further plaintext bytes may be written at
       * this stage.
       */
      if(1 != EVP_DecryptFinal_ex(ctx, plaintext + len, &len)) handleErrors();
      plaintext_len += len;
    
      /* Clean up */
      EVP_CIPHER_CTX_free(ctx);
    
      return plaintext_len;
    }
    
    void handleErrors(void)
    {
      ERR_print_errors_fp(stderr);
      abort();
    }
    main.cpp
    /*
     * File:   main.cpp
     * Author: Максим
     *
     * Created on 7 мая 2014 г., 18:06
     */
    
    #include "function.h"
    #include <sys/types.h>
    #include <sys/socket.h>
    #include <netinet/in.h>
    #include <stdio.h>
    #include <cstdlib>
    #include <unistd.h>
    
    using namespace std ;
    
    int main()
    {
        int sock, listener;
    	int buf_size = 1024;
        struct sockaddr_in addr;
        char buf[buf_size];
        int bytes_read;
    	string msg("");
    	string encripted("");
    
        listener = socket(AF_INET, SOCK_STREAM, 0);
        if(listener < 0)
        {
            perror("socket");
            exit(1);
        }
    
        addr.sin_family = AF_INET;
        addr.sin_port = htons(3425);
        addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
        if(bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
        {
            perror("bind");
            exit(2);
        }
    
        listen(listener, 1);
    
        while(1)
        {
            sock = accept(listener, NULL, NULL);
            if(sock < 0)
            {
                perror("accept");
                exit(3);
            }
    
            switch(fork())
            {
            case -1:
                perror("fork");
                break;
    
            case 0:
                close(listener);
                while(1)
                {
                    bytes_read = recv(sock, &buf, buf_size, 0);
    
    				msg.append(buf, 0, bytes_read);
                    if(bytes_read <= 0 || bytes_read <= buf_size)
    				{
    					encripted = encript_scring(msg);
    
    					//send(sock, msg.c_str(), msg.size(), 0);
    					close(listener);
    					close(sock);
    					break;
    				}
                }
    
                close(sock);
                _exit(0);
    
            default:
                close(sock);
            }
        }
    
        close(listener);
    
        return 0;
    }
  • Cтранности версий php + apache под windows

    Slavenin999
    @Slavenin999 Автор вопроса
    если бы мне нужен был xampp, я бы его поставил
  • Javasript - как отключить/включить отрисовку документа?

    Slavenin999
    @Slavenin999 Автор вопроса
    если бы мог, обязательно бы это сделал, но вот заказчик с этим не согласен...
  • Javasript - как отключить/включить отрисовку документа?

    Slavenin999
    @Slavenin999 Автор вопроса
    Вся проблема в том, что это 8 ИЕ (да-да, он еще жив и под него приходится что-то думать...) прямой работы с DOM не очень много. Пытаюсь оптимизировать этот плагин стилизации форм. Когда элементов не много всё хорошо, но когда больше сотни больших селектов, начинается беда...
  • Почему Яндекс.Диск не синхронизирует файлы, начинающиеся с точки?

    Slavenin999
    @Slavenin999 Автор вопроса
    >скорее всего для сервера это скрытые файлы и он их не видит.
    это я и так понимаю, но может есть способ заставить их синхронизироваться принудительно.

    Разрабатываю проект на нескольких компьютерах. Таким способом проще всего их синхронизировать. На гитхабе репозитории публичные, плюс надо не забыть запушить изменения, а так всё синхронизируется сразу же.
  • Есть ли драйвер для подключения из netbeans к mysql через (sftp)?

    Slavenin999
    @Slavenin999 Автор вопроса
    netBeans прекрасно умеет работать через ssh внутри проектов. Драйвера для коннекта в него можно загружать отдельно, я не могу найти сам драйвер, который поддерживал бы подключение через ssh
  • Mongodb: SORT vs $ORDERBY

    странно, почему тогда в документации предлагается несколько альтернативных вариантов и говорится о том, что индекс будет использован?
    Unless you have an index for the specified key pattern, use $orderby in conjunction with $maxScan and/or cursor.limit() to avoid requiring MongoDB to perform a large in-memory sort.
  • Вопрос по отображению веток в Git

    меня тоже постоянно удивляет тот факт, что коммит не знает в какой ветке он был создан… могу посоветовать, создать для каждой операции простенькие sh-скрипты, которые будут собирать лог, кто, что и в какой ветке делал и работать с гитом через них. совет, конечно, слабенький, но можно потом открыть лог и показать вот этот коммит был сделан в этой ветке. хотя могут усомниться в истинности лога, но хоть что-то будет.
  • Вопрос по отображению веток в Git

    если вы пользуетесь git-flow то согласно переводу статьи разработчика этого инструмента при создании мёрджа используется флаг --no-ff что даёт:
    Флаг --no-ff вынуждает Git всегда создавать новый объект коммита при слиянии, даже если слияние может быть осуществлено алгоритмом fast-forward. Это позволяет не терять информацию о том, что ветка существовала, и группирует вместе все внесённые изменения.

    поэтому инфа о ветках должна сохраняться даже если ветки больше нет
  • Как отследить что пользователь покинул страницу?

    обрыв отлавливается легко. достаточно почитать на тему сокет-сервера и ws. если коротко, то socket_select возвращает ресурс сокета, но в этом ресурсе ничего нет. это значит, что сокет сдох.
  • Как отследить что пользователь покинул страницу?

    нагрузка не возрастёт. время отклика — практически мгновенно.
  • Отслеживание страницы 404?

    Slavenin999
    @Slavenin999 Автор вопроса
    ё-моё… еще раз повторяю. В том массиве $_SERVER, который приходит на страницу, в $_SERVER['REQUEST_URI'] красуется /errors/404/index.php? хотя в адресную строку я вводил mysite.ru/123 Возможно, проблема где-то в апаче, может есть мысли, где это можно посмотреть?
  • Отслеживание страницы 404?

    Slavenin999
    @Slavenin999 Автор вопроса
    да я в общем-то и не против, но не знаю как написать rewriterule, так чтобы он срабатывал на 404 ошибку
  • Соединение со старой базой mysql из нового php

    Slavenin999
    @Slavenin999 Автор вопроса
    mysql 5.0.что-то еще
    на новом хотел работать с PHP 5.5
  • Соединение со старой базой mysql из нового php

    Slavenin999
    @Slavenin999 Автор вопроса
    у меня нет прав менять настройки мускуля, и привилегий управлять пользователеми бд