/*
* Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the Apache License 2.0 (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
#include <stdio.h>
#include <openssl/crypto.h>
#include <openssl/core_names.h>
#include <openssl/engine.h>
#include <openssl/evp.h>
#include "internal/cryptlib.h"
#include "internal/refcount.h"
#include "crypto/bn.h"
#include "crypto/evp.h"
#include "crypto/rsa.h"
#include "rsa_local.h"
RSA *RSA_new(void)
{
return RSA_new_method(NULL);
}
const RSA_METHOD *RSA_get_method(const RSA *rsa)
{
return rsa->meth;
}
int RSA_set_method(RSA *rsa, const RSA_METHOD *meth)
{
/*
* NB: The caller is specifically setting a method, so it's not up to us
* to deal with which ENGINE it comes from.
*/
const RSA_METHOD *mtmp;
mtmp = rsa->meth;
if (mtmp->finish)
mtmp->finish(rsa);
#ifndef OPENSSL_NO_ENGINE
ENGINE_finish(rsa->engine);
rsa->engine = NULL;
#endif
rsa->meth = meth;
if (meth->init)
meth->init(rsa);
return 1;
}
RSA *RSA_new_method(ENGINE *engine)
{
RSA *ret = OPENSSL_zalloc(sizeof(*ret));
if (ret == NULL) {
RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_MALLOC_FAILURE);
return NULL;
}
ret->references = 1;
ret->lock = CRYPTO_THREAD_lock_new();
if (ret->lock == NULL) {
RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_MALLOC_FAILURE);
OPENSSL_free(ret);
return NULL;
}
ret->meth = RSA_get_default_method();
#ifndef OPENSSL_NO_ENGINE
ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
if (engine) {
if (!ENGINE_init(engine)) {
RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_ENGINE_LIB);
goto err;
}
ret->engine = engine;
} else {
ret->engine = ENGINE_get_default_RSA();
}
if (ret->engine) {
ret->meth = ENGINE_get_RSA(ret->engine);
if (ret->meth == NULL) {
RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_ENGINE_LIB);
goto err;
}
}
#endif
ret->flags = ret->meth->flags & ~RSA_FLAG_NON_FIPS_ALLOW;
#ifndef FIPS_MODE
if (!CRYPTO_new_ex_data(CRYPTO_EX_INDEX_RSA, ret, &ret->ex_data)) {
goto err;
}
#endif
if ((ret->meth->init != NULL) && !ret->meth->init(ret)) {
RSAerr(RSA_F_RSA_NEW_METHOD, ERR_R_INIT_FAIL);
goto err;
}
return ret;
err:
RSA_free(ret);
return NULL;
}
void RSA_free(RSA *r)
{
int i;
if (r == NULL)
return;