代码之家  ›  专栏  ›  技术社区  ›  Siler

用opensslapi比较两个公钥

  •  1
  • Siler  · 技术社区  · 6 年前

    所以,从简单的事情开始,假设我们最初只关心比较RSA密钥。自从 public component of an RSA key 是模量 n e ,似乎我们可以试着从每个键中得到这两个数字,然后直接比较它们。如果它们相等,我们可以说这两个公钥相等。

    RSA_get0_key ,返回指向内部 BIGNUM 物体 , e ,和 d RSA BN_cmp 直接比较这些对象。所以C++代码将是:

    bool compare_pubkeys(const EVP_PKEY* k1, const EVP_PKEY* k2)
    {
        // make sure both keys are the same type
        const int tp1 = EVP_PKEY_type(k1->type);
        const int tp2 = EVP_PKEY_type(k2->type);
        if (tp1 != tp2) return false;
    
        if (tp1 == EVP_PKEY_RSA) {
            RSA* rsa1 = EVP_PKEY_get1_RSA(k1);
            RSA* rsa2 = EVP_PKEY_get1_RSA(k2);
    
            const BIGNUM* n1;
            const BIGNUM* e1;
            const BIGNUM* n2;
            const BIGNUM* e2;
            RSA_get0_key(rsa1, &n1, &e1, nullptr);
            RSA_get0_key(rsa2, &n2, &e2, nullptr);
            const bool result = BN_cmp(n1, n2) == 0 && BN_cmp(e1, e2) == 0;
    
            RSA_free(rsa1);
            RSA_free(rsa2);
            return result;
        }
        else { /* handle non-RSA keys later */ }
    
        return false;
    }
    

    我的问题 :这种方法有意义吗?我绝对不是密码学方面的专家,我对RSA密钥的工作原理有非常基本的了解,所以我不知道我的方法是否有问题。我的理解是,给定两个RSA密钥对,比较每一个 n e 这在概念上相当于检查两个公钥是否相同——但我又不是专家,所以我不确定这是否正确。

    那么,我的方法正确吗?

    1 回复  |  直到 6 年前
        1
  •  5
  •   arved    6 年前

    有一个函数叫做EVP\u PKEY\u cmp,它似乎在做你想做的事情。

    看见 https://www.openssl.org/docs/man1.0.2/crypto/EVP_PKEY_cmp.html