Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use RSA of Golang encryption and decryption

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to use RSA for Golang encryption and decryption. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

A brief History of RSA encryption algorithm

RSA was proposed by Ronald Ron Rivest, Adi Shamir and Leonard Adleman in 1977. All three of them worked at MIT at the time. RSA is made up of the initials of the three surnames.

Principle of RSA encryption algorithm

Friends who have studied algorithms all know that algorithms in computers are actually mathematical operations. Therefore, before we explain the RSA encryption algorithm, it is necessary to know some necessary mathematical knowledge. Let's start with the knowledge of mathematics.

Necessary mathematical knowledge

In RSA encryption algorithm, only some simple mathematical knowledge is used, such as prime number, coprime number, exponential operation, modular operation and so on. Therefore, we also need to understand these concepts.

Prime number

A prime number, also known as a prime number, refers to a number in a natural number greater than 1 that is not divisible by other natural numbers except 1 and the integer itself. We have learned this concept in junior high school or even primary school, so we will not explain it too much here.

Coprime number

The explanation on Baidu encyclopedia is: two numbers with a common factor of only 1 are called coprimes. The explanation on Wikipedia is: mutual prime, also known as mutual prime. If the greatest common divisor of N integers is 1, then N integers are called coprimes.

The common methods for judging coprimes are as follows:

1. Two different prime numbers must be coprimes. For example, 2 and 7, 13 and 19.

2. One prime number and the other is not a multiple of it. These two numbers are mutual primes. For example, 3 and 10, 5 and 26.

3. The two adjacent natural numbers are coprimes. Such as 15 and 16.

4. The two adjacent odd numbers are coprimes. Such as 49 and 51.

5. Two numbers whose larger numbers are prime numbers are coprimes. Such as 97 and 88.

6. Decimals are prime numbers, and two numbers that are not multiples of decimals are coprimes. For example, 7 and 16.

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

8, 1 is neither a prime number nor a composite number, it is a coprime number with any natural number. Such as 1 and 9908.

9. Division by tossing and turning.

Exponential operation

Exponential operation is also called power calculation, and the result is called power. Nm means to multiply n by m times. Think of nm as the result of the power, which is called "the m power of n" or "the m power of n". Where n is called "base number" and m is called "index".

Modular operation

Modular operation is the operation of remainder. "Modular" is the transliteration of "Mod". A concept closely related to modular computing is congruence. Mathematically, when two integers are divided by the same positive integer, if the same remainder is obtained, the two integers are congruent.

If the remainder of the positive integer m divided by two integers is equal, then a ≡ b is called congruence with respect to module m: a ≡ b (mod m); read as: a congruence to b module m, or an and b with respect to module m congruence. For example: 26 ≡ 14 (mod 12).

RSA encryption algorithm

Generation of public key and key

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 which are not equal to Q, and calculate the N=pq.

2. According to the Euler function, r = (pmur1) (qmel1) is obtained.

3. Select an integer e which is less than r, and obtain the modular inverse element of e with respect to module r, which is named d. (modular inverse elements exist if and only if e and r are coprime)

4. Destroy the records of p and Q.

(NMagnee) is the public key, and (NMagned) is the private key. Alice passes her public key (NMague e) to Bob and hides her private key (NMague d).

Encrypted message

Suppose Bob wants to send a message m to Alice, and he knows the N and e generated by Alice. He converts m to an integer n less than N using the format originally agreed with Alice. For example, he can convert each word to the Unicode code of that word, and then concatenate these numbers together to form a number. If his message is very long, he can divide the message into several segments and then convert each paragraph to n. He can encrypt n to c with the following formula:

Ne ≡ c (mod N)

Calculating c is not complicated. After Bob calculates c, it can be passed to Alice.

Decrypt the message

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 principle of decoding is:

Cd ≡ n e d (mod N)

And ed ≡ 1 (mod PMI 1) and ed ≡ 1 (mod Q Mel 1). Can be proved by Fermat's Little Theorem (because p and Q are prime numbers)

N e ·d ≡ n (mod p) and n e ·d ≡ n (mod Q)

This shows that (because p and Q are different prime numbers, p and Q are mutually prime)

N e ·d ≡ n (mod pq)

Signed message

RSA can also be used to sign a message. If A wants to send B a signed message, she can calculate a hash value (Message digest) for her message, then encrypt the hash value with her key (private key) and add the "signature" to the end of the message. The message can only be decrypted with her public key. After getting the message, B can decrypt the hash value with A's public key and then compare the data with the hash value he calculated for the message. If the two match, then he can know that the sender holds the key of An and that the message has not been tampered with in the transmission path.

