Easily learn the principles of RSA encryption algorithms

Source: Internet
Author: User

Previously also contacted RSA encryption algorithm, feel this thing is too mysterious, is a mathematician thing, and I have nothing to do. However, after looking at a lot of information on the principles of RSA encryption algorithm, I found that the principle is not as complex as we imagined, and then found that the original is just this.

Friends who have learned the algorithm know that the algorithm in the computer is actually a mathematical operation. Therefore, before explaining the RSA encryption algorithm, it is necessary to understand some essential mathematical knowledge. Let's start with the math knowledge.

Essential Mathematical Knowledge

In RSA encryption algorithm, only a few simple mathematical knowledge such as prime number, Inma, exponential arithmetic and modulo operation are used. So, we also need to understand these concepts.

Prime

The prime number is also called Prime, which is the number of natural numbers greater than 1 that cannot be divisible by other natural numbers except 1 and the integer itself. This concept, we have learned in junior high school, even elementary school, here will not explain too much.

Inma

Baidu Encyclopedia on the explanation is: the public factor only 1 of two number, called Inma. The Wikipedia explanation is: coprime , also known as mutual- vegetarian . If the maximum common factor for n integers is 1, it is called the n integer coprime.

The common Inma judgment methods are as follows:

    1. Two different prime numbers must be Inma. For example, 2 and 7, 13, and 19.
    2. One prime number, the other is not a multiple of it, and these two numbers are Inma. For example, 3 and 10, 5, and 26.
    3. The adjacent two natural numbers are Inma. such as 15 and 16.
    4. The adjacent two odd numbers are Inma. such as 49 and 51.
    5. The larger number is the two number of prime numbers that are Inma. such as 97 and 88.
    6. Decimals are prime numbers, the large number is not a multiple of the decimal number of two numbers is Inma. For example 7 and 16.
    7. 2 and any odd number is Inma. For example 2 and 87.
    8. 1 is not a prime or a composite, it is Inma with any natural number. such as 1 and 9908.
    9. The method of dividing.
Exponential arithmetic

Exponential operation is also called power calculation, the result of calculation is called exponentiation. nm refers to n squared m times. Think of nm as the result of a power, called "N's M powers" or "N's M-squares". where n is called " base" and M is called " exponent ".

Modulo operations

Modulo operation is to find the remainder operation. "Modulo" is a transliteration of "Mod". A concept closely related to modulo operations is "congruence". Mathematically, when two integers are divided by the same positive integer, the remainder is equal to two integers.

Two integers a , B, if they are divided by the remainder of the positive integer m , is called a, b for modulo m congruence, as follows: A≡b (mod m); read:a with more than b modulo m, or,a and b about modulo m congruence. Example: 26≡14 (mod 12).

RSA encryption algorithm A brief history of RSA encryption algorithm

RSA was introduced in 1977 by Ronald Leevist (Ron rivest), Adi Samor (Adi Shamir) and Lennard Adman (Leonard Adleman). At the time, all three of them worked at MIT. RSA is the first letter of their three surnames made together.

The creation of public keys and keys

Suppose Alice wants to receive a private message from Bob through an unreliable medium. She can generate a public key and a private key in the following ways:

    1. Randomly select two large prime numbers p and Q,p is not equal to Q, calculate N=PQ.
    2. R = (p-1) (Q-1) According to the Euler function
    3. Select an integer ethat is less than R, and find the e-modulo inverse element of module R, named D. (modulo inverse element exists, when and only if E with R coprime)
    4. The records of P and Q are destroyed.

(n,e) is the public key,(N,D) is the private key. Alice passes her public key (N,e) to Bob and hides her private key (N,d).

Encrypt messages

Suppose Bob wanted to send Alice a message m, and he knew that Alice produced N and e. He used the first date with Alice to convert m to an integer nless than n , for example, he could convert each word to the Unicode code of the word, and then connect the numbers together to form a number. If his message is very long, he can divide the message into several paragraphs and then convert each section to N. Using the following formula, he can encrypt n to C:

Ne≡c (mod N)

Computing C is not complicated. Bob can pass it to Alice after he has calculated C .

Decrypting messages

After Alice gets Bob's message C , she can use her key D to decode it. She can use the following formula to convert C to N:

Cd≡n (mod n)

After getting n , she can restore the original message m .

The decoding principle is:

Cd≡n e D (mod n)

and Ed ≡1 (mod p-1) and Ed ≡1 (mod q-1). Proved by Fermat theorem (since p and Q are prime numbers)

n e d≡n (mod p) and n e d≡n (mod q)

This indicates (because p and Q are different prime numbers, so p and Q coprime)

n e d≡n (mod PQ)

Signing messages

RSA can also be used to give a message a signature. If a wants to send a signed message to B, then she can calculate a hash value for her message (Message digest), then use her key (private key) to encrypt the hash value and add the "signature" to the message. This message can only be decrypted with her public key. After obtaining this message, you can decrypt the hash value with the public key of a, and then compare the data to the hash value that he has computed for the message. If the two match, then he can know the sender holds a key, and this message has not been tampered with in the transmission path.

