且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

验证OpenSSL中的RSA公钥?

更新时间:2023-01-18 10:25:41

借助@jww在此答案中 https://***.com/a/29885771/2692914 .我想出了这个解决方案,希望可以:

With the help of @jww in this answer https://***.com/a/29885771/2692914. I came up with this solution, I hope it is ok:

bool isValidPublicKeyOnly(EVP_PKEY *pkey) {
    //EVP_PKEY_get_type from https://***.com/a/29885771/2692914
    int type = EVP_PKEY_get_type(pkey); //checks nullptr
    if (type != EVP_PKEY_RSA && type != EVP_PKEY_RSA2) {
        //not RSA
        return false;
    }

    RSA *rsa = EVP_PKEY_get1_RSA(pkey);
    if (!rsa) {
        return false;
    }

    bool isValid = isValidRSAPublicKeyOnly(rsa);
    RSA_free(rsa);
    return isValid;
}

bool isValidRSAPublicKeyOnly(RSA *rsa) {
    //from rsa_ameth.c do_rsa_print : has a private key
    //from rsa_chk.c RSA_check_key : doesn't have n (modulus) and e (public exponent)
    if (!rsa || rsa->d || !rsa->n || !rsa->e) {
        return false;
    }
    //from http://rt.openssl.org/Ticket/Display.html?user=guest&pass=guest&id=1454
    //doesnt have a valid public exponent
    return BN_is_odd(rsa->e) && !BN_is_one(rsa->e);
}