本文整理汇总了C++中RSA_size函数的典型用法代码示例。如果您正苦于以下问题:C++ RSA_size函数的具体用法?C++ RSA_size怎么用?C++ RSA_size使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了RSA_size函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: _cjose_jws_verify_sig_ps
static bool _cjose_jws_verify_sig_ps(cjose_jws_t *jws, const cjose_jwk_t *jwk, cjose_err *err)
{
bool retval = false;
uint8_t *em = NULL;
size_t em_len = 0;
// ensure jwk is RSA
if (jwk->kty != CJOSE_JWK_KTY_RSA)
{
CJOSE_ERROR(err, CJOSE_ERR_INVALID_ARG);
goto _cjose_jws_verify_sig_ps_cleanup;
}
// make sure we have an alg header
json_t *alg_obj = json_object_get(jws->hdr, CJOSE_HDR_ALG);
if (NULL == alg_obj)
{
CJOSE_ERROR(err, CJOSE_ERR_INVALID_ARG);
return false;
}
const char *alg = json_string_value(alg_obj);
// build digest using SHA-256/384/512 digest algorithm
const EVP_MD *digest_alg = NULL;
if (strcmp(alg, CJOSE_HDR_ALG_PS256) == 0)
digest_alg = EVP_sha256();
else if (strcmp(alg, CJOSE_HDR_ALG_PS384) == 0)
digest_alg = EVP_sha384();
else if (strcmp(alg, CJOSE_HDR_ALG_PS512) == 0)
digest_alg = EVP_sha512();
if (NULL == digest_alg)
{
CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
goto _cjose_jws_verify_sig_ps_cleanup;
}
// allocate buffer for encoded message
em_len = RSA_size((RSA *)jwk->keydata);
em = (uint8_t *)cjose_get_alloc()(em_len);
if (NULL == em)
{
CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
goto _cjose_jws_verify_sig_ps_cleanup;
}
// decrypt signature
if (RSA_public_decrypt(jws->sig_len, jws->sig, em, (RSA *)jwk->keydata, RSA_NO_PADDING) != em_len)
{
CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
goto _cjose_jws_verify_sig_ps_cleanup;
}
// verify decrypted signature data against PSS encoded digest
if (RSA_verify_PKCS1_PSS((RSA *)jwk->keydata, jws->dig, digest_alg, em, -1) != 1)
{
CJOSE_ERROR(err, CJOSE_ERR_CRYPTO);
goto _cjose_jws_verify_sig_ps_cleanup;
}
// if we got this far - success
retval = true;
_cjose_jws_verify_sig_ps_cleanup:
cjose_get_dealloc()(em);
return retval;
}
示例2: rsa_default_verify_raw
int rsa_default_verify_raw(RSA *rsa, size_t *out_len, uint8_t *out,
size_t max_out, const uint8_t *in, size_t in_len,
int padding) {
const unsigned rsa_size = RSA_size(rsa);
BIGNUM *f, *result;
int ret = 0;
int r = -1;
uint8_t *buf = NULL;
BN_CTX *ctx = NULL;
if (max_out < rsa_size) {
OPENSSL_PUT_ERROR(RSA, RSA_R_OUTPUT_BUFFER_TOO_SMALL);
return 0;
}
if (!check_modulus_and_exponent_sizes(rsa)) {
return 0;
}
ctx = BN_CTX_new();
if (ctx == NULL) {
goto err;
}
BN_CTX_start(ctx);
f = BN_CTX_get(ctx);
result = BN_CTX_get(ctx);
if (padding == RSA_NO_PADDING) {
buf = out;
} else {
/* Allocate a temporary buffer to hold the padded plaintext. */
buf = OPENSSL_malloc(rsa_size);
if (buf == NULL) {
OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
goto err;
}
}
if (!f || !result) {
OPENSSL_PUT_ERROR(RSA, ERR_R_MALLOC_FAILURE);
goto err;
}
if (in_len != rsa_size) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_LEN_NOT_EQUAL_TO_MOD_LEN);
goto err;
}
if (BN_bin2bn(in, in_len, f) == NULL) {
goto err;
}
if (BN_ucmp(f, rsa->n) >= 0) {
OPENSSL_PUT_ERROR(RSA, RSA_R_DATA_TOO_LARGE_FOR_MODULUS);
goto err;
}
if (rsa->flags & RSA_FLAG_CACHE_PUBLIC) {
if (BN_MONT_CTX_set_locked(&rsa->mont_n, &rsa->lock, rsa->n, ctx) == NULL) {
goto err;
}
}
if (!rsa->meth->bn_mod_exp(result, f, rsa->e, rsa->n, ctx, rsa->mont_n)) {
goto err;
}
if (!BN_bn2bin_padded(buf, rsa_size, result)) {
OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR);
goto err;
}
switch (padding) {
case RSA_PKCS1_PADDING:
r = RSA_padding_check_PKCS1_type_1(out, rsa_size, buf, rsa_size);
break;
case RSA_NO_PADDING:
r = rsa_size;
break;
default:
OPENSSL_PUT_ERROR(RSA, RSA_R_UNKNOWN_PADDING_TYPE);
goto err;
}
if (r < 0) {
OPENSSL_PUT_ERROR(RSA, RSA_R_PADDING_CHECK_FAILED);
} else {
*out_len = r;
ret = 1;
}
err:
if (ctx != NULL) {
BN_CTX_end(ctx);
BN_CTX_free(ctx);
}
if (padding != RSA_NO_PADDING && buf != NULL) {
OPENSSL_cleanse(buf, rsa_size);
OPENSSL_free(buf);
}
return ret;
//.........这里部分代码省略.........
示例3: openssl_rsa_crypt
void openssl_rsa_crypt()
{
RSA *r;
BIO *b;
BIGNUM *bne;
unsigned int len;
int size, elen, dlen;
unsigned char inputs[COMM_LEN] = "rsa crypt";
unsigned char tmps[MAX1_LEN], outputs[MAX1_LEN];
memset(tmps, 0, sizeof(tmps));
memset(outputs, 0, sizeof(outputs));
printf("\nRSA generate key:\n");
bne = BN_new();
BN_set_word(bne, RSA_3);
r = RSA_new();
RSA_generate_key_ex(r, MAX1_LEN, bne, NULL);
RSA_print_fp(stdout, r, 11);
b = BIO_new_file("/tmp/rsa.key", "w");
i2d_RSAPrivateKey_bio(b, r);
BIO_free(b);
elen = RSA_private_encrypt(RSA_size(r) - 11,
inputs, outputs, r, RSA_PKCS1_PADDING);
dlen = RSA_public_decrypt(elen, outputs, tmps, r, RSA_PKCS1_PADDING);
if (elen <= 0 || dlen <= 0 || memcmp(inputs, tmps, RSA_size(r) - 11)) {
printf("RSA_private_encrypt error!\n");
RSA_free(r);
return;
}
printf("RSA_private_encrypt(%s) = ", inputs);
for (size = 0; size < elen; size++)
printf("%02x", outputs[size]);
printf("\n");
memset(outputs, 0, sizeof(outputs));
elen = RSA_public_encrypt(RSA_size(r) - 11,
inputs, outputs, r, RSA_PKCS1_PADDING);
dlen = RSA_private_decrypt(elen, outputs, tmps, r, RSA_PKCS1_PADDING);
if (elen <= 0 || dlen <= 0 || memcmp(inputs, tmps, RSA_size(r) - 11)) {
printf("RSA_public_encrypt error!\n");
RSA_free(r);
return;
}
printf("RSA_public_encrypt(%s) = ", inputs);
for (size = 0; size < elen; size++)
printf("%02x", outputs[size]);
printf("\n");
memset(outputs, 0, sizeof(outputs));
RSA_sign(NID_md5_sha1, inputs, 36, outputs, &len, r);
printf("RSA_sign(%s) = ", inputs);
for (size = 0; size < len; size++)
printf("%02x", outputs[size]);
printf("\n");
memset(tmps, 0, sizeof(tmps));
RSA_verify(NID_md5_sha1, inputs, 36, outputs, len, r);
printf("RSA_verify(");
for (size = 0; size < len; size++)
printf("%02x", outputs[size]);
printf(") = %s\n", inputs);
RSA_free(r);
}
示例4: bdd_do_select
int bdd_do_select ( char *safe_trame )
{
// Déclaration variable
char* morceau = NULL ; // Variable contenant chaque morceau de la trame (strtok_r)
char* statut = NULL ;
char* affectation = NULL ;
char* groupes = NULL ;
char* reference = NULL ;
int cpt = 0 ; // Compteur
MYSQL_RES* resultat_req ; // Object MYSQL décrivant le résultat d'une requête
MYSQL_ROW tuple ; // Object MYSQL décrivant un tuple dans la liste résultat
char* safe_tuple = NULL ; // Permet d'appeler strtok_r sur le bon contenu.
char* valeur = NULL ;
char* politique = NULL ;
int code_retour = 0 ;
// On découpe les 4 éléments restant de notre trame
for ( cpt = 0; cpt < 4; cpt++ )
{
// On découpe la trame en morceaux repérés via un "*"
if ( ( morceau = strtok_r ( NULL, "*", &safe_trame ) ) == NULL )
{
perror ( "Erreur_bdd_do_select : information manquante " ) ;
bdd_send_msg ( SELECT, "ERROR" ) ;
return ERRNO ;
}
// On vérifie que l'information est présente
if ( strcmp ( morceau, "EOF") == 0 )
{
perror ( "Erreur_bdd_do_select : information manquante II" ) ;
bdd_send_msg ( SELECT, "ERROR" ) ;
return ERRNO ;
}
else
{
// On affecte l'information
switch ( cpt )
{
case ZERO :
statut = morceau ;
break ;
case UN :
affectation = morceau ;
break ;
case DEUX :
groupes = morceau ;
break ;
case TROIS :
reference = morceau ;
break ;
default :
perror ( "Erreur_do_select : overflow compteur cpt " ) ;
bdd_send_msg ( SELECT, "ERROR" ) ;
return ERRNO ;
break ;
}
}
}
// On récupère auprès de la BDD, la valeur associée à cette référence
if ( bdd_do_request ( mysql_bdd, SELECT, reference, NULL, &resultat_req ) == ERRNO )
{
perror ( "Erreur_bdd_do_select : bad requete " ) ;
mysql_free_result ( resultat_req ) ;
bdd_send_msg ( SELECT, "ERROR" ) ;
return ERRNO ;
}
// On récupère le tuple
if ( ( tuple = mysql_fetch_row ( resultat_req ) ) == NULL )
{
perror ( "Erreur_bdd_do_select : bad tuple " ) ;
mysql_free_result ( resultat_req ) ;
bdd_send_msg ( SELECT, "ERROR" ) ;
return ERRNO ;
}
// On déchiffre le tuple
char* output = (char*) malloc ( RSA_size ( bdd_key ) * sizeof ( char ) ) ;
memset ( output, '\0', RSA_size ( bdd_key ) ) ;
if ( RSA_chiffrement ( (unsigned char*) tuple[0], (unsigned char*) output, DECHIFFREMENT ) != TRUE )
{
perror ( "Erreur_bdd_do_select : RSA_dechiffrement " ) ;
free ( output ) ;
mysql_free_result ( resultat_req ) ;
bdd_send_msg ( SELECT, "ERROR" ) ;
return ERRNO ;
}
// On récupère les 3 informations du tuple
morceau = NULL ;
for ( cpt = 0; cpt < 3; cpt++ )
{
// On découpe le tuple en morceaux repérés via un "*"
if ( cpt == 0 )
//.........这里部分代码省略.........
示例5: bdd_do_request
int bdd_do_request ( MYSQL* mysql_bdd, int action, char* reference, char* valeur, MYSQL_RES** resultat_req )
{
// Initialisation
char *requete = (char*) malloc ( TAILLE_REQUETE * sizeof ( char ) ) ;
memset ( requete, '\0', TAILLE_REQUETE ) ;
int return_value ;
// On prépare la zone mémoire de sortie (chiffrement)
int i = 0 ;
int good = FALSE ;
char* insertion = (char*) malloc ( RSA_size ( bdd_key ) * sizeof ( char ) ) ;
memset ( insertion, '\0', RSA_size ( bdd_key ) ) ;
// Chiffrement BDD
if ( action == INSERT )
{
// On vérifie la taille du buffer d'entrée
if ( strlen ( valeur ) <= ( TAILLE_MAX_UTILE - 1 ) )
{
// Tant que le chiffré n'est pas bon
while ( good != TRUE )
{
// Ini
memset ( insertion, '\0', RSA_size ( bdd_key ) ) ;
// On chiffre
if ( RSA_chiffrement ( (unsigned char*) valeur, (unsigned char*) insertion, CHIFFREMENT ) != TRUE )
{
perror ( "Erreur_bdd_do_request : RSA_chiffrement " ) ;
free ( insertion ) ;
free ( requete ) ;
return ERRNO ;
}
// On suppose chiffré bon
good = TRUE ;
// On vérifie la non présence du caractère ", \ et \0
for ( i = 0; i < TAILLE_MAX_RSA; i ++ )
{
if ( ( (int) insertion[i] == APOSTROPHE ) || ( (int) insertion[i] == BACK_SLASH ) || ( (int) insertion[i] == ZERO_TERMINAL ) )
good = FALSE ;
}
}
}
}
// On prépare la requête selon l'action à faire
switch ( action )
{
case SELECT_ALL :
sprintf ( requete, "select REF, VAL from %s;", TABLE ) ;
break ;
case SELECT :
sprintf ( requete, "select VAL from %s where REF = \"%s\";", TABLE, reference ) ;
break ;
case INSERT :
sprintf ( requete, "insert into %s (REF, VAL) values(\"%s\",\"%s\");", TABLE, reference, insertion ) ;
break ;
case DELETE :
sprintf ( requete, "delete from %s where REF = \"%s\";", TABLE, reference ) ;
break ;
case DELETE_ALL :
sprintf ( requete, "delete from %s;", TABLE ) ;
break ;
default :
perror ( "Erreur_bdd_do_request : bad action " ) ;
free ( requete ) ;
free ( insertion ) ;
return ERRNO ;
break ;
}
// On réalise la requête
if ( ( return_value = mysql_query ( mysql_bdd, requete ) ) != 0 )
{
fprintf ( stderr, "Erreur_bdd_do_request : mysql_query avec code action : %d \n", action ) ;
fprintf ( stderr, "Erreur_bdd_do_request : mysql_query avec requete : %s \n", requete ) ;
fprintf ( stderr, "Erreur_bdd_do_request : mysql_query avec retour : %d \n", return_value ) ;
free ( requete ) ;
free ( insertion ) ;
return ERRNO ;
}
// Selon l'action réalisée, on récupère des résultats
if ( ( action == SELECT_ALL ) || ( action == SELECT ) )
{
if ( ( *resultat_req = mysql_use_result ( mysql_bdd ) ) == NULL )
{
perror ( "Erreur_bdd_do_request : mysql_use_result " ) ;
free ( requete ) ;
free ( insertion ) ;
return ERRNO ;
}
}
//.........这里部分代码省略.........
示例6: ssh_rsa_sign
/* RSASSA-PKCS1-v1_5 (PKCS #1 v2.0 signature) with SHA1 */
int
ssh_rsa_sign(const Key *key, u_char **sigp, u_int *lenp,
const u_char *data, u_int datalen)
{
const EVP_MD *evp_md;
EVP_MD_CTX md;
u_char digest[EVP_MAX_MD_SIZE], *sig;
u_int slen, dlen, len;
int ok, nid;
Buffer b;
if (key == NULL || key->type != KEY_RSA || key->rsa == NULL) {
pamsshagentauth_logerror("ssh_rsa_sign: no RSA key");
return -1;
}
nid = (datafellows & SSH_BUG_RSASIGMD5) ? NID_md5 : NID_sha1;
if ((evp_md = EVP_get_digestbynid(nid)) == NULL) {
pamsshagentauth_logerror("ssh_rsa_sign: EVP_get_digestbynid %d failed", nid);
return -1;
}
EVP_DigestInit(&md, evp_md);
EVP_DigestUpdate(&md, data, datalen);
EVP_DigestFinal(&md, digest, &dlen);
slen = RSA_size(key->rsa);
sig = pamsshagentauth_xmalloc(slen);
ok = RSA_sign(nid, digest, dlen, sig, &len, key->rsa);
memset(digest, 'd', sizeof(digest));
if (ok != 1) {
int ecode = ERR_get_error();
pamsshagentauth_logerror("ssh_rsa_sign: RSA_sign failed: %s",
ERR_error_string(ecode, NULL));
pamsshagentauth_xfree(sig);
return -1;
}
if (len < slen) {
u_int diff = slen - len;
pamsshagentauth_verbose("slen %u > len %u", slen, len);
memmove(sig + diff, sig, len);
memset(sig, 0, diff);
} else if (len > slen) {
pamsshagentauth_logerror("ssh_rsa_sign: slen %u slen2 %u", slen, len);
pamsshagentauth_xfree(sig);
return -1;
}
/* encode signature */
pamsshagentauth_buffer_init(&b);
pamsshagentauth_buffer_put_cstring(&b, "ssh-rsa");
pamsshagentauth_buffer_put_string(&b, sig, slen);
len = pamsshagentauth_buffer_len(&b);
if (lenp != NULL)
*lenp = len;
if (sigp != NULL) {
*sigp = pamsshagentauth_xmalloc(len);
memcpy(*sigp, pamsshagentauth_buffer_ptr(&b), len);
}
pamsshagentauth_buffer_free(&b);
memset(sig, 's', slen);
pamsshagentauth_xfree(sig);
return 0;
}
示例7: _
/* called by CSPFullPluginSession */
void RSA_CryptContext::init(const Context &context, bool encoding /*= true*/)
{
StLock<Mutex> _(gMutex());
if(mInitFlag && !opStarted()) {
/* reusing - e.g. query followed by encrypt */
return;
}
/* optional mode to use alternate key class (e.g., decrypt with public key) */
CSSM_KEYCLASS keyClass;
switch (context.getInt(CSSM_ATTRIBUTE_MODE)) {
case CSSM_ALGMODE_PUBLIC_KEY:
keyClass = CSSM_KEYCLASS_PUBLIC_KEY;
break;
case CSSM_ALGMODE_PRIVATE_KEY:
keyClass = CSSM_KEYCLASS_PRIVATE_KEY;
break;
case CSSM_ALGMODE_NONE:
/* default, not present in context: infer from op type */
keyClass = encoding ? CSSM_KEYCLASS_PUBLIC_KEY : CSSM_KEYCLASS_PRIVATE_KEY;
break;
default:
CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_MODE);
}
/* fetch key from context */
if(mRsaKey == NULL) {
assert(!opStarted());
CSSM_DATA label = {0, NULL};
mRsaKey = contextToRsaKey(context,
session(),
keyClass,
encoding ? CSSM_KEYUSE_ENCRYPT : CSSM_KEYUSE_DECRYPT,
mAllocdRsaKey,
label);
if(label.Data) {
mLabel.copy(label);
mOaep = true;
free(label.Data);
}
}
else {
assert(opStarted());
}
unsigned cipherBlockSize = RSA_size(mRsaKey);
unsigned plainBlockSize;
/* padding - not present means value zero, CSSM_PADDING_NONE */
uint32 padding = context.getInt(CSSM_ATTRIBUTE_PADDING);
switch(padding) {
case CSSM_PADDING_NONE:
mPadding = RSA_NO_PADDING;
plainBlockSize = cipherBlockSize;
break;
case CSSM_PADDING_PKCS1:
mPadding = RSA_PKCS1_PADDING;
plainBlockSize = cipherBlockSize - 11;
break;
case CSSM_PADDING_APPLE_SSLv2:
rsaCryptDebug("RSA_CryptContext::init using CSSM_PADDING_APPLE_SSLv2");
mPadding = RSA_SSLV23_PADDING;
plainBlockSize = cipherBlockSize - 11;
break;
default:
rsaCryptDebug("RSA_CryptContext::init bad padding (0x%x)",
(unsigned)padding);
CssmError::throwMe(CSSMERR_CSP_INVALID_ATTR_PADDING);
}
/* optional blinding attribute */
uint32 blinding = context.getInt(CSSM_ATTRIBUTE_RSA_BLINDING);
if(blinding) {
if(RSA_blinding_on(mRsaKey, NULL) <= 0) {
/* actually no legit failures */
CssmError::throwMe(CSSMERR_CSP_INTERNAL_ERROR);
}
}
else {
RSA_blinding_off(mRsaKey);
}
/* finally, have BlockCryptor set up its stuff. */
setup(encoding ? plainBlockSize : cipherBlockSize, // blockSizeIn
encoding ? cipherBlockSize : plainBlockSize, // blockSizeOut
false, // pkcs5Pad
false, // needsFinal
BCM_ECB,
NULL); // IV
mInitFlag = true;
}
示例8: pkey_rsa_sign
static int pkey_rsa_sign(EVP_PKEY_CTX *ctx, unsigned char *sig,
size_t *siglen, const unsigned char *tbs,
size_t tbslen)
{
int ret;
RSA_PKEY_CTX *rctx = ctx->data;
RSA *rsa = ctx->pkey->pkey.rsa;
if (rctx->md) {
if (tbslen != (size_t)EVP_MD_size(rctx->md)) {
RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_INVALID_DIGEST_LENGTH);
return -1;
}
if (EVP_MD_type(rctx->md) == NID_mdc2) {
unsigned int sltmp;
if (rctx->pad_mode != RSA_PKCS1_PADDING)
return -1;
ret = RSA_sign_ASN1_OCTET_STRING(0,
tbs, tbslen, sig, &sltmp, rsa);
if (ret <= 0)
return ret;
ret = sltmp;
} else if (rctx->pad_mode == RSA_X931_PADDING) {
if ((size_t)EVP_PKEY_size(ctx->pkey) < tbslen + 1) {
RSAerr(RSA_F_PKEY_RSA_SIGN, RSA_R_KEY_SIZE_TOO_SMALL);
return -1;
}
if (!setup_tbuf(rctx, ctx)) {
RSAerr(RSA_F_PKEY_RSA_SIGN, ERR_R_MALLOC_FAILURE);
return -1;
}
memcpy(rctx->tbuf, tbs, tbslen);
rctx->tbuf[tbslen] = RSA_X931_hash_id(EVP_MD_type(rctx->md));
ret = RSA_private_encrypt(tbslen + 1, rctx->tbuf,
sig, rsa, RSA_X931_PADDING);
} else if (rctx->pad_mode == RSA_PKCS1_PADDING) {
unsigned int sltmp;
ret = RSA_sign(EVP_MD_type(rctx->md),
tbs, tbslen, sig, &sltmp, rsa);
if (ret <= 0)
return ret;
ret = sltmp;
} else if (rctx->pad_mode == RSA_PKCS1_PSS_PADDING) {
if (!setup_tbuf(rctx, ctx))
return -1;
if (!RSA_padding_add_PKCS1_PSS_mgf1(rsa,
rctx->tbuf, tbs,
rctx->md, rctx->mgf1md,
rctx->saltlen))
return -1;
ret = RSA_private_encrypt(RSA_size(rsa), rctx->tbuf,
sig, rsa, RSA_NO_PADDING);
} else {
return -1;
}
} else {
ret = RSA_private_encrypt(tbslen, tbs, sig, ctx->pkey->pkey.rsa,
rctx->pad_mode);
}
if (ret < 0)
return ret;
*siglen = ret;
return 1;
}
示例9: ssh_encrypt_rsa1
ssh_string ssh_encrypt_rsa1(ssh_session session, ssh_string data, ssh_public_key key) {
ssh_string str = NULL;
size_t len = string_len(data);
size_t size = 0;
#ifdef HAVE_LIBGCRYPT
const char *tmp = NULL;
gcry_sexp_t ret_sexp;
gcry_sexp_t data_sexp;
if (gcry_sexp_build(&data_sexp, NULL, "(data(flags pkcs1)(value %b))",
len, string_data(data))) {
ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
return NULL;
}
if (gcry_pk_encrypt(&ret_sexp, data_sexp, key->rsa_pub)) {
gcry_sexp_release(data_sexp);
ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
return NULL;
}
gcry_sexp_release(data_sexp);
data_sexp = gcry_sexp_find_token(ret_sexp, "a", 0);
if (data_sexp == NULL) {
ssh_set_error(session, SSH_FATAL, "RSA1 encrypt: libgcrypt error");
gcry_sexp_release(ret_sexp);
return NULL;
}
tmp = gcry_sexp_nth_data(data_sexp, 1, &size);
if (*tmp == 0) {
size--;
tmp++;
}
str = string_new(size);
if (str == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
gcry_sexp_release(data_sexp);
gcry_sexp_release(ret_sexp);
return NULL;
}
string_fill(str, tmp, size);
gcry_sexp_release(data_sexp);
gcry_sexp_release(ret_sexp);
#elif defined HAVE_LIBCRYPTO
size = RSA_size(key->rsa_pub);
str = string_new(size);
if (str == NULL) {
ssh_set_error(session, SSH_FATAL, "Not enough space");
return NULL;
}
if (RSA_public_encrypt(len, string_data(data), string_data(str), key->rsa_pub,
RSA_PKCS1_PADDING) < 0) {
string_free(str);
return NULL;
}
#endif
return str;
}
示例10: main
//.........这里部分代码省略.........
int t3 = sprintf(tmp3, "%i", part3);
char p3[t3];
strcpy(p3, tmp3);
/* Costruisco la chiave di sessione */
int dim_ses = t1 + t2 + t3; //Numero di caratteri della chiave di sessione
char *ses_key = (char*) malloc (dim_ses);
bzero(ses_key, dim_ses);
strcpy(ses_key, p1);
strcat(ses_key, p2);
strcat(ses_key, p3);
/* Setto la chiave di sessione */
BF_KEY kcs;
BF_set_key(&kcs, dim_ses, (const unsigned char*)ses_key);
/* Costruisco il messaggio M3 da criptare e inviare al client */
int sep3 = 4; //Numero di separatori da inserire nel messaggio M3
int ids3 = 2; //Numero di identificatori da inserire nel messaggio M3
int dim3 = ids3 + n + np + dim_ses + sep3;
char *m3 = (char*) malloc(dim3 + 1);
bzero(m3, dim3 + 1);
strcpy(m3, "C");
strcat(m3, " ");
strcat(m3, "S");
strcat(m3, " ");
strcat(m3, nounce);
strcat(m3, " ");
strcat(m3, CLIENT_PWD);
strcat(m3, " ");
strcat(m3, ses_key);
/* Cripto il messaggio M3 con la chiave pubblica */
unsigned char *m3c = (unsigned char*) malloc(RSA_size(pub_key));
bzero(m3c, RSA_size(pub_key));
int nc; //Numero di byte restituiti dalla cifratura
nc = RSA_public_encrypt(dim3, (unsigned char*)m3, m3c, pub_key, RSA_PKCS1_OAEP_PADDING);
if(nc == -1) {
cerr << "Errore: funzione <RSA_public_encrypt> sul messaggio M3 non effettuata con successo" << endl;
exit(1);
}
if(nc == 0) {
cerr << "Errore: messaggio M3 non criptato correttamente" << endl;
exit(1);
}
/* Invio al server la dimensione del messaggio cifrato */
int dim3c = RSA_size(pub_key);
ret = send(cl_sk, &dim3c, 4, 0);
if(ret == -1) {
cerr << "Errore: dimensione del messaggio cifrato M3 non inviata correttamente" << endl;
return -1;
}
/* Invio al server il messaggio cifrato M3 */
ret = send(cl_sk, m3c, dim3c, 0);
if(ret == -1) {
cerr << "Errore: messaggio cifrato M3 non inviato correttamente" << endl;
return -1;
}
cout << "\033[32m:: C -> S\033[0m" << endl;
cout << "\033[34m:: Messaggio cifrato M3 inviato al server\033[0m" << endl;
cout << endl;
/* Ricevo dal server la dimensione il messaggio criptato M4 */
示例11: output
/* Pre-processes and outputs RSA public key to standard out.
*/
void output(RSA* key) {
int i, nwords;
const BIGNUM *key_n;
BIGNUM *N = NULL;
BIGNUM *Big1 = NULL, *Big2 = NULL, *Big32 = NULL, *BigMinus1 = NULL;
BIGNUM *B = NULL;
BIGNUM *N0inv= NULL, *R = NULL, *RR = NULL, *RRTemp = NULL, *NnumBits = NULL;
BIGNUM *n = NULL, *rr = NULL;
BN_CTX *bn_ctx = BN_CTX_new();
uint32_t n0invout;
/* Output size of RSA key in 32-bit words */
nwords = RSA_size(key) / 4;
if (-1 == write(1, &nwords, sizeof(nwords)))
goto failure;
/* Initialize BIGNUMs */
RSA_get0_key(key, &key_n, NULL, NULL);
N = BN_dup(key_n);
Big1 = BN_new();
Big2 = BN_new();
Big32 = BN_new();
BigMinus1 = BN_new();
N0inv= BN_new();
R = BN_new();
RR = BN_new();
RRTemp = BN_new();
NnumBits = BN_new();
n = BN_new();
rr = BN_new();
BN_set_word(Big1, 1L);
BN_set_word(Big2, 2L);
BN_set_word(Big32, 32L);
BN_sub(BigMinus1, Big1, Big2);
B = BN_new();
BN_exp(B, Big2, Big32, bn_ctx); /* B = 2^32 */
/* Calculate and output N0inv = -1 / N[0] mod 2^32 */
BN_mod_inverse(N0inv, N, B, bn_ctx);
BN_sub(N0inv, B, N0inv);
n0invout = BN_get_word(N0inv);
if (-1 == write(1, &n0invout, sizeof(n0invout)))
goto failure;
/* Calculate R = 2^(# of key bits) */
BN_set_word(NnumBits, BN_num_bits(N));
BN_exp(R, Big2, NnumBits, bn_ctx);
/* Calculate RR = R^2 mod N */
BN_copy(RR, R);
BN_mul(RRTemp, RR, R, bn_ctx);
BN_mod(RR, RRTemp, N, bn_ctx);
/* Write out modulus as little endian array of integers. */
for (i = 0; i < nwords; ++i) {
uint32_t nout;
BN_mod(n, N, B, bn_ctx); /* n = N mod B */
nout = BN_get_word(n);
if (-1 == write(1, &nout, sizeof(nout)))
goto failure;
BN_rshift(N, N, 32); /* N = N/B */
}
/* Write R^2 as little endian array of integers. */
for (i = 0; i < nwords; ++i) {
uint32_t rrout;
BN_mod(rr, RR, B, bn_ctx); /* rr = RR mod B */
rrout = BN_get_word(rr);
if (-1 == write(1, &rrout, sizeof(rrout)))
goto failure;
BN_rshift(RR, RR, 32); /* RR = RR/B */
}
failure:
/* Free BIGNUMs. */
BN_free(N);
BN_free(Big1);
BN_free(Big2);
BN_free(Big32);
BN_free(BigMinus1);
BN_free(N0inv);
BN_free(R);
BN_free(RRTemp);
BN_free(NnumBits);
BN_free(n);
BN_free(rr);
}
示例12: __pkcs11h_openssl_rsa_enc
static
int
__pkcs11h_openssl_rsa_enc (
IN int flen,
IN unsigned char *from,
OUT unsigned char *to,
IN OUT RSA *rsa,
IN int padding
) {
#else
static
int
__pkcs11h_openssl_rsa_enc (
IN int flen,
IN const unsigned char *from,
OUT unsigned char *to,
IN OUT RSA *rsa,
IN int padding
) {
#endif
pkcs11h_certificate_t certificate = __pkcs11h_openssl_rsa_get_pkcs11h_certificate (rsa);
PKCS11H_BOOL session_locked = FALSE;
CK_RV rv = CKR_FUNCTION_FAILED;
size_t tlen;
_PKCS11H_ASSERT (from!=NULL);
_PKCS11H_ASSERT (to!=NULL);
_PKCS11H_ASSERT (rsa!=NULL);
_PKCS11H_DEBUG (
PKCS11H_LOG_DEBUG2,
"PKCS#11: __pkcs11h_openssl_rsa_enc entered - flen=%d, from=%p, to=%p, rsa=%p, padding=%d",
flen,
from,
to,
(void *)rsa,
padding
);
if (padding != RSA_PKCS1_PADDING) {
rv = CKR_MECHANISM_INVALID;
goto cleanup;
}
tlen = (size_t)RSA_size(rsa);
if ((rv = pkcs11h_certificate_lockSession (certificate)) != CKR_OK) {
goto cleanup;
}
session_locked = TRUE;
_PKCS11H_DEBUG (
PKCS11H_LOG_DEBUG1,
"PKCS#11: Performing signature"
);
if (
(rv = pkcs11h_certificate_signAny (
certificate,
CKM_RSA_PKCS,
from,
flen,
to,
&tlen
)) != CKR_OK
) {
_PKCS11H_LOG (PKCS11H_LOG_WARN, "PKCS#11: Cannot perform signature %ld:'%s'", rv, pkcs11h_getMessage (rv));
goto cleanup;
}
rv = CKR_OK;
cleanup:
if (session_locked) {
pkcs11h_certificate_releaseSession (certificate);
session_locked = FALSE;
}
_PKCS11H_DEBUG (
PKCS11H_LOG_DEBUG2,
"PKCS#11: __pkcs11h_openssl_rsa_enc - return rv=%lu-'%s'",
rv,
pkcs11h_getMessage (rv)
);
return rv == CKR_OK ? (int)tlen : -1;
}
示例13: RSA_verify_PKCS1_PSS_mgf1
int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
const unsigned char *EM, int sLen)
{
int i;
int ret = 0;
int hLen, maskedDBLen, MSBits, emLen;
const unsigned char *H;
unsigned char *DB = NULL;
EVP_MD_CTX ctx;
unsigned char H_[EVP_MAX_MD_SIZE];
EVP_MD_CTX_init(&ctx);
if (mgf1Hash == NULL)
mgf1Hash = Hash;
hLen = EVP_MD_size(Hash);
if (hLen < 0)
goto err;
/*-
* Negative sLen has special meanings:
* -1 sLen == hLen
* -2 salt length is autorecovered from signature
* -N reserved
*/
if (sLen == -1)
sLen = hLen;
else if (sLen == -2)
sLen = -2;
else if (sLen < -2) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
emLen = RSA_size(rsa);
if (EM[0] & (0xFF << MSBits)) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_FIRST_OCTET_INVALID);
goto err;
}
if (MSBits == 0) {
EM++;
emLen--;
}
if (emLen < (hLen + sLen + 2)) { /* sLen can be small negative */
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_DATA_TOO_LARGE);
goto err;
}
if (EM[emLen - 1] != 0xbc) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_LAST_OCTET_INVALID);
goto err;
}
maskedDBLen = emLen - hLen - 1;
H = EM + maskedDBLen;
DB = OPENSSL_malloc(maskedDBLen);
if (!DB) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, ERR_R_MALLOC_FAILURE);
goto err;
}
if (PKCS1_MGF1(DB, maskedDBLen, H, hLen, mgf1Hash) < 0)
goto err;
for (i = 0; i < maskedDBLen; i++)
DB[i] ^= EM[i];
if (MSBits)
DB[0] &= 0xFF >> (8 - MSBits);
for (i = 0; DB[i] == 0 && i < (maskedDBLen - 1); i++) ;
if (DB[i++] != 0x1) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_RECOVERY_FAILED);
goto err;
}
if (sLen >= 0 && (maskedDBLen - i) != sLen) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
if (!EVP_DigestInit_ex(&ctx, Hash, NULL)
|| !EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes)
|| !EVP_DigestUpdate(&ctx, mHash, hLen))
goto err;
if (maskedDBLen - i) {
if (!EVP_DigestUpdate(&ctx, DB + i, maskedDBLen - i))
goto err;
}
if (!EVP_DigestFinal_ex(&ctx, H_, NULL))
goto err;
if (sgx_memcmp(H_, H, hLen)) {
RSAerr(RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1, RSA_R_BAD_SIGNATURE);
ret = 0;
} else
ret = 1;
err:
if (DB)
OPENSSL_free(DB);
EVP_MD_CTX_cleanup(&ctx);
return ret;
}
示例14: RSA_padding_add_PKCS1_PSS_mgf1
int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM,
const unsigned char *mHash,
const EVP_MD *Hash, const EVP_MD *mgf1Hash,
int sLen)
{
int i;
int ret = 0;
int hLen, maskedDBLen, MSBits, emLen;
unsigned char *H, *salt = NULL, *p;
EVP_MD_CTX ctx;
if (mgf1Hash == NULL)
mgf1Hash = Hash;
hLen = EVP_MD_size(Hash);
if (hLen < 0)
goto err;
/*-
* Negative sLen has special meanings:
* -1 sLen == hLen
* -2 salt length is maximized
* -N reserved
*/
if (sLen == -1)
sLen = hLen;
else if (sLen == -2)
sLen = -2;
else if (sLen < -2) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1, RSA_R_SLEN_CHECK_FAILED);
goto err;
}
MSBits = (BN_num_bits(rsa->n) - 1) & 0x7;
emLen = RSA_size(rsa);
if (MSBits == 0) {
*EM++ = 0;
emLen--;
}
if (sLen == -2) {
sLen = emLen - hLen - 2;
} else if (emLen < (hLen + sLen + 2)) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE);
goto err;
}
if (sLen > 0) {
salt = OPENSSL_malloc(sLen);
if (!salt) {
RSAerr(RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1,
ERR_R_MALLOC_FAILURE);
goto err;
}
if (RAND_bytes(salt, sLen) <= 0)
goto err;
}
maskedDBLen = emLen - hLen - 1;
H = EM + maskedDBLen;
EVP_MD_CTX_init(&ctx);
if (!EVP_DigestInit_ex(&ctx, Hash, NULL)
|| !EVP_DigestUpdate(&ctx, zeroes, sizeof zeroes)
|| !EVP_DigestUpdate(&ctx, mHash, hLen))
goto err;
if (sLen && !EVP_DigestUpdate(&ctx, salt, sLen))
goto err;
if (!EVP_DigestFinal_ex(&ctx, H, NULL))
goto err;
EVP_MD_CTX_cleanup(&ctx);
/* Generate dbMask in place then perform XOR on it */
if (PKCS1_MGF1(EM, maskedDBLen, H, hLen, mgf1Hash))
goto err;
p = EM;
/*
* Initial PS XORs with all zeroes which is a NOP so just update pointer.
* Note from a test above this value is guaranteed to be non-negative.
*/
p += emLen - sLen - hLen - 2;
*p++ ^= 0x1;
if (sLen > 0) {
for (i = 0; i < sLen; i++)
*p++ ^= salt[i];
}
if (MSBits)
EM[0] &= 0xFF >> (8 - MSBits);
/* H is already in place so just set final 0xbc */
EM[emLen - 1] = 0xbc;
ret = 1;
err:
if (salt)
OPENSSL_free(salt);
return ret;
}
示例15: fips_check_rsa
int fips_check_rsa(RSA *rsa)
{
int n, ret = 0;
unsigned char tctext[256], *ctext = tctext;
unsigned char tptext[256], *ptext = tptext;
/* The longest we can have with PKCS#1 v1.5 padding and a 512 bit key,
* namely 512/8-11-1 = 52 bytes */
static const unsigned char original_ptext[] =
"\x01\x23\x45\x67\x89\xab\xcd\xef\x01\x23\x45\x67\x89\xab\xcd\xef"
"\x01\x23\x45\x67\x89\xab\xcd\xef\x01\x23\x45\x67\x89\xab\xcd\xef"
"\x01\x23\x45\x67\x89\xab\xcd\xef\x01\x23\x45\x67\x89\xab\xcd\xef"
"\x01\x23\x45\x67";
if (RSA_size(rsa) > sizeof(tctext))
{
ctext = OPENSSL_malloc(RSA_size(rsa));
ptext = OPENSSL_malloc(RSA_size(rsa));
if (!ctext || !ptext)
{
ERR_print_errors_fp(OPENSSL_stderr());
exit(1);
}
}
/* this will fail for keys shorter than 512 bits */
n=RSA_private_encrypt(sizeof(original_ptext)-1,original_ptext,ctext,rsa,
RSA_PKCS1_PADDING);
if(n < 0)
{
ERR_print_errors_fp(OPENSSL_stderr());
exit(1);
}
if(!memcmp(ctext,original_ptext,n))
{
FIPSerr(FIPS_F_FIPS_CHECK_RSA,FIPS_R_PAIRWISE_TEST_FAILED);
goto error;
}
n=RSA_public_decrypt(n,ctext,ptext,rsa,RSA_PKCS1_PADDING);
if(n < 0)
{
ERR_print_errors_fp(OPENSSL_stderr());
exit(1);
}
if(n != sizeof(original_ptext)-1 || memcmp(ptext,original_ptext,n))
{
FIPSerr(FIPS_F_FIPS_CHECK_RSA,FIPS_R_PAIRWISE_TEST_FAILED);
goto error;
}
ret = 1;
error:
if (RSA_size(rsa) > sizeof(tctext))
{
OPENSSL_free(ctext);
OPENSSL_free(ptext);
}
return ret;
}