# Golang Encryption decryption RSA (with PHP) _golang

Source: Internet
Author: User

A brief history of RSA encryption algorithms

RSA was presented in 1977 by Ronald Leevist (Ron rivest), Adi Samor (Adi Shamir) and Lennard Adman (Leonard Adleman). All three of them were working at MIT. RSA is the beginning of their three-person surname together with the letter of the composition.

The principle of RSA encryption algorithm

Learning algorithm friends know that the computer algorithm is in fact mathematical operations. Therefore, before we explain the RSA encryption algorithm, it is necessary to understand some of the necessary mathematical knowledge. Let's start with the math knowledge.

Essential Mathematical Knowledge

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

Prime

Primes are also called prime numbers, which are not divisible by other natural numbers except for 1 and the integer itself, in a natural number greater than 1. This concept, we have learned in junior high school, and even in primary school, there is no longer too much explanation.

Inma

Baidu Encyclopedia on the explanation is: the public factor is only 1 of the two number, called Inma. Wikipedia's explanation is: coprime, also known as the mutual element. If the maximum common factor of n integers is 1, then the n integers are called coprime.

The common methods of Inma judgment are as follows:

1, two different prime numbers must be Inma. For example, 2 and 7, 13 and 19.

2, a prime number, and the other is not a multiple of it, these two numbers are Inma. For example, 3 and 10, 5 and 26.

3, adjacent to the two natural number is Inma. such as 15 and 16.

4, adjacent to the two odd is Inma. such as 49 and 51.

5, the larger number of the two number of prime numbers is Inma. such as 97 and 88.

6, decimal is prime, large number is not a multiple of the decimal number of two is Inma. For example 7 and 16.

7, 2 and any odd number are Inma. For example 2 and 87.

8, 1 is not a prime number and is not a composite, it and any one of the natural numbers are Inma. such as 1 and 9908.

9. The Division of Euclidean method.

Exponential operation

The exponential operation is also called the Power calculation, and the result is called exponentiation. NM refers to n squared m times. Think of NM as the result of a power, called "M-exponentiation of N" or "m-th-square of n". where n is called "base" and M is called "exponent".

Modulus operation

The modulo operation is the remainder operation. "Modulo" is a "Mod" transliteration. A concept closely related to modulo operation is "congruence". Mathematically, when two integers are divided by the same positive integer, if the same remainder is obtained, then two integers are the same.

Two integer a,b, if they are equal to the remainder of the positive integer m, then the A,b is said to be the same as the modulus m, which `a ≡ b (mod m)；` reads: A with more than B modulus m, or, A and b about modulo m congruence. For example: 26≡14 (mod 12).

RSA encryption algorithm

The generation of public key and key

Let's say that Alice wants to receive a private message from Bob through an unreliable media. She can generate a public key and a private key in the following ways:

1, randomly choose two large prime numbers p and q,p not equal to Q, calculate N=PQ.

2, according to Euler function, obtain r = (p-1) (q-1)

3, select an integer e less than R, get e about modulo R's modulo inverse element, named D. (modulo inverse element exists, when and only if E and 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 message

Suppose Bob wants to send Alice a message to M, and he knows Alice produces the N and E. He converts m to an integer n that is less than n by using the format originally associated with Alice, such as he can 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 information into several paragraphs and then convert each paragraph to n. Using the following formula, he can encrypt N to c:

`ne ≡ c (mod N)`

Calculating c is not complicated. Bob can pass it to Alice when he calculates C.

Decrypting a message

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

`cd ≡ n (mod N)`

After getting N, she can restore the original information m.

The decoding principle is:

`cd ≡ n e·d(mod N)`

As well as `ed ≡ 1 (mod p-1)` and `ed ≡ 1 (mod q-1)。` by Fermat's little theorem provable (since p and q are prime numbers)

`n e·d ≡ n (mod p)`And`n e·d ≡ n (mod q)`

This shows (because P and q are different prime numbers, so p and Q coprime)

`n e·d ≡ n (mod pq)`

