/* Generate an RSA key. The base-2 logarithm of the modulus n will lie in the * interval [numbits - 1, numbits). Calls abort if any error occurs. */ void rsa_genkey(struct rsa_key *key, unsigned int numbits) { //Init our mpz vars mpz_t p, q, n, pq, d, e; mpz_init(pq); mpz_init(d); mpz_init(e); mpz_init(n); mpz_init(p); mpz_init(q); //Generate two primes and make sure they are different int cmp = 0; while(cmp == 0) { generate_prime(p, numbits/2); generate_prime(q, numbits/2); cmp = mpz_cmp(p, q); } //Generate n as the product of p and q mpz_mul(n, p, q); //Generate (p-1)(q-1) mpz_sub_ui(p, p, 1); mpz_sub_ui(q, q, 1); mpz_mul(pq, p, q); //Set e to be 65537 mpz_set_ui(e, 65537); //Find d = e^-1 mod (p-1)(q-1) mpz_invert(d, e, pq); //Set our key vars mpz_set(key->d, d); mpz_set(key->e, e); mpz_set(key->n, n); //Cleanup mpz_clear(d); mpz_clear(e); mpz_clear(n); mpz_clear(p); mpz_clear(q); mpz_clear(pq); }
void SPDZ_Data_Setup_Primes(bigint& p,int lgp,int& idx,int& m) { cout << "Setting up parameters" << endl; switch (lgp) { case -1: m=16; idx=1; // Any old figures will do, but need to be for lgp at last lgp=32; // Switch to bigger prime to get parameters break; case 32: m=8192; idx=0; break; case 64: m=16384; idx=1; break; case 128: m=32768; idx=2; break; case 256: m=32768; idx=3; break; case 512: m=65536; idx=4; break; default: m=1; idx=0; cout << "no precomputed parameters, trying anyway" << endl; break; } cout << "m = " << m << endl; generate_prime(p, lgp, m); }
int main(void) { long prime[SIZE],g; int i; generate_prime(prime); while(scanf("%ld",&g)==1 && g){ printf("%ld =",g); if(g<0){ printf(" -1 x"); g*=-1; } for(i=0;i<SIZE && g>1;i++) while((g%prime[i])==0){ printf(" %ld",prime[i]); g/=prime[i]; if(g>1) printf(" x"); else printf("\n"); } if(i==SIZE && g>1) printf(" %ld\n",g); } return 0; }
/* ** Generate and return a new RSA public and private key. ** Both keys are encoded in a single RSAPrivateKey structure. ** "cx" is the random number generator context ** "keySizeInBits" is the size of the key to be generated, in bits. ** 512, 1024, etc. ** "publicExponent" when not NULL is a pointer to some data that ** represents the public exponent to use. The data is a byte ** encoded integer, in "big endian" order. */ RSAPrivateKey * RSA_NewKey(int keySizeInBits, SECItem *publicExponent) { unsigned int primeLen; mp_int p, q, e, d; int kiter; mp_err err = MP_OKAY; SECStatus rv = SECSuccess; int prerr = 0; RSAPrivateKey *key = NULL; PLArenaPool *arena = NULL; /* Require key size to be a multiple of 16 bits. */ if (!publicExponent || keySizeInBits % 16 != 0 || BAD_RSA_KEY_SIZE(keySizeInBits/8, publicExponent->len)) { PORT_SetError(SEC_ERROR_INVALID_ARGS); return NULL; } /* 1. Allocate arena & key */ arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE); if (!arena) { PORT_SetError(SEC_ERROR_NO_MEMORY); return NULL; } key = PORT_ArenaZNew(arena, RSAPrivateKey); if (!key) { PORT_SetError(SEC_ERROR_NO_MEMORY); PORT_FreeArena(arena, PR_TRUE); return NULL; } key->arena = arena; /* length of primes p and q (in bytes) */ primeLen = keySizeInBits / (2 * PR_BITS_PER_BYTE); MP_DIGITS(&p) = 0; MP_DIGITS(&q) = 0; MP_DIGITS(&e) = 0; MP_DIGITS(&d) = 0; CHECK_MPI_OK( mp_init(&p) ); CHECK_MPI_OK( mp_init(&q) ); CHECK_MPI_OK( mp_init(&e) ); CHECK_MPI_OK( mp_init(&d) ); /* 2. Set the version number (PKCS1 v1.5 says it should be zero) */ SECITEM_AllocItem(arena, &key->version, 1); key->version.data[0] = 0; /* 3. Set the public exponent */ SECITEM_TO_MPINT(*publicExponent, &e); kiter = 0; do { prerr = 0; PORT_SetError(0); CHECK_SEC_OK( generate_prime(&p, primeLen) ); CHECK_SEC_OK( generate_prime(&q, primeLen) ); /* Assure q < p */ if (mp_cmp(&p, &q) < 0) mp_exch(&p, &q); /* Attempt to use these primes to generate a key */ rv = rsa_build_from_primes(&p, &q, &e, PR_FALSE, /* needPublicExponent=false */ &d, PR_TRUE, /* needPrivateExponent=true */ key, keySizeInBits); if (rv == SECSuccess) break; /* generated two good primes */ prerr = PORT_GetError(); kiter++; /* loop until have primes */ } while (prerr == SEC_ERROR_NEED_RANDOM && kiter < MAX_KEY_GEN_ATTEMPTS); if (prerr) goto cleanup; cleanup: mp_clear(&p); mp_clear(&q); mp_clear(&e); mp_clear(&d); if (err) { MP_TO_SEC_ERROR(err); rv = SECFailure; } if (rv && arena) { PORT_FreeArena(arena, PR_TRUE); key = NULL; } return key; }
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { // See FIPS 186-4 appendix B.3. This function implements a generalized version // of the FIPS algorithm. |RSA_generate_key_fips| performs additional checks // for FIPS-compliant key generation. // Always generate RSA keys which are a multiple of 128 bits. Round |bits| // down as needed. bits &= ~127; // Reject excessively small keys. if (bits < 256) { OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } // Reject excessively large public exponents. Windows CryptoAPI and Go don't // support values larger than 32 bits, so match their limits for generating // keys. (|check_modulus_and_exponent_sizes| uses a slightly more conservative // value, but we don't need to support generating such keys.) // https://github.com/golang/go/issues/3161 // https://msdn.microsoft.com/en-us/library/aa387685(VS.85).aspx if (BN_num_bits(e_value) > 32) { OPENSSL_PUT_ERROR(RSA, RSA_R_BAD_E_VALUE); return 0; } int ret = 0; int prime_bits = bits / 2; BN_CTX *ctx = BN_CTX_new(); if (ctx == NULL) { goto bn_err; } BN_CTX_start(ctx); BIGNUM *totient = BN_CTX_get(ctx); BIGNUM *pm1 = BN_CTX_get(ctx); BIGNUM *qm1 = BN_CTX_get(ctx); BIGNUM *sqrt2 = BN_CTX_get(ctx); BIGNUM *pow2_prime_bits_100 = BN_CTX_get(ctx); BIGNUM *pow2_prime_bits = BN_CTX_get(ctx); if (totient == NULL || pm1 == NULL || qm1 == NULL || sqrt2 == NULL || pow2_prime_bits_100 == NULL || pow2_prime_bits == NULL || !BN_set_bit(pow2_prime_bits_100, prime_bits - 100) || !BN_set_bit(pow2_prime_bits, prime_bits)) { goto bn_err; } // We need the RSA components non-NULL. if (!ensure_bignum(&rsa->n) || !ensure_bignum(&rsa->d) || !ensure_bignum(&rsa->e) || !ensure_bignum(&rsa->p) || !ensure_bignum(&rsa->q) || !ensure_bignum(&rsa->dmp1) || !ensure_bignum(&rsa->dmq1)) { goto bn_err; } if (!BN_copy(rsa->e, e_value)) { goto bn_err; } // Compute sqrt2 >= ⌊2^(prime_bits-1)×√2⌋. if (!bn_set_words(sqrt2, kBoringSSLRSASqrtTwo, kBoringSSLRSASqrtTwoLen)) { goto bn_err; } int sqrt2_bits = kBoringSSLRSASqrtTwoLen * BN_BITS2; assert(sqrt2_bits == (int)BN_num_bits(sqrt2)); if (sqrt2_bits > prime_bits) { // For key sizes up to 3072 (prime_bits = 1536), this is exactly // ⌊2^(prime_bits-1)×√2⌋. if (!BN_rshift(sqrt2, sqrt2, sqrt2_bits - prime_bits)) { goto bn_err; } } else if (prime_bits > sqrt2_bits) { // For key sizes beyond 3072, this is approximate. We err towards retrying // to ensure our key is the right size and round up. if (!BN_add_word(sqrt2, 1) || !BN_lshift(sqrt2, sqrt2, prime_bits - sqrt2_bits)) { goto bn_err; } } assert(prime_bits == (int)BN_num_bits(sqrt2)); do { // Generate p and q, each of size |prime_bits|, using the steps outlined in // appendix FIPS 186-4 appendix B.3.3. if (!generate_prime(rsa->p, prime_bits, rsa->e, NULL, sqrt2, pow2_prime_bits_100, ctx, cb) || !BN_GENCB_call(cb, 3, 0) || !generate_prime(rsa->q, prime_bits, rsa->e, rsa->p, sqrt2, pow2_prime_bits_100, ctx, cb) || !BN_GENCB_call(cb, 3, 1)) { goto bn_err; } if (BN_cmp(rsa->p, rsa->q) < 0) { BIGNUM *tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-4. This differs // from typical RSA implementations which use (p-1)*(q-1). // // Note this means the size of d might reveal information about p-1 and // q-1. However, we do operations with Chinese Remainder Theorem, so we only // use d (mod p-1) and d (mod q-1) as exponents. Using a minimal totient // does not affect those two values. int no_inverse; if (!bn_usub_consttime(pm1, rsa->p, BN_value_one()) || !bn_usub_consttime(qm1, rsa->q, BN_value_one()) || !bn_lcm_consttime(totient, pm1, qm1, ctx) || !bn_mod_inverse_consttime(rsa->d, &no_inverse, rsa->e, totient, ctx)) { goto bn_err; } // Retry if |rsa->d| <= 2^|prime_bits|. See appendix B.3.1's guidance on // values for d. } while (BN_cmp(rsa->d, pow2_prime_bits) <= 0); if (// Calculate n. !bn_mul_consttime(rsa->n, rsa->p, rsa->q, ctx) || // Calculate d mod (p-1). !bn_div_consttime(NULL, rsa->dmp1, rsa->d, pm1, ctx) || // Calculate d mod (q-1) !bn_div_consttime(NULL, rsa->dmq1, rsa->d, qm1, ctx)) { goto bn_err; } bn_set_minimal_width(rsa->n); // Sanity-check that |rsa->n| has the specified size. This is implied by // |generate_prime|'s bounds. if (BN_num_bits(rsa->n) != (unsigned)bits) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); goto err; } // Call |freeze_private_key| to compute the inverse of q mod p, by way of // |rsa->mont_p|. if (!freeze_private_key(rsa, ctx)) { goto bn_err; } // The key generation process is complex and thus error-prone. It could be // disastrous to generate and then use a bad key so double-check that the key // makes sense. if (!RSA_check_key(rsa)) { OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR); goto err; } ret = 1; bn_err: if (!ret) { OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); } err: if (ctx != NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); } return ret; }
int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e_value, BN_GENCB *cb) { // See FIPS 186-4 appendix B.3. This function implements a generalized version // of the FIPS algorithm. |RSA_generate_key_fips| performs additional checks // for FIPS-compliant key generation. // Always generate RSA keys which are a multiple of 128 bits. Round |bits| // down as needed. bits &= ~127; // Reject excessively small keys. if (bits < 256) { OPENSSL_PUT_ERROR(RSA, RSA_R_KEY_SIZE_TOO_SMALL); return 0; } int ret = 0; BN_CTX *ctx = BN_CTX_new(); if (ctx == NULL) { goto bn_err; } BN_CTX_start(ctx); BIGNUM *totient = BN_CTX_get(ctx); BIGNUM *pm1 = BN_CTX_get(ctx); BIGNUM *qm1 = BN_CTX_get(ctx); BIGNUM *gcd = BN_CTX_get(ctx); BIGNUM *sqrt2 = BN_CTX_get(ctx); if (totient == NULL || pm1 == NULL || qm1 == NULL || gcd == NULL || sqrt2 == NULL) { goto bn_err; } // We need the RSA components non-NULL. if (!ensure_bignum(&rsa->n) || !ensure_bignum(&rsa->d) || !ensure_bignum(&rsa->e) || !ensure_bignum(&rsa->p) || !ensure_bignum(&rsa->q) || !ensure_bignum(&rsa->dmp1) || !ensure_bignum(&rsa->dmq1)) { goto bn_err; } if (!BN_copy(rsa->e, e_value)) { goto bn_err; } int prime_bits = bits / 2; // Compute sqrt2 >= ⌊2^(prime_bits-1)×√2⌋. if (!bn_set_words(sqrt2, kBoringSSLRSASqrtTwo, kBoringSSLRSASqrtTwoLen)) { goto bn_err; } int sqrt2_bits = kBoringSSLRSASqrtTwoLen * BN_BITS2; assert(sqrt2_bits == (int)BN_num_bits(sqrt2)); if (sqrt2_bits > prime_bits) { // For key sizes up to 3072 (prime_bits = 1536), this is exactly // ⌊2^(prime_bits-1)×√2⌋. if (!BN_rshift(sqrt2, sqrt2, sqrt2_bits - prime_bits)) { goto bn_err; } } else if (prime_bits > sqrt2_bits) { // For key sizes beyond 3072, this is approximate. We err towards retrying // to ensure our key is the right size and round up. if (!BN_add_word(sqrt2, 1) || !BN_lshift(sqrt2, sqrt2, prime_bits - sqrt2_bits)) { goto bn_err; } } assert(prime_bits == (int)BN_num_bits(sqrt2)); do { // Generate p and q, each of size |prime_bits|, using the steps outlined in // appendix FIPS 186-4 appendix B.3.3. if (!generate_prime(rsa->p, prime_bits, rsa->e, NULL, sqrt2, ctx, cb) || !BN_GENCB_call(cb, 3, 0) || !generate_prime(rsa->q, prime_bits, rsa->e, rsa->p, sqrt2, ctx, cb) || !BN_GENCB_call(cb, 3, 1)) { goto bn_err; } if (BN_cmp(rsa->p, rsa->q) < 0) { BIGNUM *tmp = rsa->p; rsa->p = rsa->q; rsa->q = tmp; } // Calculate d = e^(-1) (mod lcm(p-1, q-1)), per FIPS 186-4. This differs // from typical RSA implementations which use (p-1)*(q-1). // // Note this means the size of d might reveal information about p-1 and // q-1. However, we do operations with Chinese Remainder Theorem, so we only // use d (mod p-1) and d (mod q-1) as exponents. Using a minimal totient // does not affect those two values. if (!BN_sub(pm1, rsa->p, BN_value_one()) || !BN_sub(qm1, rsa->q, BN_value_one()) || !BN_mul(totient, pm1, qm1, ctx) || !BN_gcd(gcd, pm1, qm1, ctx) || !BN_div(totient, NULL, totient, gcd, ctx) || !BN_mod_inverse(rsa->d, rsa->e, totient, ctx)) { goto bn_err; } // Check that |rsa->d| > 2^|prime_bits| and try again if it fails. See // appendix B.3.1's guidance on values for d. } while (!rsa_greater_than_pow2(rsa->d, prime_bits)); if (// Calculate n. !BN_mul(rsa->n, rsa->p, rsa->q, ctx) || // Calculate d mod (p-1). !BN_mod(rsa->dmp1, rsa->d, pm1, ctx) || // Calculate d mod (q-1) !BN_mod(rsa->dmq1, rsa->d, qm1, ctx)) { goto bn_err; } // Sanity-check that |rsa->n| has the specified size. This is implied by // |generate_prime|'s bounds. if (BN_num_bits(rsa->n) != (unsigned)bits) { OPENSSL_PUT_ERROR(RSA, ERR_R_INTERNAL_ERROR); goto err; } // Call |freeze_private_key| to compute the inverse of q mod p, by way of // |rsa->mont_p|. if (!freeze_private_key(rsa, ctx)) { goto bn_err; } // The key generation process is complex and thus error-prone. It could be // disastrous to generate and then use a bad key so double-check that the key // makes sense. if (!RSA_check_key(rsa)) { OPENSSL_PUT_ERROR(RSA, RSA_R_INTERNAL_ERROR); goto err; } ret = 1; bn_err: if (!ret) { OPENSSL_PUT_ERROR(RSA, ERR_LIB_BN); } err: if (ctx != NULL) { BN_CTX_end(ctx); BN_CTX_free(ctx); } return ret; }