/* * See RFC 4034, Appendix B.1 : * * " For a DNSKEY RR with algorithm 1, the key tag is defined to be the most * significant 16 bits of the least significant 24 bits in the public * key modulus (in other words, the 4th to last and 3rd to last octets * of the public key modulus)." */ u_int16_t rsamd5_keytag(const u_char *pubkey, size_t pubkey_len) { RSA *rsa = NULL; BIGNUM *modulus; u_int16_t keytag = 0x0000; u_char *modulus_bin; int modulus_len; if ((rsa = RSA_new()) == NULL) { return VAL_OUT_OF_MEMORY; }; if (rsamd5_parse_public_key(pubkey, pubkey_len, rsa) != VAL_NO_ERROR) { RSA_free(rsa); return VAL_BAD_ARGUMENT; } RSA_get0_key(rsa, (const BIGNUM **) &modulus, NULL, NULL); modulus_len = BN_num_bytes(modulus); modulus_bin = (u_char *) MALLOC(modulus_len * sizeof(u_char)); BN_bn2bin(modulus, modulus_bin); keytag = ((0x00ff & modulus_bin[modulus_len - 3]) << 8) | (0x00ff & modulus_bin[modulus_len - 2]); FREE(modulus_bin); RSA_free(rsa); return keytag; }
/* returns error */ int rdssl_rkey_get_exp_mod(RDSSL_RKEY * rkey, uint8 * exponent, uint32 max_exp_len, uint8 * modulus, uint32 max_mod_len) { int len; #if OPENSSL_VERSION_NUMBER >= 0x10100000 && !defined(LIBRESSL_VERSION_NUMBER) const BIGNUM *e, *n; RSA_get0_key(rkey, &n, &e, NULL); if ((BN_num_bytes(e) > (int) max_exp_len) || (BN_num_bytes(n) > (int) max_mod_len)) { return 1; } len = BN_bn2bin(e, exponent); reverse(exponent, len); len = BN_bn2bin(n, modulus); reverse(modulus, len); #else if ((BN_num_bytes(rkey->e) > (int) max_exp_len) || (BN_num_bytes(rkey->n) > (int) max_mod_len)) { return 1; } len = BN_bn2bin(rkey->e, exponent); reverse(exponent, len); len = BN_bn2bin(rkey->n, modulus); reverse(modulus, len); #endif return 0; }
static LUA_FUNCTION(openssl_rsa_parse) { const BIGNUM *n = NULL, *e = NULL, *d = NULL; const BIGNUM *p = NULL, *q = NULL; const BIGNUM *dmp1 = NULL, *dmq1 = NULL, *iqmp = NULL; RSA* rsa = CHECK_OBJECT(1, RSA, "openssl.rsa"); RSA_get0_key(rsa, &n, &e, &d); RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); lua_newtable(L); lua_pushinteger(L, RSA_size(rsa)); lua_setfield(L, -2, "size"); lua_pushinteger(L, RSA_bits(rsa)); lua_setfield(L, -2, "bits"); OPENSSL_PKEY_GET_BN(n, n); OPENSSL_PKEY_GET_BN(e, e); OPENSSL_PKEY_GET_BN(d, d); OPENSSL_PKEY_GET_BN(p, p); OPENSSL_PKEY_GET_BN(q, q); OPENSSL_PKEY_GET_BN(dmp1, dmp1); OPENSSL_PKEY_GET_BN(dmq1, dmq1); OPENSSL_PKEY_GET_BN(iqmp, iqmp); return 1; }
/* Creates a term which can be parsed by get_rsa_private_key(). This is a list of plain integer binaries (not mpints). */ static ERL_NIF_TERM put_rsa_private_key(ErlNifEnv* env, const RSA *rsa) { ERL_NIF_TERM result[8]; const BIGNUM *n, *e, *d, *p, *q, *dmp1, *dmq1, *iqmp; /* Return at least [E,N,D] */ n = NULL; e = NULL; d = NULL; RSA_get0_key(rsa, &n, &e, &d); result[0] = bin_from_bn(env, e); // Exponent E result[1] = bin_from_bn(env, n); // Modulus N = p*q result[2] = bin_from_bn(env, d); // Exponent D /* Check whether the optional additional parameters are available */ p = NULL; q = NULL; RSA_get0_factors(rsa, &p, &q); dmp1 = NULL; dmq1 = NULL; iqmp = NULL; RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); if (p && q && dmp1 && dmq1 && iqmp) { result[3] = bin_from_bn(env, p); // Factor p result[4] = bin_from_bn(env, q); // Factor q result[5] = bin_from_bn(env, dmp1); // D mod (p-1) result[6] = bin_from_bn(env, dmq1); // D mod (q-1) result[7] = bin_from_bn(env, iqmp); // (1/q) mod p return enif_make_list_from_array(env, result, 8); } else { return enif_make_list_from_array(env, result, 3); } }
static int test_fips1864_keygen_kat(void) { int ret = 0; RSA *key = NULL; BN_CTX *ctx = NULL; BIGNUM *e, *Xp, *Xp1, *Xp2, *Xq, *Xq1, *Xq2; BIGNUM *p1, *p2, *q1, *q2; BIGNUM *p1_exp, *p2_exp, *q1_exp, *q2_exp; BIGNUM *p_exp, *q_exp, *n_exp, *d_exp; const BIGNUM *p, *q, *n, *d, *e2; if (!(TEST_ptr(key = RSA_new()) && TEST_ptr(ctx = BN_CTX_new()))) goto err; BN_CTX_start(ctx); e = bn_load(ctx, cav_e, sizeof(cav_e)); Xp = bn_load(ctx, cav_Xp, sizeof(cav_Xp)); Xp1 = bn_load(ctx, cav_Xp1, sizeof(cav_Xp1)); Xp2 = bn_load(ctx, cav_Xp2, sizeof(cav_Xp2)); Xq = bn_load(ctx, cav_Xq, sizeof(cav_Xq)); Xq1 = bn_load(ctx, cav_Xq1, sizeof(cav_Xq1)); Xq2 = bn_load(ctx, cav_Xq2, sizeof(cav_Xq2)); p1_exp = bn_load(ctx, cav_p1, sizeof(cav_p1)); p2_exp = bn_load(ctx, cav_p2, sizeof(cav_p2)); q1_exp = bn_load(ctx, cav_q1, sizeof(cav_q1)); q2_exp = bn_load(ctx, cav_q2, sizeof(cav_q2)); p_exp = bn_load(ctx, cav_p, sizeof(cav_p)); q_exp = bn_load(ctx, cav_q, sizeof(cav_q)); n_exp = bn_load(ctx, cav_n, sizeof(cav_n)); d_exp = bn_load(ctx, cav_d, sizeof(cav_d)); p1 = BN_CTX_get(ctx); p2 = BN_CTX_get(ctx); q1 = BN_CTX_get(ctx); q2 = BN_CTX_get(ctx); ret = TEST_ptr(q2) && TEST_true(rsa_fips186_4_gen_prob_primes(key, p1, p2, NULL, Xp, Xp1, Xp2, q1, q2, NULL, Xq, Xq1, Xq2, 2048, e, ctx, NULL)) && TEST_true(rsa_sp800_56b_derive_params_from_pq(key, 2048, e, ctx)) && TEST_BN_eq(p1_exp, p1) && TEST_BN_eq(p2_exp, p2) && TEST_BN_eq(q1_exp, q1) && TEST_BN_eq(q2_exp, q2); if (!ret) goto err; RSA_get0_key(key, &n, &e2, &d); RSA_get0_factors(key, &p, &q); ret = TEST_BN_eq(e, e2) && TEST_BN_eq(p_exp, p) && TEST_BN_eq(q_exp, q) && TEST_BN_eq(n_exp, n) && TEST_BN_eq(d_exp, d); err: RSA_free(key); BN_CTX_end(ctx); BN_CTX_free(ctx); return ret; }
void _cjose_jwk_rsa_get(RSA *rsa, BIGNUM **rsa_n, BIGNUM **rsa_e, BIGNUM **rsa_d) { if (rsa == NULL) return; #if (CJOSE_OPENSSL_11X) RSA_get0_key(rsa, (const BIGNUM **)rsa_n, (const BIGNUM **)rsa_e, (const BIGNUM **)rsa_d); #else *rsa_n=rsa->n; *rsa_e=rsa->e; *rsa_d=rsa->d; #endif }
RSAKeyImpl::ByteVec RSAKeyImpl::decryptionExponent() const { #if OPENSSL_VERSION_NUMBER >= 0x10100000L const BIGNUM* n = 0; const BIGNUM* e = 0; const BIGNUM* d = 0; RSA_get0_key(_pRSA, &n, &e, &d); return convertToByteVec(d); #else return convertToByteVec(_pRSA->d); #endif }
RSAKeyImpl::ByteVec RSAKeyImpl::modulus() const { #if OPENSSL_VERSION_NUMBER >= 0x10100000L const BIGNUM* n = 0; const BIGNUM* e = 0; const BIGNUM* d = 0; RSA_get0_key(_pRSA, &n, &e, &d); return convertToByteVec(n); #else return convertToByteVec(_pRSA->n); #endif }
void computeFingerprint() { Expects(isValid()); const BIGNUM *n, *e; mtpBuffer string; RSA_get0_key(_rsa, &n, &e, nullptr); MTP_bytes(toBytes(n)).write(string); MTP_bytes(toBytes(e)).write(string); uchar sha1Buffer[20]; _fingerprint = *(uint64*)(hashSha1(&string[0], string.size() * sizeof(mtpPrime), sha1Buffer) + 3); }
int ssh_rsa_complete_crt_parameters(struct sshkey *key, const BIGNUM *iqmp) { const BIGNUM *rsa_p, *rsa_q, *rsa_d; BIGNUM *aux = NULL, *d_consttime = NULL; BIGNUM *rsa_dmq1 = NULL, *rsa_dmp1 = NULL, *rsa_iqmp = NULL; BN_CTX *ctx = NULL; int r; if (key == NULL || key->rsa == NULL || sshkey_type_plain(key->type) != KEY_RSA) return SSH_ERR_INVALID_ARGUMENT; RSA_get0_key(key->rsa, NULL, NULL, &rsa_d); RSA_get0_factors(key->rsa, &rsa_p, &rsa_q); if ((ctx = BN_CTX_new()) == NULL) return SSH_ERR_ALLOC_FAIL; if ((aux = BN_new()) == NULL || (rsa_dmq1 = BN_new()) == NULL || (rsa_dmp1 = BN_new()) == NULL) return SSH_ERR_ALLOC_FAIL; if ((d_consttime = BN_dup(rsa_d)) == NULL || (rsa_iqmp = BN_dup(iqmp)) == NULL) { r = SSH_ERR_ALLOC_FAIL; goto out; } BN_set_flags(aux, BN_FLG_CONSTTIME); BN_set_flags(d_consttime, BN_FLG_CONSTTIME); if ((BN_sub(aux, rsa_q, BN_value_one()) == 0) || (BN_mod(rsa_dmq1, d_consttime, aux, ctx) == 0) || (BN_sub(aux, rsa_p, BN_value_one()) == 0) || (BN_mod(rsa_dmp1, d_consttime, aux, ctx) == 0)) { r = SSH_ERR_LIBCRYPTO_ERROR; goto out; } if (!RSA_set0_crt_params(key->rsa, rsa_dmp1, rsa_dmq1, rsa_iqmp)) { r = SSH_ERR_LIBCRYPTO_ERROR; goto out; } rsa_dmp1 = rsa_dmq1 = rsa_iqmp = NULL; /* transferred */ /* success */ r = 0; out: BN_clear_free(aux); BN_clear_free(d_consttime); BN_clear_free(rsa_dmp1); BN_clear_free(rsa_dmq1); BN_clear_free(rsa_iqmp); BN_CTX_free(ctx); return r; }
static int check_bitlen_rsa(RSA *rsa, int ispub, unsigned int *pmagic) { int nbyte, hnbyte, bitlen; BIGNUM *e; RSA_get0_key(rsa, &e, NULL, NULL); if (BN_num_bits(e) > 32) goto badkey; bitlen = RSA_bits(rsa); nbyte = RSA_size(rsa); hnbyte = (bitlen + 15) >> 4; if (ispub) { *pmagic = MS_RSA1MAGIC; return bitlen; } else { BIGNUM *d, *p, *q, *iqmp, *dmp1, *dmq1; *pmagic = MS_RSA2MAGIC; /* * For private key each component must fit within nbyte or hnbyte. */ RSA_get0_key(rsa, NULL, NULL, &d); if (BN_num_bytes(d) > nbyte) goto badkey; RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); if ((BN_num_bytes(iqmp) > hnbyte) || (BN_num_bytes(p) > hnbyte) || (BN_num_bytes(q) > hnbyte) || (BN_num_bytes(dmp1) > hnbyte) || (BN_num_bytes(dmq1) > hnbyte)) goto badkey; } return bitlen; badkey: PEMerr(PEM_F_CHECK_BITLEN_RSA, PEM_R_UNSUPPORTED_KEY_COMPONENTS); return 0; }
static int s2n_rsa_modulus_check(RSA *rsa) { /* RSA was made opaque starting in Openssl 1.1.0 */ #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined LIBRESSL_VERSION_NUMBER notnull_check(rsa->n); #else const BIGNUM *n = NULL; /* RSA still owns the memory for n */ RSA_get0_key(rsa, &n, NULL, NULL); notnull_check(n); #endif return 0; }
static isc_result_t rsa_check(RSA *rsa, RSA *pub) { const BIGNUM *n1 = NULL, *n2 = NULL; const BIGNUM *e1 = NULL, *e2 = NULL; BIGNUM *n = NULL, *e = NULL; /* * Public parameters should be the same but if they are not set * copy them from the public key. */ RSA_get0_key(rsa, &n1, &e1, NULL); if (pub != NULL) { RSA_get0_key(pub, &n2, &e2, NULL); if (n1 != NULL) { if (BN_cmp(n1, n2) != 0) return (DST_R_INVALIDPRIVATEKEY); } else { n = BN_dup(n2); } if (e1 != NULL) { if (BN_cmp(e1, e2) != 0) return (DST_R_INVALIDPRIVATEKEY); } else { e = BN_dup(e2); } if (RSA_set0_key(rsa, n, e, NULL) == 0) { if (n != NULL) BN_free(n); if (e != NULL) BN_free(e); } } RSA_get0_key(rsa, &n1, &e1, NULL); if (n1 == NULL || e1 == NULL) return (DST_R_INVALIDPRIVATEKEY); return (ISC_R_SUCCESS); }
/* TODO: remove this function in libp11 0.5.0 */ int pkcs11_get_key_exponent(PKCS11_KEY *key, BIGNUM **bn) { RSA *rsa = pkcs11_rsa(key); const BIGNUM *rsa_e; if (rsa == NULL) return 0; #if OPENSSL_VERSION_NUMBER >= 0x10100005L RSA_get0_key(rsa, NULL, &rsa_e, NULL); #else rsa_e=rsa->e; #endif *bn = BN_dup(rsa_e); return *bn == NULL ? 0 : 1; }
/* TODO: remove this function in libp11 0.5.0 */ int pkcs11_get_key_modulus(PKCS11_KEY *key, BIGNUM **bn) { RSA *rsa = pkcs11_rsa(key); const BIGNUM *rsa_n; if (rsa == NULL) return 0; #if OPENSSL_VERSION_NUMBER >= 0x10100005L RSA_get0_key(rsa, &rsa_n, NULL, NULL); #else rsa_n=rsa->n; #endif *bn = BN_dup(rsa_n); return *bn == NULL ? 0 : 1; }
static isc_boolean_t opensslrsa_isprivate(const dst_key_t *key) { const BIGNUM *d = NULL; #if USE_EVP RSA *rsa = EVP_PKEY_get1_RSA(key->keydata.pkey); INSIST(rsa != NULL); RSA_free(rsa); /* key->keydata.pkey still has a reference so rsa is still valid. */ #else RSA *rsa = key->keydata.rsa; #endif if (rsa != NULL && RSA_test_flags(rsa, RSA_FLAG_EXT_PKEY) != 0) return (ISC_TRUE); RSA_get0_key(rsa, NULL, NULL, &d); return (ISC_TF(rsa != NULL && d != NULL)); }
int RSA_get_RSAPUBLICKEYBLOB(RSA *rsa, RSAPUBLICKEYBLOB *blob) { const BIGNUM *n; const BIGNUM *e; if (!rsa || !blob) { GMAPIerr(GMAPI_F_RSA_GET_RSAPUBLICKEYBLOB, ERR_R_PASSED_NULL_PARAMETER); return 0; } RSA_get0_key(rsa, &n, &e, NULL); if (!n || !e) { GMAPIerr(GMAPI_F_RSA_GET_RSAPUBLICKEYBLOB, GMAPI_R_INVALID_RSA_PUBLIC_KEY); return 0; } if (RSA_bits(rsa) > sizeof(blob->Modulus) * 8 || RSA_bits(rsa) % 8 != 0) { GMAPIerr(GMAPI_F_RSA_GET_RSAPUBLICKEYBLOB, GMAPI_R_INVALID_RSA_PUBLIC_KEY); return 0; } memset(blob, 0, sizeof(RSAPUBLICKEYBLOB)); blob->AlgID = SGD_RSA; blob->BitLen = RSA_bits(rsa); if (BN_bn2bin(n, blob->Modulus + sizeof(blob->Modulus) - BN_num_bytes(n)) <= 0) { GMAPIerr(GMAPI_F_RSA_GET_RSAPUBLICKEYBLOB, GMAPI_R_ENCODE_RSA_PUBLIC_KEY_FAILED); return 0; } if (BN_bn2bin(e, blob->PublicExponent + sizeof(blob->PublicExponent) - BN_num_bytes(e)) <= 0) { GMAPIerr(GMAPI_F_RSA_GET_RSAPUBLICKEYBLOB, GMAPI_R_ENCODE_RSA_PUBLIC_KEY_FAILED); return 0; } return 1; }
Result<RSA> RSA::from_pem(Slice pem) { init_crypto(); auto *bio = BIO_new_mem_buf(const_cast<void *>(static_cast<const void *>(pem.ubegin())), narrow_cast<int32>(pem.size())); if (bio == nullptr) { return Status::Error("Cannot create BIO"); } SCOPE_EXIT { BIO_free(bio); }; auto *rsa = RSA_new(); if (rsa == nullptr) { return Status::Error("Cannot create RSA"); } SCOPE_EXIT { RSA_free(rsa); }; if (!PEM_read_bio_RSAPublicKey(bio, &rsa, nullptr, nullptr)) { return Status::Error("Error while reading rsa pubkey"); } if (RSA_size(rsa) != 256) { return Status::Error("RSA_size != 256"); } const BIGNUM *n_num; const BIGNUM *e_num; #if OPENSSL_VERSION_NUMBER < 0x10100000L n_num = rsa->n; e_num = rsa->e; #else RSA_get0_key(rsa, &n_num, &e_num, nullptr); #endif auto n = static_cast<void *>(BN_dup(n_num)); auto e = static_cast<void *>(BN_dup(e_num)); if (n == nullptr || e == nullptr) { return Status::Error("Cannot dup BIGNUM"); } return RSA(BigNum::from_raw(n), BigNum::from_raw(e)); }
static unsigned char * gen_publickey_from_rsa(LIBSSH2_SESSION *session, RSA *rsa, size_t *key_len) { int e_bytes, n_bytes; unsigned long len; unsigned char *key; unsigned char *p; const BIGNUM * e; const BIGNUM * n; #ifdef HAVE_OPAQUE_STRUCTS RSA_get0_key(rsa, &n, &e, NULL); #else e = rsa->e; n = rsa->n; #endif e_bytes = BN_num_bytes(e) + 1; n_bytes = BN_num_bytes(n) + 1; /* Key form is "ssh-rsa" + e + n. */ len = 4 + 7 + 4 + e_bytes + 4 + n_bytes; key = LIBSSH2_ALLOC(session, len); if(key == NULL) { return NULL; } /* Process key encoding. */ p = key; _libssh2_htonu32(p, 7); /* Key type. */ p += 4; memcpy(p, "ssh-rsa", 7); p += 7; p = write_bn(p, e, e_bytes); p = write_bn(p, n, n_bytes); *key_len = (size_t)(p - key); return key; }
static void write_rsa(unsigned char **out, RSA *rsa, int ispub) { int nbyte, hnbyte; BIGNUM *n, *d, *e, *p, *q, *iqmp, *dmp1, *dmq1; nbyte = RSA_size(rsa); hnbyte = (RSA_bits(rsa) + 15) >> 4; RSA_get0_key(rsa, &e, &n, &d); write_lebn(out, e, 4); write_lebn(out, n, -1); if (ispub) return; RSA_get0_factors(rsa, &p, &q); RSA_get0_crt_params(rsa, &dmp1, &dmq1, &iqmp); write_lebn(out, p, hnbyte); write_lebn(out, q, hnbyte); write_lebn(out, dmp1, hnbyte); write_lebn(out, dmq1, hnbyte); write_lebn(out, iqmp, hnbyte); write_lebn(out, d, nbyte); }
int check(RSA* key) { const BIGNUM *n, *e; int public_exponent, modulus; RSA_get0_key(key, &n, &e, NULL); public_exponent = BN_get_word(e); modulus = BN_num_bits(n); if (public_exponent != 3 && public_exponent != 65537) { fprintf(stderr, "WARNING: Public exponent should be 3 or 65537 (but is %d).\n", public_exponent); } if (modulus != 1024 && modulus != 2048 && modulus != 3072 && modulus != 4096 && modulus != 8192) { fprintf(stderr, "ERROR: Unknown modulus length = %d.\n", modulus); return 0; } return 1; }
rdpRsaKey* key_new_from_content(const char* keycontent, const char* keyfile) { BIO* bio = NULL; RSA* rsa = NULL; rdpRsaKey* key = NULL; const BIGNUM* rsa_e = NULL; const BIGNUM* rsa_n = NULL; const BIGNUM* rsa_d = NULL; key = (rdpRsaKey*) calloc(1, sizeof(rdpRsaKey)); if (!key) return NULL; bio = BIO_new_mem_buf((void*)keycontent, strlen(keycontent)); if (!bio) goto out_free; rsa = PEM_read_bio_RSAPrivateKey(bio, NULL, NULL, NULL); BIO_free(bio); if (!rsa) { WLog_ERR(TAG, "unable to load RSA key from %s: %s.", keyfile, strerror(errno)); goto out_free; } switch (RSA_check_key(rsa)) { case 0: WLog_ERR(TAG, "invalid RSA key in %s", keyfile); goto out_free_rsa; case 1: /* Valid key. */ break; default: WLog_ERR(TAG, "unexpected error when checking RSA key from %s: %s.", keyfile, strerror(errno)); goto out_free_rsa; } RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); if (BN_num_bytes(rsa_e) > 4) { WLog_ERR(TAG, "RSA public exponent too large in %s", keyfile); goto out_free_rsa; } key->ModulusLength = BN_num_bytes(rsa_n); key->Modulus = (BYTE*) malloc(key->ModulusLength); if (!key->Modulus) goto out_free_rsa; BN_bn2bin(rsa_n, key->Modulus); crypto_reverse(key->Modulus, key->ModulusLength); key->PrivateExponentLength = BN_num_bytes(rsa_d); key->PrivateExponent = (BYTE*) malloc(key->PrivateExponentLength); if (!key->PrivateExponent) goto out_free_modulus; BN_bn2bin(rsa_d, key->PrivateExponent); crypto_reverse(key->PrivateExponent, key->PrivateExponentLength); memset(key->exponent, 0, sizeof(key->exponent)); BN_bn2bin(rsa_e, key->exponent + sizeof(key->exponent) - BN_num_bytes(rsa_e)); crypto_reverse(key->exponent, sizeof(key->exponent)); RSA_free(rsa); return key; out_free_modulus: free(key->Modulus); out_free_rsa: RSA_free(rsa); out_free: free(key); return NULL; }
/* * Store private key */ static int pkcs11_store_key(PKCS11_TOKEN *token, EVP_PKEY *pk, unsigned int type, char *label, unsigned char *id, size_t id_len, PKCS11_KEY ** ret_key) { PKCS11_SLOT *slot = TOKEN2SLOT(token); PKCS11_CTX *ctx = TOKEN2CTX(token); PKCS11_SLOT_private *spriv = PRIVSLOT(slot); CK_OBJECT_HANDLE object; CK_ATTRIBUTE attrs[32]; unsigned int n = 0; int rv; const BIGNUM *rsa_n, *rsa_e, *rsa_d, *rsa_p, *rsa_q; /* First, make sure we have a session */ if (!spriv->haveSession && PKCS11_open_session(slot, 1)) return -1; /* Now build the key attrs */ pkcs11_addattr_int(attrs + n++, CKA_CLASS, type); if (label) pkcs11_addattr_s(attrs + n++, CKA_LABEL, label); if (id && id_len) pkcs11_addattr(attrs + n++, CKA_ID, id, id_len); pkcs11_addattr_bool(attrs + n++, CKA_TOKEN, TRUE); if (type == CKO_PRIVATE_KEY) { pkcs11_addattr_bool(attrs + n++, CKA_PRIVATE, TRUE); pkcs11_addattr_bool(attrs + n++, CKA_SENSITIVE, TRUE); pkcs11_addattr_bool(attrs + n++, CKA_DECRYPT, TRUE); pkcs11_addattr_bool(attrs + n++, CKA_SIGN, TRUE); pkcs11_addattr_bool(attrs + n++, CKA_UNWRAP, TRUE); } else { /* CKO_PUBLIC_KEY */ pkcs11_addattr_bool(attrs + n++, CKA_ENCRYPT, TRUE); pkcs11_addattr_bool(attrs + n++, CKA_VERIFY, TRUE); pkcs11_addattr_bool(attrs + n++, CKA_WRAP, TRUE); } #if OPENSSL_VERSION_NUMBER >= 0x10100003L if (EVP_PKEY_base_id(pk) == EVP_PKEY_RSA) { RSA *rsa = EVP_PKEY_get1_RSA(pk); #else if (pk->type == EVP_PKEY_RSA) { RSA *rsa = pk->pkey.rsa; #endif pkcs11_addattr_int(attrs + n++, CKA_KEY_TYPE, CKK_RSA); #if OPENSSL_VERSION_NUMBER >= 0x10100005L RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); RSA_get0_factors(rsa, &rsa_p, &rsa_q); #else rsa_n=rsa->n; rsa_e=rsa->e; rsa_d=rsa->d; rsa_p=rsa->p; rsa_q=rsa->q; #endif pkcs11_addattr_bn(attrs + n++, CKA_MODULUS, rsa_n); pkcs11_addattr_bn(attrs + n++, CKA_PUBLIC_EXPONENT, rsa_e); if (type == CKO_PRIVATE_KEY) { pkcs11_addattr_bn(attrs + n++, CKA_PRIVATE_EXPONENT, rsa_d); pkcs11_addattr_bn(attrs + n++, CKA_PRIME_1, rsa_p); pkcs11_addattr_bn(attrs + n++, CKA_PRIME_2, rsa_q); } } else { pkcs11_zap_attrs(attrs, n); PKCS11err(type == CKO_PRIVATE_KEY ? PKCS11_F_PKCS11_STORE_PRIVATE_KEY : PKCS11_F_PKCS11_STORE_PUBLIC_KEY, PKCS11_NOT_SUPPORTED); return -1; } /* Now call the pkcs11 module to create the object */ rv = CRYPTOKI_call(ctx, C_CreateObject(spriv->session, attrs, n, &object)); /* Zap all memory allocated when building the template */ pkcs11_zap_attrs(attrs, n); CRYPTOKI_checkerr(PKCS11_F_PKCS11_STORE_PRIVATE_KEY, rv); /* Gobble the key object */ return pkcs11_init_key(ctx, token, spriv->session, object, type, ret_key); } /* * Get the key type */ int pkcs11_get_key_type(PKCS11_KEY *key) { PKCS11_KEY_private *kpriv = PRIVKEY(key); return kpriv->ops->type; }
base::byte_vector getE() const { Expects(isValid()); const BIGNUM *e; RSA_get0_key(_rsa, nullptr, &e, nullptr); return toBytes(e); }
base::byte_vector getN() const { Expects(isValid()); const BIGNUM *n; RSA_get0_key(_rsa, &n, nullptr, nullptr); return toBytes(n); }
static int build_encrypt_op(int flen, const unsigned char *from, unsigned char *to, RSA *rsa, int padding, CpaCyRsaEncryptOpData ** enc_op_data, CpaFlatBuffer ** output_buffer, int alloc_pad) { CpaCyRsaPublicKey *cpa_pub_key = NULL; int rsa_len = 0; const BIGNUM *n = NULL; const BIGNUM *e = NULL; const BIGNUM *d = NULL; DEBUG("- Started\n"); RSA_get0_key((const RSA*)rsa, &n, &e, &d); /* Note: not checking 'd' as it is not used */ if (n == NULL || e == NULL) { WARN("RSA key values n = %p or e = %p are NULL\n", n, e); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_N_E_NULL); return 0; } if (padding != RSA_PKCS1_PADDING) { WARN("Unknown Padding %d\n", padding); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_UNKNOWN_PADDING); return 0; } cpa_pub_key = OPENSSL_zalloc(sizeof(CpaCyRsaPublicKey)); if (NULL == cpa_pub_key) { WARN("Public Key zalloc failed\n"); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_PUB_KEY_MALLOC_FAILURE); return 0; } rsa_len = RSA_size(rsa); /* Output and input data MUST allocate memory for RSA verify process */ /* Memory allocation for EncOpData[IN] */ *enc_op_data = OPENSSL_zalloc(sizeof(CpaCyRsaEncryptOpData)); if (NULL == *enc_op_data) { WARN("Failed to allocate enc_op_data\n"); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_ENC_OP_DATA_MALLOC_FAILURE); OPENSSL_free(cpa_pub_key); return 0; } /* Setup the Encrypt operation Data structure */ (*enc_op_data)->pPublicKey = cpa_pub_key; DEBUG("flen=%d padding=%d\n", flen, padding); /* Passing Public key from big number format to big endian order binary */ if (qat_BN_to_FB(&cpa_pub_key->modulusN, n) != 1 || qat_BN_to_FB(&cpa_pub_key->publicExponentE, e) != 1) { WARN("Failed to convert cpa_pub_key elements to flatbuffer\n"); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_N_E_CONVERT_TO_FB_FAILURE); return 0; } if (alloc_pad) { (*enc_op_data)->inputData.pData = qat_alloc_pad((Cpa8U *) from, flen, rsa_len, 0); } else { (*enc_op_data)->inputData.pData = (Cpa8U *) copyAllocPinnedMemory((void *)from, flen, __FILE__, __LINE__); } if (NULL == (*enc_op_data)->inputData.pData) { WARN("Failed to allocate (*enc_op_data)->inputData.pData\n"); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_INPUT_DATA_MALLOC_FAILURE); return 0; } if (alloc_pad) (*enc_op_data)->inputData.dataLenInBytes = rsa_len; else (*enc_op_data)->inputData.dataLenInBytes = flen; /* * Memory allocation for outputBuffer[OUT] OutputBuffer size initialize * as the size of rsa size */ (*output_buffer) = (CpaFlatBuffer *) OPENSSL_malloc(sizeof(CpaFlatBuffer)); if (NULL == (*output_buffer)) { WARN("Failed to allocate output_buffer\n"); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_OUTPUT_BUF_MALLOC_FAILURE); return 0; } /* * outputBuffer size should large enough to hold the Hash value but * smaller than (RSA_size(rsa)-11) */ (*output_buffer)->dataLenInBytes = rsa_len; (*output_buffer)->pData = qaeCryptoMemAlloc(rsa_len, __FILE__, __LINE__); if (NULL == (*output_buffer)->pData) { WARN("Failed to allocate (*output_buffer)->pData\n"); QATerr(QAT_F_BUILD_ENCRYPT_OP, QAT_R_OUTPUT_BUF_PDATA_MALLOC_FAILURE); return 0;; } DEBUG("- Finished\n"); return 1; }
/* * convert the RSA public key in the X.509 certificate in the BIO pointed to * by "input" to a JSON Web Key object */ static apr_byte_t oidc_jwk_rsa_bio_to_jwk(apr_pool_t *pool, BIO *input, cjose_jwk_t **jwk, int is_private_key, oidc_jose_error_t *err) { X509 *x509 = NULL; EVP_PKEY *pkey = NULL; apr_byte_t rv = FALSE; cjose_jwk_rsa_keyspec key_spec; memset(&key_spec, 0, sizeof(cjose_jwk_rsa_keyspec)); if (is_private_key) { /* get the private key struct from the BIO */ if ((pkey = PEM_read_bio_PrivateKey(input, NULL, NULL, NULL)) == NULL) { oidc_jose_error_openssl(err, "PEM_read_bio_PrivateKey"); goto end; } } else { /* read the X.509 struct */ if ((x509 = PEM_read_bio_X509_AUX(input, NULL, NULL, NULL)) == NULL) { oidc_jose_error_openssl(err, "PEM_read_bio_X509_AUX"); goto end; } /* get the public key struct from the X.509 struct */ if ((pkey = X509_get_pubkey(x509)) == NULL) { oidc_jose_error_openssl(err, "X509_get_pubkey"); goto end; } } /* get the RSA key from the public key struct */ RSA *rsa = EVP_PKEY_get1_RSA(pkey); if (rsa == NULL) { oidc_jose_error_openssl(err, "EVP_PKEY_get1_RSA"); goto end; } const BIGNUM *rsa_n, *rsa_e, *rsa_d; #if OPENSSL_VERSION_NUMBER >= 0x10100005L && !defined (LIBRESSL_VERSION_NUMBER) RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); #else rsa_n = rsa->n; rsa_e = rsa->e; rsa_d = rsa->d; #endif RSA_free(rsa); /* convert the modulus bignum in to a key/len */ key_spec.nlen = BN_num_bytes(rsa_n); key_spec.n = apr_pcalloc(pool, key_spec.nlen); BN_bn2bin(rsa_n, key_spec.n); /* convert the exponent bignum in to a key/len */ key_spec.elen = BN_num_bytes(rsa_e); key_spec.e = apr_pcalloc(pool, key_spec.elen); BN_bn2bin(rsa_e, key_spec.e); /* convert the private exponent bignum in to a key/len */ if (rsa_d != NULL) { key_spec.dlen = BN_num_bytes(rsa_d); key_spec.d = apr_pcalloc(pool, key_spec.dlen); BN_bn2bin(rsa_d, key_spec.d); } cjose_err cjose_err; *jwk = cjose_jwk_create_RSA_spec(&key_spec, &cjose_err); if (*jwk == NULL) { oidc_jose_error(err, "cjose_jwk_create_RSA_spec failed: %s", oidc_cjose_e2s(pool, cjose_err)); goto end; } char *fingerprint = apr_pcalloc(pool, key_spec.nlen + key_spec.elen); memcpy(fingerprint, key_spec.n, key_spec.nlen); memcpy(fingerprint + key_spec.nlen, key_spec.e, key_spec.elen); if (oidc_jwk_set_or_generate_kid(pool, *jwk, NULL, fingerprint, key_spec.nlen + key_spec.elen, err) == FALSE) { goto end; } rv = TRUE; end: if (pkey) EVP_PKEY_free(pkey); if (x509) X509_free(x509); return rv; }
int main(int c, char **v) { crypto_pk_t *env; char *str; RSA *rsa; int wantdigest=0; int fname_idx; char *fname=NULL; init_logging(1); if (c < 2) { fprintf(stderr, "Hi. I'm tor-checkkey. Tell me a filename that " "has a PEM-encoded RSA public key (like in a cert) and I'll " "dump the modulus. Use the --digest option too and I'll " "dump the digest.\n"); return 1; } if (crypto_global_init(0, NULL, NULL)) { fprintf(stderr, "Couldn't initialize crypto library.\n"); return 1; } if (!strcmp(v[1], "--digest")) { wantdigest = 1; fname_idx = 2; if (c<3) { fprintf(stderr, "too few arguments"); return 1; } } else { wantdigest = 0; fname_idx = 1; } fname = expand_filename(v[fname_idx]); str = read_file_to_str(fname, 0, NULL); tor_free(fname); if (!str) { fprintf(stderr, "Couldn't read %s\n", v[fname_idx]); return 1; } env = crypto_pk_new(); if (crypto_pk_read_public_key_from_string(env, str, strlen(str))<0) { fprintf(stderr, "Couldn't parse key.\n"); return 1; } tor_free(str); if (wantdigest) { char digest[HEX_DIGEST_LEN+1]; if (crypto_pk_get_fingerprint(env, digest, 0)<0) return 1; printf("%s\n",digest); } else { rsa = crypto_pk_get_rsa_(env); const BIGNUM *rsa_n; #ifdef OPENSSL_1_1_API const BIGNUM *rsa_e, *rsa_d; RSA_get0_key(rsa, &rsa_n, &rsa_e, &rsa_d); #else rsa_n = rsa->n; #endif str = BN_bn2hex(rsa_n); printf("%s\n", str); } return 0; }
static void CheckPublicKey(X509 *x509, struct tm tm_after) { EVP_PKEY *pkey = X509_get_pubkey(x509); if (pkey == NULL) { SetError(ERR_UNKNOWN_PUBLIC_KEY_TYPE); } else if (EVP_PKEY_base_id(pkey) == EVP_PKEY_RSA) { RSA *rsa = EVP_PKEY_get1_RSA(pkey); if (rsa == NULL) { SetError(ERR_INVALID); RSA_free(rsa); return; } const BIGNUM *n, *e; RSA_get0_key(rsa, &n, &e, NULL); if (n == NULL || e == NULL) { SetError(ERR_INVALID); RSA_free(rsa); return; } if (!GetBit(errors, ERR_INVALID_TIME_FORMAT)) { if (tm_after.tm_year >= 114 && BN_num_bits(n) < 2048) { SetError(ERR_RSA_SIZE_2048); } } if (BN_is_odd(e) == 0) { SetError(ERR_RSA_EXP_NOT_ODD); } BIGNUM *i = BN_new(); BN_set_word(i, 3); if (BN_cmp(e, i) < 0) { SetError(ERR_RSA_EXP_3); } else { BN_set_word(i, 0x10001); if (BN_cmp(e, i) < 0) { SetWarning(WARN_RSA_EXP_RANGE); } BN_hex2bn(&i, "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"); if (BN_cmp(e, i) > 0) { SetWarning(WARN_RSA_EXP_RANGE); } } BN_CTX *ctx = BN_CTX_new(); if (BN_gcd(i, n, bn_factors, ctx) == 0 || !BN_is_one(i)) { SetError(ERR_RSA_SMALL_FACTOR); } BN_free(i); BN_CTX_free(ctx); RSA_free(rsa); } else if (EVP_PKEY_base_id(pkey) == EVP_PKEY_EC) { EC_KEY *ec_key = EVP_PKEY_get1_EC_KEY(pkey); const EC_GROUP *group = EC_KEY_get0_group(ec_key); const EC_POINT *point = EC_KEY_get0_public_key(ec_key); BN_CTX *ctx = BN_CTX_new(); BIGNUM *order = BN_new(); EC_GROUP_get_order(group, order, ctx); if (EC_POINT_is_at_infinity(group, point)) { SetError(ERR_EC_AT_INFINITY); } if (EC_POINT_is_on_curve(group, point, ctx) != 1) { SetError(ERR_EC_POINT_NOT_ON_CURVE); } EC_POINT *result = EC_POINT_new(group); if (BN_is_zero(order)) { SetError(ERR_EC_INVALID_GROUP_ORDER); } EC_POINT_mul(group, result, NULL, point, order, ctx); if (!EC_POINT_is_at_infinity(group, result)) { SetError(ERR_EC_INCORRECT_ORDER); } int nid = EC_GROUP_get_curve_name(group); if (nid != NID_X9_62_prime256v1 && nid != NID_secp384r1 && nid != NID_secp521r1) { SetError(ERR_EC_NON_ALLOWED_CURVE); } EC_POINT_free(result); BN_free(order); BN_CTX_free(ctx); EC_KEY_free(ec_key); } else { SetError(ERR_UNKNOWN_PUBLIC_KEY_TYPE); } if (pkey != NULL) { EVP_PKEY_free(pkey); } }
/* 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); }