RSA of Golang encryption and decryption

In PHP, many functions are often solved as a function; those in Go are not. This article will learn the RSA-related API of Go through PHP encryption, Go decryption, Go encryption, PHP decryption.

This paper discusses Go RSA encryption and decryption. All operations are done under linux.

I. Summary

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

During the encryption and decryption process, openssl is used to produce the key. Do the following:

1) create a private key:

Openssl genrsa-out private.pem 1024 / / key length. If 1024 feels insecure, you can use 2048, but the cost will increase accordingly.

2) create a public key:

Openssl rsa-in private.pem-pubout-out public.pem thus produces the key.

In general, various languages also provide API for generating keys. In Go, you can view the encoding/ PEM package and the crypto/x509 package.

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

2. Go RSA encryption and decryption

1. Rsa encryption and decryption, it is necessary to look up the crypto/ras package.

Package rsa implements RSA encryption as specified in PKCS#1.

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

For what is PKCS#1, you can consult the relevant information. PKCS (Public key Cryptography Standard), and # 1 is the standard of RSA. You can view: introduction to the PKCS series

From the name of the function in the package, you can see that there are two pairs of encrypted and decrypted functions.

EncryptOAEP and DecryptOAEPEncryptPKCS1v15 and DecryptPKCS1v15

This is called an encryption scheme, and can be found in PKCS # 1 v2.1 RSA algorithm Standard.

As you can see, when interacting with other languages, you need to decide which solution to use.

PublicKey and PrivateKey represent public key and private key respectively. How to set the members of these two types involves the RSA encryption algorithm. In this article, the examples of these two types are obtained by parsing the key generated at the beginning of the article.

2. Parse the key to get the examples of PublicKey and PrivateKey

I also spent a lot of time in this process (mainly unfamiliar with all kinds of encryption): how to parse the key file generated by openssl to public and private key instances?

In the encoding/pem package, you see the words-- BEGIN Type--, which is similar to the key generated by openssl, so give it a try.

In this package, a block represents the structure of the PEM code. For more information about PEM, please refer to the relevant information. We want to parse the key, using the Decode method, of course:

Func Decode (data [] byte) (p * Block, rest [] byte)

This gives you an instance of Block (pointer).

Parsing to see crypto/x509. Why x509? This involves a lot of concepts. Regardless of these, I also fumbled out by looking at the subpackages of encoding and crypto.

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 typically found in PEM blocks with "BEGIN PUBLIC KEY". So this is the parsing of PublicKey. In addition, when it comes to PEM, you can use the encoding/pem above.

There are several ways to parse a private key. From the above introduction, we know that RSA is PKCS#1, and there happens to be one way:

Func ParsePKCS1PrivateKey (der [] byte) (key * rsa.PrivateKey, err error)

What is returned is rsa.PrivateKey.

3. Decryption implementation

Through the above introduction, the decryption implementation of RSA in Go 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} pub: = pubInterface. (* rsa.PublicKey) return 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)}

Where publicKey and privateKey are the keys generated by openssl, and I generate the following:

/ / Public and private keys can be read from the file

Var privateKey = [] byte (`- BEGIN RSA PRIVATE KEY-MIICXQIBAAKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQABAoGBAJlNxenTQj6OfCl9FMR2jlMJjtMrtQT9InQEE7m3m7bLHeC+MCJOhmNVBjaMZpthDORdxIZ6oCuOf6Z2+Dl35lntGFh6J7S34UP2BWzF1IyyQfySCNexGNHKT1G1XKQtHmtc2gWWthEg+S6ciIyw2IGrrP2Rke81vYHExPrexf0hAkEA9Izb0MiYsMCB/jemLJB0Lb3Y/B8xjGjQFFBQT7bmwBVjvZWZVpnMnXi9sWGdgUpxsCuAIROXjZ40IRZ2C9EouwJBAOPjPvV8Sgw4vaseOqlJvSq/C/pIFx6RVznDGlc8bRg7SgTPpjHG4G+M3mVgpCX1a/EU1mB+fhiJ2LAZ/pTtY6sCQGaW9NwIWu3DRIVGCSMm0mYh/3X9DAcwLSJoctiODQ1Fq9rreDE5QfpJnaJdJfsIJNtX1F+L3YceeBXtW0Ynz2MCQBI89KP274Is5FkWkUFNKnuKUK4WKOuEXEO+LpR+vIhs7k6WQ8nGDd4/mujoJBr5mkrwDPwqA3N5TMNDQVGv8gMCQQCaKGJgWYgvo3/milFfImbp+m7/Y3vCptarldXrYQWOAQjxwc71ZGBFDITYvdgJM1MTqc8xQek1FXn1vfpy2c6O-END RSA PRIVATE KEY-`) var publicKey = [] byte (`- BEGIN PUBLIC KEY-MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQAB-END PUBLIC KEY-`)

