示例#1
0
文件: set5.c 项目: avanpo/cryptopals
void challenge_33()
{
	srand(time(NULL));
	int p = 37;
	int g = 5;

	int a = randn(37);
	int A = modexp(g, a, p);

	int b = randn(37);
	int B = modexp(g, b, p);

	int s = modexp(B, a, p);
	if (s == modexp(A, b, p)) {
		printf("Shared secrets are equal: %d\n", s);
	}

	gmp_randstate_t *state = gmp_rand();
	mpz_t mp, mg, ma, mb, mA, mB;
	unsigned char key1[16], key2[16];

	dh_params(mp, mg);
	dh_keyexchange(state, mp, mg, ma, mA);
	dh_keyexchange(state, mp, mg, mb, mB);

	dh_finished(mp, mB, ma, key1);
	dh_finished(mp, mA, mb, key2);
	
	if (memcmp(key1, key2, 16) == 0) {
		print_str("Shared keys are equal:");
		print_hex(key1, 16);
	}

	dh_cleanup(state, mp, mg, ma, mA, mb, mB);
}
示例#2
0
	vlong private_key::decrypt( const vlong& cipher )
	{
		// Calculate values for performing decryption
		// These could be cached, but the calculation is quite fast
		vlong d = modinv( e, (p-(vlong)1)*(q-(vlong)1) );
		vlong u = modinv( p, q );
		vlong dp = d % (p-(vlong)1);
		vlong dq = d % (q-(vlong)1);

		// Apply chinese remainder theorem
		vlong a = modexp( cipher % p, dp, p );
		vlong b = modexp( cipher % q, dq, q );
		if ( b < a ) b += q;
		return a + p * ( ((b-a)*u) % q );
	}