Programming practices

Now, let's start with our focus: programming practices. Before we start programming, we use calculations to determine the public key and the key.

Calculating public keys and keys
    1. Suppose P = 3, q = One (P,q are primes.) ), then n = PQ = 33;
    2. R = (p-1) (q-1) = (3-1) (11-1) = 20;
    3. Based on the formula of the modulo inverse element, we can conclude that e d≡1 (mod 20), i.e. e d = 20n+1 (n is a positive integer); we assume N=1, then e d = 21. E, D is a positive integer, and E is coprime with R, then E = 3,d = 7. (two numbers can also be exchanged for a bit.) )

Here, the public key and key have been determined. The public key is (n, e) = (33, 3), and the key is (n, D) = (33, 7).

Programming implementation

Here we use Java to implement the encryption and decryption process. The specific code is as follows:

RSA algorithm implementation:

[Java]View Plaincopy
  1. <span style="FONT-SIZE:14PX;"  > Packagesecurity.rsa;
  2. Public class RSA {
  3. /** 
  4. * Encryption, decryption algorithm
  5. * @param key Public key or key
  6. * @param message data
  7. * @return
  8. */
  9. public Static long RSA (int basenum, int key, long message) {
  10. if (Basenum < 1 | | Key < 1) {
  11. return 0L;
  12. }
  13. //Encrypt or decrypt the data after
  14. long rsamessage = 0L;
  15. //encryption Core algorithm
  16. Rsamessage = Math.Round (MATH.POW (message, key))% Basenum;
  17. return rsamessage;
  18. }
  19. public static void Main (string[] args) {
  20. //Cardinality
  21. int basenum = 3 * 11;
  22. //Public key
  23. int keye = 3;
  24. // key
  25. int keyd = 7;
  26. //Unencrypted data
  27. long msg = 24L;
  28. //Encrypted data
  29. Long encodemsg = RSA (Basenum, Keye, msg);
  30. //Decrypted data
  31. Long decodemsg = RSA (Basenum, Keyd, encodemsg);
  32. System.out.println ("before encryption:" + msg);
  33. System.out.println ("after encryption:" + encodemsg);
  34. System.out.println ("after decryption:" + decodemsg);
  35. }
  36. </span>
  37. }

RSA algorithm results:

Before encryption: 24
After encryption: 30
After decryption: 24

(See the program most clearly, for the number m to encrypt, M^e%n=c, C is encrypted after the ciphertext.) C^d%n=m, you can decrypt it. m)

Security of RSA encryption algorithm

When P and Q are a large prime number, the decomposition factor p and Q from their product PQ is a recognized mathematical problem. However, although RSA's security relies on the factorization of large numbers, it does not theoretically prove that the difficulty of deciphering RSA is equivalent to the difficulty of large number decomposition.

1994 Peter Sul (Peter Shor) proves that a quantum computer can decompose factoring in polynomial time. If a quantum computer can someday become a viable technology, then the algorithm can eliminate RSA and related derivative algorithms. (i.e., a cryptographic algorithm that relies on the decomposition of large integer difficulties)

In addition, if the length of N is less than or equal to 256 bits, then a personal computer can decompose its factor within a few hours. In 1999, hundreds of computers collaborated to decompose a 512-bit long N. 1997 years after the development of the system, the user should use a 1024-bit key, certification authority application 2048 or more.

Disadvantages of RSA encryption algorithm

