当前位置:首页 » Project Euler » 详细页

RSA encryption 题号:182 难度: 60 中英对照

The RSA encryption is based on the following procedure:

Generate two distinct primes p and q.
Compute n=pq and φ=(p-1)(q-1).
Find an integer e, 1<e<φ, such that gcd(e,φ)=1.

A message in this system is a number in the interval [0,n-1].
A text to be encrypted is then somehow converted to messages (numbers in the interval [0,n-1]).
To encrypt the text, for each message, m, c=me mod n is calculated.

To decrypt the text, the following procedure is needed: calculate d such that ed=1 mod φ, then for each encrypted message, c, calculate m=cd mod n.

There exist values of e and m such that me mod n=m.
We call messages m for which me mod n=m unconcealed messages.

An issue when choosing e is that there should not be too many unconcealed messages.
For instance, let p=19 and q=37.
Then n=19*37=703 and φ=18*36=648.
If we choose e=181, then, although gcd(181,648)=1 it turns out that all possible messages
m (0≤mn-1) are unconcealed when calculating me mod n.
For any valid choice of e there exist some unconcealed messages.
It's important that the number of unconcealed messages is at a minimum.

Choose p=1009 and q=3643.
Find the sum of all values of e, 1<e<φ(1009,3643) and gcd(e,φ)=1, so that the number of unconcealed messages for this value of e is at a minimum.

Solution

在给定$p,q$的情况下,对于符合条件的$e$,目标是最小化关于的$m$方程$m=m^e\quad mod\ (pq)$的解的个数。 由于$p,q$为不等的素数,所以上式可化为: $$m=m^e\quad mod\ p$$ $$m=m^e\quad mod\ q$$ 由于$m^{p-1}=1\quad mod\ p$,而此处$m^{e-1}=1\quad mod\ p$,所以考虑其循环节得到其解的个数等于$gcd(e-1,p-1)+1$,同理对第二式有$gcd(e-1,q-1)+1$ 考虑到上两式要同时成立,所以实际上的解的个数为$[gcd(e-1,p-1)+1]\times [gcd(e-1,q-1)+1]$ 于是可以直接暴力求解。

Code

public final class p182 {
    public static void main(String[] args) {
        long start=System.nanoTime();
        String result = run();        
        long end=System.nanoTime();
        System.out.println(result);
        System.out.println( (end-start)/1000000 + "ms" );
    }
    static public String run() {
    	long ans=0;
		long min = Long.MAX_VALUE;
		for (long e = 2; e < phi; e++)
			if (gcd(e, phi) == 1) {
				long num = (gcd(e - 1, p - 1) + 1)
						* (gcd(e - 1, q - 1) + 1);

				if (num < min) {
					ans = 0;
					min = num;
				}
				if (num == min)
					ans += e;
			}
		return ""+ans;
	}

	static long p = 1009;
	static long q = 3643;

	static long phi = (p - 1) * (q - 1);

	static long gcd(long x, long y) {
		long r;
		while (y != 0) {
			r = x % y;
			x = y;
			y = r;
		}
		return x;
	}
    
    
}
399788195976
1237ms