示例#3
0
文件: baby.c 项目: filipecn/ICPC
LL solve(LL a, LL b, LL n) // baby step giant step, a^x = b mod n! gcd(a, n) == gcd(b, n) == 1 !!
{
	if (gcd(a, n) != 1 || gcd(b, n) != 1) return -1;
	vector<pair<LL, LL> > v;
	LL m = sqrt(n)+1, aa = 1;
	// baby step
	for (LL j = 0; j < m; ++j)
	{
		v.push_back(mp(aa, j));
		aa = aa*a;
		if (aa > n) aa %= n;
	}
	sort(v.begin(), v.end());
	LL in = inverse(a, n);
	in = modexp(in, m, n);
	// giant step
	LL y = b;
	for (LL i = 0; i < n/m+1; ++i)
	{
		typeof(v.begin()) f = lower_bound(v.begin(), v.end(), mp(y, 0LL));
		if (f != v.end() && f->F == y) return i*m+f->S;
		y = (y*in);
		if (y > n) y %= n;
	}
	return -1;
}
示例#4
0
void init_inverses()
{
 int i;
 for (i = 1; i < PRIME; i++) {
  inv[i] = modexp(i, PRIME-2);
 }
}
示例#5
0
int findGen(long long start, long long end,int factorSize, long long *myFactor)
{
    int x;
    int generatorSize=0;
    for (x=start;x<end;x++)
    {
        int gen = 1;
        int k;
        for (k=0; k<factorSize; k++)
        {
            if (modexp(x, (p-1)/myFactor[k], p)==1)
            {
                gen=0;
                break;
            }
        }
        if (gen)
        {
            if (x>=min && x<=max)
                printf("A generator for %d is %d.\n",p,x);
            generatorSize++;
        }
    }
    return generatorSize;
}
示例#6
0
文件: rsa.c 项目: ArineYao/algorithms
void rsa_encipher(Huge plaintext, Huge *ciphertext, RsaPubKey pubkey) {

*ciphertext = modexp(plaintext, pubkey.e, pubkey.n);

return;

}
示例#7
0
int main()
{
//BigUnsigned a = 8866446688, b = 196819691970, 
//    p = 2425967623052370772757633156976982469681, g = 3;
//
//BigUnsigned A(modexp(g,a,p)), B(modexp(g,b,p));
//std::cout << std::endl << 
//  "g^a(mod p) = A = " << A << std::endl <<
//  "g^b(mod p) = B = " << B << std::endl <<
//  "Alice's K  = B^a(mod p) = " << modexp(B, a, p) << std::endl <<
//  "Bob's K    = A^b(mod p) = " << modexp(A, b, p) << std::endl <<
//  std::endl;

  std::cout << "Example 9.4:\n\n";
  BigUnsigned s(1790), e(883), n(1817), m(1776);
  std::cout << "Alice sent (s,n,e) of (" << s << ", " << e << ", " << n << ") " <<
    "for the message " << m << ".\nBob authenticates to " <<
    RSADigitalSigAuthenticate(s,e,n) << std::endl;
  std::cout << "The signature is ";
  if(m != RSADigitalSigAuthenticate(s,e,n)) std::cout << "not ";
  std::cout << "valid.\n";

  std::cout << "\n\n\n";
  e = 727641838100;
  n = 153817*1542689;
  m = 888999000;
  s = modexp(m, 25936022131, n);
  std::cout << "Alice sent (s,n,e) of (" << s << ", " << e << ", " << n << ") " <<
    "for the message " << m << ".\nBob authenticates to " <<
    RSADigitalSigAuthenticate(s,e,n) << std::endl;
  std::cout << "The signature is ";
  if(m != RSADigitalSigAuthenticate(s,e,n)) std::cout << "not ";
  std::cout << "valid.\n";
  return 0;
}
示例#8
0
文件: rsa.c 项目: ArineYao/algorithms
void rsa_decipher(Huge ciphertext, Huge *plaintext, RsaPriKey prikey) {

*plaintext = modexp(ciphertext, prikey.d, prikey.n);

return;

}
示例#9
0
文件: impl.cpp 项目: gxr/CryptoBreaks
//we don't have to bother with making sure that gcd(R,M) == 1 since M is odd.
uberzahl modexp_mm(mm_t & mm, uberzahl base, uberzahl exp, uberzahl M){
	if(!mm.initialized){
		mm.R = next_power(M);
		mm.Rbits = mm.R.bitLength();
		mm.Mprime = (mm.R-M.inverse(mm.R));
		uberzahl z("1");
		uberzahl t("2");
		mm.Rsq = modexp(mm.R,t,M);
		//mm.z_init = mm.R % M;
		mm.z_init = montgomery_reduction(mm.Rsq, M, mm.Mprime, mm.Rbits, mm.R);
		mm.initialized = true;
	}

	//convert into Montgomery space
	uberzahl z = mm.z_init;

	//According to Piazza post we don't even need to calculate the residues with mod
	if(base * mm.Rsq < mm.R*M)
		base = montgomery_reduction(base * mm.Rsq, M, mm.Mprime, mm.Rbits, mm.R);
	else
		base = base * mm.R % M;

	mediumType i = exp.bitLength() - 1;

	while(i >= 0) {
		z = montgomery_reduction(z * z, M, mm.Mprime, mm.Rbits, mm.R);
		if(exp.bit(i) == 1){
			z = montgomery_reduction(z * base , M, mm.Mprime, mm.Rbits, mm.R);
		}
		if(i == 0)
			break;
		i -= 1;
	}
	return montgomery_reduction(z, M, mm.Mprime, mm.Rbits, mm.R);
}
示例#10
0
// Checks if given number if prime 
bool isPrime(XLong& number)
{
	// if number is even it can't ne prime
	if (!number.bt(0)) return false;

	/*
	// algorithm #1 (school like)
	// if (P mod i) == 0, for all (i = 2..t) or (i = 2..sqrt(t))
	// then P is prime 
	//
	XLong i(0,number.GetBitLength());
	XLong t(0,number.GetBitLength());
	t = root(number,2);	//t = number;
	//
    for (i=2; i< t; i++)
    {
        if (number % i == 0)  // check 
            return false;
    }
    return true;*/


/*
	// algorithm #2 (strong)
	// if  M^P,mod P = M, where M <= P
	// then P is prime 
	//
	XLong M(0,number.GetBitLength());
	XLong M1(0,number.GetBitLength());
	M = 2; // any constant < number
#if 1 
	M1 = modexp(M,number,number); 
#else
	M1 = power(M,number);M1 = M1%number;
#endif
	if (M1 == M)
	{
		return true;
	}
*/
	
	
	// algorithm #3 (strongest)
	// if  M^((P-1)/2),mod P = +-1 (1 or P-1), where M <= P
	// then P is prime 
	//
	XLong M(0,number.GetBitLength());
	XLong M1(0,number.GetBitLength());
	M = 2; // any constant
	M1 = modexp(M,(number-1)/2,number);
	if ((M1 == 1) || (M1 == (number-1)))
	{
		//printf("ff");
		return true;
	}
	//
	//
	return false;
}
示例#11
0
文件: impl.cpp 项目: gxr/CryptoBreaks
uberzahl crt_helper(bool type, mm_t & mm, uberzahl base, uberzahl exp, uberzahl p, uberzahl q, uberzahl q_inverse){
	if(type == CLASSIC)
		return modexp(base, exp % (p-1), p) * q * q_inverse;
	else if(type == MONTGOMERY)
		return modexp_mm(mm, base, exp % (p-1),p) * q * q_inverse;
	//Only types allowed are CLASSIC and MONTGOMERY!
	assert(0);
}
示例#12
0
bool CryptoScheme::isProbablyPrime(const BigUnsigned& n) {
    if (n%2 == 0 || n==1) return n==2;
    for (int i = 0; i < 30; i++) {
        BigUnsigned a = random(n.bitLength()-1);
        if (modexp(a, n-1, n) != 1) return false;
    }
    return true;
}
示例#13
0
文件: pthread_6.c 项目: dtbinh/cs450
void
pthreads_6 (void)
{
  /* PTHREADS 6 */
  int i = 0;

  int rc = 0;
  pthread_t threads[4];
  pthread_attr_t attr;
  void *status = NULL;

  modexp_t params[4];
  uint64_t results[4] = { 0, 0, 0, 0 };

  bool threaded = false;

  /* Set up arguments for 4 calls to modexp */
  for (i = 0; i < 4; i++)
    {
      params[i].base = base_values[i];
      params[i].power = powers[i];
      params[i].modulus = modulus[i];
    }

  if (threaded)
    {
      /* Make the thread "joinable" so we can wait on it */
      pthread_attr_init (&attr);
      pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_JOINABLE);

      /* Fix this multithreaded version to pass the arguments */
      for (i = 0; i < 4; i++)
        {
          rc = pthread_create (&threads[i], &attr, mod_exp_thread, (void *)i);
          assert (rc == 0);
        }

      for (i = 0; i < NUM_THREADS; i++)
        {
          rc = pthread_join (threads[i], &status);
          assert (rc == 0);
        }
    }
  else
    {
      for (i = 0; i < 4; i++)
        modexp (&params[i]);
        /* results[i] = modexp (&params[i]); */
    }

  /*
  for (i = 0; i < 4; i++)
    printf ("%" PRIu64 "^%" PRIu64 " mod %" PRIu64 " = %" PRIu64 "\n",
            params[i].base, params[i].power, params[i].modulus, results[i]);
            */

  /* END PTHREADS 6 */
}
示例#14
0
文件: modexp.cpp 项目: wo3kie/cxxDojo
void modexp_test(){
	for(unsigned a = 1; a < 10; ++a){
		for(unsigned exp = 1; exp < 10; ++exp){
			for(unsigned mod = 1; mod < 10; ++mod){
				assert(modexp(a, exp, mod) == (unsigned)std::pow(a, exp) % mod);
			}
		}
	}
}
示例#15
0
//解密,用5元组形式的私钥
vlong rsa_decrypt(
				  const vlong& cipher,
				  const vlong& p,
				  const vlong& q,
				  const vlong& dp,
				  const vlong& dq,
				  const vlong& qinv
				  )
{
	if (p == 0 || q == 0 || dp == 0 || dq == 0 || qinv == 0) return 0;

	vlong m1 = modexp( cipher % p, dp, p );
	vlong m2 = modexp( cipher % q, dq, q );

	if ( m1 < m2 ) m1 += p;

	return m2 + q * ( ((m1-m2)*qinv) % p );
}
示例#16
0
//解密
vlong rsa_decrypt(
				  const vlong& cipher ,
				  const vlong& d,
				  const vlong& m
				  )
{
	if (d == 0 || m == 0) return 0;
	return modexp( cipher , d ,m);
}
示例#17
0
int modexp(int a, int b, int c){
  if (b==0)
    return 1;
  ll tmp = modexp(a,b/2,c);
  tmp = (tmp * tmp) % c;
  if ((b%2)==1)
    tmp = (tmp * a) % c;
  return (int)tmp;
}
示例#18
0
文件: p2.c 项目: ngzhian/cs3211-p2
int main(int argc, char *argv[]) {
  long p = atol(argv[1]);
  if (p == 0) return 0;

  double start, end;
  int my_rank, num_procs;

  MPI_Init(&argc, &argv);
  MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
  MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
  
  long num_per_proc = p/num_procs + 1;

  long *factors = malloc(2 * sqrt(p-1) * sizeof(long));
  long num_factors = find_prime_factors(p-1, factors);

  long candidate_start = my_rank * num_per_proc + 1;
  long candidate_end = num_per_proc * (my_rank + 1);

  long candidate;
  long num_gens = 0;

  start = MPI_Wtime();

  //printf("rank: %ld, start: %ld, end: %ld\n", my_rank, candidate_start, candidate_end);
  for (candidate = candidate_start; candidate <= candidate_end; candidate++) {
    if (candidate == 0 || candidate == 1 || candidate >= p) {
      continue;
    }
    long is_generator = 1;
    long j;
    for (j = 0; j < num_factors; j++) {
      long factor = factors[j];
      long m = modexp(candidate, (p-1)/factor, p);
      if (m == 1L) {
        is_generator = 0;
        break;
      }
    }
    if (is_generator) {
      //printf("%ld is a generator\n", candidate);
      num_gens++;
    }
  }


  long total_gens;
  int success = MPI_Reduce(&num_gens, &total_gens, 1, MPI_LONG, MPI_SUM, 0, MPI_COMM_WORLD);

  end = MPI_Wtime();
  if (my_rank == 0) {
    printf("%d: %ld total\n", my_rank, total_gens);
    printf("time taken: %f\n", end - start);
  } 
  MPI_Finalize();

}
示例#19
0
文件: modexp.cpp 项目: wo3kie/cxxDojo
constexpr unsigned modexp(unsigned a, unsigned exp, unsigned mod){
	return exp == 0
		? 1
		
		//: exp % 2 == 0
		//	? (    pow2(modexp(a, exp/2, mod))) % mod
		//	: (a * pow2(modexp(a, exp/2, mod))) % mod;

		: ( (exp % 2 == 0 ? 1 : a) * pow2(modexp(a, exp/2, mod)) % mod );
}
示例#20
0
	vlong public_key::encrypt( const vlong& plain )
	{
#if defined(__DEBUG__)
		if ( plain >= m ) 
		{
			printf("ERROR: plain too big for this key\n");
		}
#endif
		return modexp( plain, e, m );
	}