Signature message

RSA can also be used for signing a message. If a wants to send a signed message to B, then she can compute a hash value (message digest) for her messages, then encrypt the hash value with her key (private key) and append the "signature" to the message. This message can only be decrypted with her public key. b When you get this message, you can decrypt the hash value with a public key, and then compare the data to the hash value that he calculated for the message. If the two match, then he can know that the sender has a key and the message has not been tampered with on the propagation path.

RSA Golang Encryption and decryption

In PHP, many functions are often a function of the solution, while the go is not. This article will use PHP encryption, go decryption, go encryption, PHP decryption to learn about the RSA-related API.

This article discusses go RSA encryption and decryption. All operations are done under Linux.

I. Overview

This is an asymmetric encryption algorithm, generally through public key encryption, private key decryption.

During the encryption and decryption process, the OpenSSL production key is used. Perform the following actions:

1) Create private key:

`OpenSSL genrsa-out PRIVATE.PEM 1024//Key length, 1024 if not safe enough to use 2048, but the cost is correspondingly increased`

2 Create the Public key:

```OpenSSL rsa-in private.pem-pubout-out Public.pem
This produces the key.```

In general, each language also provides an API for generating keys. In go, you can view `encoding/pem` packages and packages `crypto/x509` .

Encryption and decryption of this piece, involves a lot of standards, personal advice when needed to study temporarily.

Second, go RSA encryption and decryption

1, RSA Plus decryption, will certainly go to check `crypto/ras` this bag

`Package RSA implements RSA encryption as specified in Pkcs#1.`

This is the package description: Implementation of RSA encryption technology, based on the PKCS#1 specification.

For what is pkcs#1, you can access the relevant information. A PKCS (public-key password standard), and # # is the standard for RSA. To view: A PKCS Series introduction

From the name of the function in the package, you can see a function with two pairs of encryption decryption.

```ENCRYPTOAEP and DECRYPTOAEP
encryptpkcs1v15 and Decryptpkcs1v15```

This is known as the encryption scheme, which can be viewed in detail, a PKCS #1 v2.1 RSA algorithm Standard

Obviously, when interacting with other languages, you need to determine which scenario to use.

The publickey and privatekey Two types represent the public and private keys, respectively, about how the members of these two types are set, which involves the RSA encryption algorithm, which is obtained by parsing the key generated at the beginning of the article.

2, analytic key to get publickey and Privatekey examples

This process, I also spent a lot of time (mainly on a variety of encryption of all kinds of things are not familiar): How to OpenSSL generated key files to the public and private key instances?

In the `encoding/pem` package, you see the words-–begin type-–, which is just like the form of the key that OpenSSL generates, try it.

In this package, a block represents a PEM-encoded structure, and for the PEM, please refer to the relevant information. We want to parse the key, of course, with the Decode method:

`Func Decode (data []byte) (P *block, rest []byte)`

This results in an instance of the block (pointer).

Analytic view `crypto/x509` . Why is it x509? This involves a bunch of concepts. Regardless of these, I also look at encoding and crypto These two bags of the bag groping out.

In the X509 package, there is a function:

`Func Parsepkixpublickey (Derbytes []byte) (Pub interface{}, err Error)`

From the description of the function: Parsepkixpublickey parses a DER encoded public key. These values are are typically found in the PEM blocks with ' BEGIN public KEY '. It can be seen that this is the analytic publickey. In addition, here is a PEM, you can encoding/pem the above.

And to parse the private key, there are several methods, from the above introduction, we know that RSA is pkcs#1, just have a way:

`Func Parsepkcs1privatekey (der []byte) (Key *rsa. Privatekey, err Error)`

The return is RSA. Privatekey.

3, decryption and decryption implementation

Through the above introduction, go in RSA decryption and decryption implementation is not difficult. The code is as follows:

Encryption