Although RSA encryption algorithm, as one of the best public key schemes, has experienced various attacks and gradually accepted them for more than 30 years of publication. However, it is not that RSA has no shortcomings. There is no theoretical proof of the equivalence between the difficulty of deciphering RSA and the difficulty of large number decomposition. So, the major flaw of RSA is that it can't theoretically grasp how its secrecy performance is. In practice, RSA has some drawbacks:

    1. It is troublesome to generate the key, which is limited by the technology of the prime number, so it is difficult to do it once.
    2. The packet length is too large, in order to ensure security, n at least more than bits, so that the cost of the operation is very high, especially the slow speed.
    3. The basic idea of the algorithm:

      1. Generation of public and private keys:

      (1) Random selection of two large prime numbers p and q, construction n = p*q;

      (2) Calculate Euler function φ (N) = (p-1) * (q-1);

      (3) Randomly select E to make gcd (E,φ (n)) = 1, i.e. e and φ (n);

      (4) Calculate d, make e*d≡1 (modφ (N)), that is, D is the multiplication inverse of E.

      At this point, the public key is (e, n), the private key is (d, N), the public key is public, and the private key is stored.

      2. Encrypt information:

      (1) The information to be encrypted (plaintext) is M,m < n; (because to do modulo operations, if M is greater than N, then the subsequent operation will not be established, so when the information is larger than n, it should be chunked encrypted)

      (2) Ciphertext c = Me MoD N

      (3) Decrypt CD mod n = (Me) d mod n = md*e mod n;

      To understand why it can be decrypted? To use Euler's theorem (which is actually the generalization of the Fermat theorem) aφ (n) ≡1 (mod n), and then promotion: Aφ (n) *k≡1 (mod n), get: Aφ (n) *k+1≡a (mod n)

      Notice the e*d≡1 modφ (n), which is: E*d = 1 + k*φ (n).

      So, md*e mod n = M1 + k*φ (n) mod n = M

      Simply put, someone else uses my public key to encrypt the message and then I decrypt it with the private key.

      3. Digital signature:

      (1) Ciphertext c = Md MoD N

      (2) Decrypt M = Ce mod n = (Md) e mod n = md*e mod n = m; (Same principle)

      In a nutshell, I encrypt my signature with my own key, and someone else decrypts it with my public key to see that it's my signature. Note that this is not privacy, that is, anyone can decrypt this signature.

      The security of the algorithm: it is difficult to decompose P and Q based on large integer n, to construct φ (n), or to construct φ (n) directly from N.

      The implementation of the algorithm:

      1. Quick power to take the mold; http://www.cnblogs.com/7hat/p/3398394.html

      2. primality test; http://www.cnblogs.com/7hat/p/3400831.html

      3. Expand Euclid to seek multiplication inverse and greatest common divisor; http://www.cnblogs.com/7hat/p/3406494.html

      Implementation code:

      Import randomdef fastexpmod (b, E, m): "" "e = e0* (2^0) + e1* (2^1) + e2* (2^2) + ... + en * (2^n) b^e = b^ (e0* (2^0) + e1* (2^1) + e2* (2^2) + ... + en * (2^n ) = b^ (e0* (2^0)) * b^ (e1* (2^1)) * b^ (e2* (2^2)) * ... * b^ (en* (2^n)) b^e mod m = ((b^ (e0* (2^0)) mod m) * (b^ (E1 * (2^1)) mod m) * (b^ (e2* (2^2)) mod m) * ... * (b^ (en* (2^n)) mod m) mod m"""result= 1 whileE! = 0:if(e&1) = = 1:#ei = 1, then Mulresult = (Result * b)%m e>>= 1#B, B^2, b^4, B^8, ..., b^ (2^n)b = (b*b)%mreturnresultdef primetest (n):Q= N-1k= 0#Find K, q, satisfied 2^k * q = n-1     whileQ% 2 = = 0:k+ = 1; Q/= 2a= Random.randint (2, N-2); #If a^q mod n= 1, n Maybe is a prime number    ifFastexpmod (A, q, n) = = 1:return"Inconclusive"#If there exists J satisfy a ^ ((2 ^ j) * Q) mod n = = n-1, n Maybe is a prime number     forJ inRange(0, K):ifFastexpmod (A, (2**j) *q, n) = = N-1:return"Inconclusive"#A is not a prime number    return"Composite"def findprime (halfkeylength): while True:#Select a random number nn = random.randint (0, 1<<halfkeylength)ifN% 2! = 0:found=True            #If n satisfy primetest times, then N should is a prime number             forI inRange(0, 10):ifPrimetest (n) = = "Composite":found=False                     Break            ifFoundreturnndef EXTENDEDGCD (a, b):#a*xi + b*yi = ri    ifb = = 0:return(1, 0,a)#a*x1 + b*y1 = aX1 = 1Y1= 0#a*x2 + b*y2 = bx2 = 0y2= 1 whileB! = 0:Q= A/b#ri = r (i-2)% r (i-1)r = a%B a=b b=R#XI = x (i-2)-q*x (i-1)x = x1-q*X2 X1=X2 x2=x#Yi = y (i-2)-Q*y (i-1)y = y1-q*y2 y1=y2 y2=yreturn(x1, Y1,a) def selecte (FN, halfkeylength): while True:#e and FN are relatively primeE = Random.randint (0, 1<<halfkeylength) (x, y, R) = EXTENDEDGCD (E,fn)ifr = = 1:returnedef ComputeD (FN, e):(x, y, R) = EXTENDEDGCD (FN,e)#y maybe < 0, so convert it    ifY < 0:returnfn +yreturnydef keygeneration (keylength):#generate public key and private keyp = findprime (KEYLENGTH/2) Q= Findprime (KEYLENGTH/2) n= P *q fn= (p-1) * (q-1) e= Selecte (FN, KEYLENGTH/2) d= ComputeD (FN,e)return(N, E,d) def encryption (M, E, N):#RSA C = m^e mod n    returnFastexpmod (M, E,N) def decryption (C, D, N):#RSA M = c^d mod n    returnFastexpmod (C, D,N)#Unit Testing(N, E, D) = Keygeneration (1024)#AES keylength =X = Random.randint (0, 1<<256) C= Encryption (X, E,N) M= Decryption (C, D,N)Print"PlainText:",XPrint"Encryption of plaintext:",CPrint"Decryption of ciphertext:",MPrint"The algorithm is correct:", X = =Mpython

Easily learn the principles of RSA encryption algorithms

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.