示例#21
0
int main() {
	unsigned long long sum = 0;

	for(int i = 1; i <= 1000; ++i)
		sum = modsum(sum, modexp(i, i, BASE), BASE);

	std::cout << sum << std::endl;

	return 0;
}
示例#22
0
文件: dhkey.cpp 项目: uvbs/wx2Server
bool CDHKey::Agree(unsigned char *EncryptionKey,unsigned char *RecipientInterKey)
{
	memset(EncryptionKey,0,size/8);
	aInterKey.buftov(RecipientInterKey,size);
	key=modexp(aInterKey,a,n);
	if(key<(vlong)1000)
		return false;
	key.vtobuf(EncryptionKey,size);
	return true;
}
示例#23
0
文件: rsa_os.c 项目: odzhan/tinycrypt
void key_xchg (void)
{
  if (init_session())  // initialize session key
  {
    if (recv_pkt())    // receive public key
    {      
      modexp();        // encrypt the session key
      send_pkt();      // send session key
    }
  }
}
示例#24
0
文件: Factor.cpp 项目: lancerd/OJCODE
bool Miller(const int &base,const LL &n)
{
    if(base>=n) return true;
    LL d = n-1, s = 0;
    while( !(d&1) ) { s++; d>>=1; }
    LL x = modexp(base,d,n);
    if(x==1) return true;
    for(int r=0;r<s;r++,x=LLmul(x,x,n))
        if(x==n-1)
            return true;
    return false;
}
示例#25
0
int main(){
  int i;
  ll sum = 0;
  ll talj, namn;
  scanf("%d %d",&n,&k);
  talj = k;
  namn = 1;
  for (i=2;i<=k;i++) {
    ll tmp = modexp(i-1,n-1,MOD);
    tmp = (tmp * i) % MOD;
    talj = (talj * (k-i+1)) % MOD;
    namn = (namn * modexp(i,MOD-2,MOD)) % MOD;
    tmp = (tmp * talj) % MOD;
    tmp = (tmp * namn) % MOD;
    if ((k-i) % 2 == 1)
      tmp = MOD-tmp;
    sum = (sum + tmp) % MOD;
  }
  printf("%lld\n", sum);
  return 0;
}
示例#26
0
int modexp(int a, int e)
{
 if (e == 1) {
  return a;
 } else {
  int sq = modexp(a, e/2);
  sq = (sq * sq) % PRIME;
  if (e & 1) {
   sq = (sq * a) % PRIME;
  }
  return sq;
 }
}
int main()
{
    unsigned long p,q,e,d,n,z,i,c,m;
    int len;
    char data[100];
    printf("\nenter values of P and Q (such that P and Q > 255)");
    scanf("%lu %lu",&p,&q);
    n=p*q;
    z=(p-1)*(q-1);
    for(i=1; i<z; i++)
    {
        if((z%i)==0)
            continue;
        else
            break;
    }
    e=i;
    printf("\nencryption key is %lu",e);
    for(i=1; i<z; i++)
        if(((e*i-1)%z)==0)
            break;
    d=i;
    printf("\ndecryption value is %lu",d);
    printf("\nenter the message\n");
    scanf("%s",data);
    len=strlen(data);

    for(i=0; i<len; i++)
    {
        m=(unsigned long) data[i];
        c=modexp(m,e,n);
        printf("\nencryption value & its character representation is %lu\t %c\n",c,c);
        m=modexp(c,d,n);
        printf("\ndecryption value and its character representation is %lu \t %c\n",m,m);
    }
    printf("decrypted message is %s\n%d\n%d\n",data,c,m);
    return 0;
}
示例#28
0
int main()
{
  const int number = 11;
  const int exponent = 644;
  const int modulation = 645;
  
  char * expandedValue;
  size_t size = 0;
  
  expandedValue = baseexpansion(exponent, 2, &size);
   
  printf("Result of %i^%i mod %i = %i\n", number, exponent, modulation, modexp(number, expandedValue, size, modulation));
   
  return 0;
}
示例#29
0
int main(int argc, char *argv[]) {
  
  uint64_t result=0;
  
  if (argc != 4) {
    printf ("\nUsage: modexp <base> <exponent> <modulus>\n");
    return 0;
  }
  
  result = modexp (_strtoui64(argv[1], NULL, 10), 
    _strtoui64(argv[2], NULL, 10),
    _strtoui64(argv[3], NULL, 10)); 

  printf ("\n%llu = %s ^ %s %% %s", 
    result, argv[1], argv[2], argv[3]);
  return 0;
}
示例#30
0
SecureArray QCACryptoInterface::sharedDHKey(const QString &prime, const QString &base, const QString &secret)
{
    BigUnsigned primeNumber = stringToBigUnsigned(prime.toStdString());
    BigInteger baseNumber = stringToBigUnsigned(base.toStdString());
    BigUnsigned secretNumber = stringToBigUnsigned(secret.toStdString());
    BigUnsigned result = modexp(baseNumber, secretNumber, primeNumber);

    QByteArray key;

    BigUnsigned result2(result);
    while (result2 !=  0) {
         char rest = (result2 % 256).toUnsignedShort();
         key.prepend(rest);
         result2 = result2 / 256;
    }

    int size = key.size();
    return key;
}