```Func Rsaencrypt (Origdata []byte) ([]byte, error) {block
, _: = Pem. Decode (PublicKey)
if block = = Nil {return
nil, errors. New ("Public key Error")
}
pubinterface, err: = X509. Parsepkixpublickey (block. Bytes)
If err!= nil {return
nil, err
}
RSA. Encryptpkcs1v15 (Rand. Reader, Pub, Origdata)
}```

Decrypt

```Func rsadecrypt (Ciphertext []byte) ([]byte, error) {block
, _: = Pem. Decode (Privatekey)
if block = = Nil {return
nil, errors. New ("Private key error!")
}
Priv, err: = X509. Parsepkcs1privatekey (block. Bytes)
If err!= nil {return
nil, err
} return
RSA. Decryptpkcs1v15 (Rand. Reader, Priv, ciphertext)
}```

wherepublickey and Privatekey are the keys generated by OpenSSL , I generate the following:

Public and private keys can be read from the file

```var privatekey = []byte ('-----BEGIN RSA PRIVATE KEY-----miicxqibaakbgqdzsfv1qscqydy4vy+ P4E3CATMVPPXQCRVRF1CB4DRKV0HAU24Y 7m5qytt52kr539rdbkkdlam6s20lwy7+5c0dgacdwywd/7pecelyeipzjl07vro7 Ate8Bfjya+ Wltgk9+xnuihiumukulw4kdx21+1nlauej6pew+dakmjwf6qidaqab aogbajlnxentqj6ofcl9fmr2jlmjjtmrtqt9inqee7m3m7blhec+ Mcjohmnvbjam ZPTHDORDXIZ6OCUOF6Z2+DL35LNTGFH5J7S34UP2BWZF1IYYQFYSCNEXGNHKT1G1 XKQtHmtc2gWWthEg+ s6ciiyw2igrrp2rke81vyhexprexf0hakea9izb0miysmcb/jemljb0lb3y/ B8XJGJQFFBQT7BMWBVJVZWZVPNMNXI9SWGDGUPXSCUAIROXJZ40 irz2c9eouwjbaopjpvv8sgw4vaseoqljvsq/c/
PIFX6RVZNDGLC8BRG7SGTPPJHG 4g+m3mvgpcx1a/eu1mb+fhij2laz/ptty6scqgaw9nwiwu3drivgcsmm0myh/3x9 Dacwlsjoctiodq1fq9rrede5qfpjnajdjfsijntx1f+l3yceebxtw0ynz2mcqbi8 9kp274is5fkwkufnknukuk4wkouexeo+lpr+
VIHS7K6WQ8NGDD4/MUJOJBR5MKRW Dpwqa3n5tmndqvgv8gmcqqcakgjgwygvo3/milffimbp+m7/y3vcptarldxryqwo  aqjxwc71zgbfdityvdgjm1mtqc8xqek1fxn1vfpy2c6o-----End RSA PRIVATE KEY-----') var publickey = []byte ('-----BEGIN public KEY-----Migfma0gcsqgsib3dqebaquaa4gnaDCBIQKBGQDZSFV1QSCQYDY4VY+P4E3CATMV PPXQCRVRF1CB4DRKV0HAU24Y7M5QYTT52KR539RDBKKDLAM6S20LWY7+5C0DGACD wYWd/ 7PECELYEIPZJL07VRO7ATE8BFJYA+WLTGK9+XNUIHIUMUKULW4KDX21+1NL auej6pew+dakmjwf6qidaqab-----End Public KEY-----')```

4, the use of examples

```Package main

Import (
"FMT"
)

func main () {
data, err: = Rsaencrypt ([]byte ("Git@github.com/mrkt")
If Err!= nil {
panic (err)
}
If Err!= nil {
panic (err)
}
FMT. Println (String (origdata))
}```

This example is `git@github.com/mrkt` decrypted immediately after the encryption is complete

Iii. cross-language encryption and decryption

Language internal normal, but also to see if the same as other languages, namely: Other language encryption, go language should be properly decrypted;

1, PHP RSA encryption and decryption