4. Use examples

Package main import ("fmt") func main () {data, err: = RsaEncrypt ([] byte ("git@github.com/mrkt")) if err! = nil {panic (err)} origData, err: = RsaDecrypt (data) if err! = nil {panic (err)} fmt.Println (string (origData)}

This example is decrypted immediately after encrypting git@github.com/mrkt.

III. Cross-language encryption and decryption

The internal language is normal, but we have to see if it is consistent with other languages, that is, other languages encrypt, Go must decrypt correctly; Go encrypts, other languages decrypt correctly.

1. PHP RSA encryption and decryption

Here, I choose PHP, using the openssl extension. Encryption and decryption in PHP is very simple. Here, only public key encryption and private key decryption are considered:

Boolopenssl_ public_encrypt (string $data, string & $crypted, mixed$key [, int $padding = OPENSSL_PKCS1_PADDING]) boolopenssl_private_decrypt (string $data, string & $decrypted, mixed$key [, int $padding = OPENSSL_PKCS1_PADDING])

The last parameter is the encryption scheme (complement). Because PKCS1 is used in Go instead of OAEP, you can use the default value.

The PHP code is as follows:

$privateKey ='- BEGIN RSA PRIVATE KEY-MIICXQIBAAKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQABAoGBAJlNxenTQj6OfCl9FMR2jlMJjtMrtQT9InQEE7m3m7bLHeC+MCJOhmNVBjaMZpthDORdxIZ6oCuOf6Z2+Dl35lntGFh6J7S34UP2BWzF1IyyQfySCNexGNHKT1G1XKQtHmtc2gWWthEg+S6ciIyw2IGrrP2Rke81vYHExPrexf0hAkEA9Izb0MiYsMCB/jemLJB0Lb3Y/B8xjGjQFFBQT7bmwBVjvZWZVpnMnXi9sWGdgUpxsCuAIROXjZ40IRZ2C9EouwJBAOPjPvV8Sgw4vaseOqlJvSq/C/pIFx6RVznDGlc8bRg7SgTPpjHG4G+M3mVgpCX1a/EU1mB+fhiJ2LAZ/pTtY6sCQGaW9NwIWu3DRIVGCSMm0mYh/3X9DAcwLSJoctiODQ1Fq9rreDE5QfpJnaJdJfsIJNtX1F+L3YceeBXtW0Ynz2MCQBI89KP274Is5FkWkUFNKnuKUK4WKOuEXEO+LpR+vIhs7k6WQ8nGDd4/mujoJBr5mkrwDPwqA3N5TMNDQVGv8gMCQQCaKGJgWYgvo3/milFfImbp+m7/Y3vCptarldXrYQWOAQjxwc71ZGBFDITYvdgJM1MTqc8xQek1FXn1vfpy2c6O-END RSA PRIVATE KEY-'; $publicKey ='- BEGIN PUBLIC KEY-MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDZsfv1qscqYdy4vY+P4e3cAtmvppXQcRvrF1cB4drkv0haU24Y7m5qYtT52Kr539RdbKKdLAM6s20lWy7+5C0DgacdwYWd/7PeCELyEipZJL07Vro7Ate8Bfjya+wltGK9+XNUIHiumUKULW4KDx21+1NLAUeJ6PeW+DAkmJWF6QIDAQAB-END PUBLIC KEY-';function rsaEncrypt ($data) {global $publicKey; openssl_public_encrypt ($data, $crypted, $publicKey); return $crypted;} function rsaDecrypt ($data) {global $privateKey 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 ()

PHP is also used here to encrypt and decrypt git@github.com/mrkt.

2. Go and PHP work together

One thing to note here is that since the encrypted byte stream will directly output and view the garbled code, therefore, in order to facilitate the language to encrypt and decrypt directly, the encrypted data is encoded by base64.

3. Use

In the example, both php and Go versions support passing an encrypted string in the-d parameter to decrypt it. If it is not passed, the encrypted and base64-encoded string will be output, which can be used for decryption in other languages.

This is the end of this article on "how to use RSA for Golang encryption and decryption". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it out for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report