从libsodium中的密码生成密钥对

时间:2017-12-15 13:19:01

标签: public-key libsodium

我想使用libsodium从密码短语确定性地生成公钥/私钥对。 无论何时/何地用户键入他的密码,他/她都将返回相同的密钥对。

我的方法是以某种方式获取密码(例如fgets),用crypto_generichash哈希,然后将哈希用作种子crypto_sign_seed_keypair

#include <assert.h>
#include <string.h>
#include <sodium.h>

int main (void) {
    char passphrase[1024];
    printf("ENTER PASSPHRASE: ");
    {
        char* ret = fgets(passphrase, sizeof(passphrase), stdin);
        assert(ret != NULL);
        assert(passphrase[strlen(passphrase)-1] == '\n');
        passphrase[strlen(passphrase)-1] = '\0';
    }

    unsigned char hash[crypto_generichash_BYTES];
    {
        int ret = crypto_generichash(hash, crypto_generichash_BYTES,
                                     (unsigned char*)passphrase, strlen(passphrase),
                                     NULL, 0);
        assert(ret == 0);
    }

    unsigned char pk[crypto_sign_PUBLICKEYBYTES];
    unsigned char sk[crypto_sign_SECRETKEYBYTES];
    {
        assert(crypto_generichash_BYTES == crypto_sign_SEEDBYTES);
        int ret = crypto_sign_seed_keypair(pk, sk, hash);
        assert(ret == 0);
    }
    printf("PUBLIC KEY:\n");
    for (int i=0; i<crypto_sign_PUBLICKEYBYTES; i++) {
        printf("%02X ", pk[i]);
    }
    printf("\n");
    printf("PRIVATE KEY:\n");
    for (int i=0; i<crypto_sign_SECRETKEYBYTES; i++) {
        printf("%02X ", sk[i]);
    }
    printf("\n");

    return 0;
}

假设密码强,这个方案安全可行吗?

1 个答案:

答案 0 :(得分:0)

您的代码很好,但即使是强大的&#34;密码具有相当低的熵。因此,您可能希望使用password hashing function

,而不是通用哈希函数