Here, I choose PHP, using the OpenSSL extension. Add and decrypt PHP is very simple, the following two methods (only consider using public key encryption, private key decryption):

```BOOL Openssl_public_encrypt (String \$data, String & \$crypted, mixed
openssl_private_decrypt (String \$data, String & \$decrypted, mixed

The last parameter is the encryption scheme (complement method). Because the go uses PKCS1 instead of OAEP, you can use the default value.

The PHP code is as follows:

```\$privateKey = '-----BEGIN RSA PRIVATE KEY-----miicxqibaakbgqdzsfv1qscqydy4vy+p4e3catmvppxqcrvrf1cb4drkv0hau24y 7m5qytt52kr539rdbkkdlam6s20lwy7+5c0dgacdwywd/7pecelyeipzjl07vro7 ate8bfjya+wltgk9+xnuihiumukulw4kdx21+
1nlauej6pew+dakmjwf6qidaqab Aogbajlnxentqj6ofcl9fmr2jlmjjtmrtqt9inqee7m3m7blhec+mcjohmnvbjam ZPTHDORDXIZ6OCUOF6Z2+DL35LNTGFH5J7S34UP2BWZF1IYYQFYSCNEXGNHKT1G1 xkqthmtc2gwwtheg+ s6ciiyw2igrrp2rke81vyhexprexf0hakea9izb0miysmcb/jemljb0lb3y/ B8XJGJQFFBQT7BMWBVJVZWZVPNMNXI9SWGDGUPXSCUAIROXJZ40 irz2c9eouwjbaopjpvv8sgw4vaseoqljvsq/c/
PIFX6RVZNDGLC8BRG7SGTPPJHG 4g+m3mvgpcx1a/eu1mb+fhij2laz/ptty6scqgaw9nwiwu3drivgcsmm0myh/3x9 Dacwlsjoctiodq1fq9rrede5qfpjnajdjfsijntx1f+l3yceebxtw0ynz2mcqbi8 9kp274is5fkwkufnknukuk4wkouexeo+lpr+
VIHS7K6WQ8NGDD4/MUJOJBR5MKRW Dpwqa3n5tmndqvgv8gmcqqcakgjgwygvo3/milffimbp+m7/y3vcptarldxryqwo aqjxwc71zgbfdityvdgjm1mtqc8xqek1fxn1vfpy2c6o-----End RSA PRIVATE KEY-----'; \$publicKey = '-----BEGIN public KEY-----Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdzsfv1qscqydy4vy+P4E3CATMV PPXQCRVRF1CB4DRKV0HAU24Y7M5QYTT52KR539RDBKKDLAM6S20LWY7+5C0DGACD wywd/7pecelyeipzjl07vro7ate8bfjya+
WLTGK9+XNUIHIUMUKULW4KDX21+1NL auej6pew+dakmjwf6qidaqab-----End public KEY-----';
function Rsaencrypt (\$data) {global \$publicKey;
Openssl_public_encrypt (\$data, \$crypted, \$publicKey);

return \$crypted;
Openssl_private_decrypt (\$data, \$decrypted, \$privateKey);
return \$decrypted;
function Main () {\$crypted = Rsaencrypt ("Git@github.com/mrk");
\$decrypted = Rsadecrypt (\$crypted); echo "Encrypt and Decrypt:".

\$decrypted; }```

Main ();

This is also used in PHP encryption and decryption`git@github.com/mrkt`

2, go and PHP work together

Here to note that, because the encryption is the byte stream, direct output view will be garbled, therefore, in order to facilitate the language directly to decrypt, here will encrypt the data after the Base64 code.

3. Use

In the example, both PHP and go versions support the-D argument to pass in the encrypted string, decrypt it, and, when not passed, output the encrypted and Base64 encoded string, which can be used in other languages for decryption.

Summarize

The above is to use the go language to achieve the RSA encryption and decryption of the entire content, the article is very in-depth explanation of the RSA encryption and decryption process, to learn the relevant knowledge of friends is helpful. If you have questions, please comment.

Related Keywords:
Related Article

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.