使用OpenSSL C库在多个线程中生成椭圆曲线密钥对(EC_KEY_generate_key)

时间:2013-11-13 13:50:26

标签: c multithreading openssl ecdsa

我想生成许多ec密钥对。加快了这个过程,我重写了我的应用程序,使用多个线程来完成这项工作。以下是每个线程生成密钥的方式的代码片段:

(...)
EC_KEY* _ec_key = EC_KEY_new(); 
EC_GROUP* ec_group_new = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1); 
const EC_GROUP* ec_group = ec_group_new; 
if (!EC_KEY_set_group(ec_key,ec_group)) 
  DieWithError("Error in initializeCrypto, EC_KEY_set_group failed!");

// Segfault at this position
if(!EC_KEY_generate_key(ec_key))
  DieWithError ("Error in generateKeys, EC_KEY_generate_key failed!");

(...)
EC_GROUP_free(ec_group_new); 
EC_KEY_free(ec_key);
乍一看好,一切似乎都运转良好。在i5 520m上使用四个线程,应用程序的运行速度提高了两倍。但是经过3-4次E6密钥生成后,它突然出现了段错误。如果我锁定EC_KEY_generate_key操作,则不再存在段错误,但使用多个线程的优势已经消失。现在我的问题。是否有可能将密钥的创建分成多个线程而不破坏内存?我没有使用谷歌找到任何信息。但SSL Docu没有提及有关线程安全的任何内容。任何帮助都非常感谢。 THX

1 个答案:

答案 0 :(得分:4)

// Segfault at this position
if(!EC_KEY_generate_key(ec_key))
  DieWithError ("Error in generateKeys, EC_KEY_generate_key failed!");
...

... But then after 3-4 E6 key generations it suddenly segfaults.

您正在使用OpenSSL的随机数生成器,而且它不是线程安全的。下面是来自第125行的cryptlib.c。注意随机数生成器和椭圆曲线齿轮列表。

/* real #defines in crypto.h, keep these upto date */
static const char* const lock_names[CRYPTO_NUM_LOCKS] =
    {
    "<<ERROR>>",
    "err",
    "ex_data",
    "x509",
    "x509_info",
    "x509_pkey",
    "x509_crl",
    "x509_req",
    ...
    "ssl_ctx",
    "ssl_session",
    "ssl",
    "ssl_method",
    "rand",
    "rand2",
    ...
    "ecdsa",
    "ec",
    "ecdh",
    "bn",
    "ec_pre_comp",
    ...
    };

您必须明确设置锁定。请参阅OpenSSL's threads(3)


  

是否可以将密钥的创建拆分为多个线程而不会破坏内存?

是的,但您必须使用OpenSSL的锁定机制。

这是我的OpenSSL初始化例程在C ++中的样子。它初始化锁并设置回调。

pthread_mutex_t s_locks[CRYPTO_NUM_LOCKS] = { };

void Initialize()
{    
    static once_flag init;
    std::call_once(init, []() {      

        // Standard OpenSSL library init
        OPENSSL_no_config();
        SSL_library_init();

        SSL_load_error_strings();
        OpenSSL_add_ssl_algorithms();

        // Lock setup
        LOCK_setup();
        CALLBACK_setup();
    });
}

void LOCK_setup()
{    
    ASSERT(CRYPTO_NUM_LOCKS == CRYPTO_num_locks());
    if(CRYPTO_NUM_LOCKS != CRYPTO_num_locks())
        throw runtime_error("CRYPTO_NUM_LOCKS mismatch");

    for(unsigned i = 0; i < CRYPTO_NUM_LOCKS; ++i)
    {
        int rc = pthread_mutex_init(&s_locks[i], NULL);
        ASSERT(rc == 0);
        if(!(rc == 0))
            throw runtime_error("pthread_mutex_init");
    }
}

void CALLBACK_setup()
{    
    CRYPTO_set_id_callback(&ThreadIdFnc);
    CRYPTO_set_locking_callback(&LockingFnc);
}

void LockingFnc(int mode, int idx, const char* file, int line)
{
    ASSERT(mode == CRYPTO_LOCK || mode == CRYPTO_UNLOCK);
    ASSERT(CRYPTO_NUM_LOCKS == CRYPTO_num_locks());
    ASSERT(idx >= 0 && idx < CRYPTO_NUM_LOCKS);

    if(!(idx >= 0 && idx < CRYPTO_NUM_LOCKS))
    {    
        ostringstream oss;
        oss << "LockingFnc: lock failed with bad index ";
        oss << idx << ". File: " << (file ? file : "Unknown");
        oss << ", line: " << line;

        // Log oss.str()
        return;
    }

    if((mode & CRYPTO_LOCK) == CRYPTO_LOCK)
    {
        int rc = pthread_mutex_lock(&s_locks[idx]);
        int err = errno;
        ASSERT(rc == 0);

        if(!(rc == 0))
        {
            ostringstream oss;
            oss << "LockingFnc: lock failed with error ";
            oss << err << ". File: " << (file ? file : "Unknown");
            oss << ", line: " << line;          

            throw runtime_error(oss.str());
        }
    }
    else if((mode & CRYPTO_UNLOCK) == CRYPTO_UNLOCK)
    {
        int rc = pthread_mutex_unlock(&s_locks[idx]);
        int err = errno;
        ASSERT(rc == 0);

        if(!(rc == 0))
        {
            ostringstream oss;
            oss << "LockingFnc: unlock failed with error ";
            oss << err << ". File: " << (file ? file : "Unknown");
            oss << ", line: " << line;

            throw runtime_error(oss.str());
        }
    }
}

unsigned long ThreadIdFnc()
{
#if defined(AC_OS_APPLE)
    ASSERT(sizeof(unsigned long) >= sizeof(pid_t));
    return static_cast<unsigned long>(pthread_mach_thread_np(pthread_self()));
#elif defined(AC_OS_STARNIX)
    ASSERT(sizeof(unsigned long) >= sizeof(pid_t));
    return static_cast<unsigned long>(gettid());
#else
# error "Unsupported platform"
#endif
}

如果您未使用libssl,请放弃对SSL_library_init的通话。所有libcrypto需求都是OpenSSL_add_all_algorithms初始化的调用。


  

但是,SSL文档没有提到有关线程安全的任何内容。

是的,文档有时会留下一些不足之处。我知道很多人正在通过OpenSSL Foundation运行wiki来改进它。 Matt Caswell在简单记录http://wiki.openssl.org/index.php/Elliptic_Curve_Cryptography的椭圆曲线中做了很多工作。他还负责POD文件和MAN页面。请记住,Matt没有编写任何代码 - 他只是为其他人编写代码。

有一个关于初始化的页面,但它没有锁的代码。它在我的TODO清单上。请参阅http://wiki.openssl.org/index.php/Library_Initialization

相关问题