Golang Implementing RSA Encryption Decryption (with PHP included)

Source: Internet
Author: User
Tags begin rsa private key openssl rsa asymmetric encryption
This is a creation in Article, where the information may have evolved or changed.

Security is always important, and every language is implemented for general-purpose cryptographic algorithms. A while ago, with go implementation of RSA and DES Encryption and decryption, in this share. (for RSA and DES encryption algorithms themselves, please refer to the relevant information)

In PHP, many functions are often solved by a function, but not in go. This article will use PHP encryption, go decryption, go encryption, PHP decryption to learn the RSA and DES-related APIs of Go.

This paper discusses the encryption and decryption of go RSA. All operations are done under Linux.

I. Summary

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

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

1) Create the private key:

openssl genrsa -out private.pem 1024 //密钥长度,1024觉得不够安全的话可以用2048,但是代价也相应增大

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 the ENCODING/PEM package and the crypto/x509 package. How to produce, you can see the "Go Encryption and decryption RSA Chapter: Generate RSA Key."

Encryption and decryption of this piece, involves a lot of standards, personal advice when necessary 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 description of the package: Implementing RSA cryptography, based on the PKCS#1 specification.

For what is pkcs#1, you can consult the relevant information. PKCS (Public Key Cryptography Standard), and # # is the RSA standard. 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 decrypted functions.

EncryptOAEP和DecryptOAEPEncryptPKCS1v15和DecryptPKCS1v15

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

It can be seen that when interacting with other languages, you need to determine which scenario to use.

The PublicKey and Privatekey two types represent public and private keys, respectively, about how 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. Parse key to get publickey and Privatekey examples
This process, I also spent a lot of time (mainly for various kinds of encryption of various things do not know): How to resolve the key file of OpenSSL to the public key and private key instance?

In the ENCODING/PEM package, you see the words-–begin type-–, which is exactly the form of the key generated by OpenSSL, try it.

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

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

This gives an instance of the block (pointer).

Analysis to see crypto/x509. Why is it x509? This involves a bunch of concepts. Regardless of these, I also look at encoding and crypto these two packages of the child package groped 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 is typically found in PEM blocks with "BEGIN public KEY". This is the analytic publickey. In addition, here is the PEM, you can encoding/pem on the above. (Pkix is what, check here)

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

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

The return is RSA. Privatekey.

3, decryption and decryption implementation
Through the above introduction, the decryption and decryption of the go RSA is not difficult to implement. 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 that OpenSSL generates, I generate the following:

Public and private keys can be read from a file

var privatekey = []byte ('-----BEGIN RSA PRIVATE KEY-----miicxqibaakbgqdzsfv1qscqydy4vy+ p4e3catmvppxqcrvrf1cb4drkv0hau24y7m5qytt52kr539rdbkkdlam6s20lwy7+5c0dgacdwywd/7pecelyeipzjl07vro7ate8bfjya+ wltgk9+xnuihiumukulw4kdx21+1nlauej6pew+dakmjwf6qidaqabaogbajlnxentqj6ofcl9fmr2jlmjjtmrtqt9inqee7m3m7blhec+ mcjohmnvbjamzpthdordxiz6ocuof6z2+dl35lntgfh5j7s34up2bwzf1iyyqfyscnexgnhkt1g1xkqthmtc2gwwtheg+ 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. Examples of Use

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

Third, cross-language plus decryption

Language inside normal, but also to see whether and other languages are consistent, namely: other language encryption, go language is correctly decrypted; Go language encryption, other languages correctly decrypted

1, PHP RSA Plus decryption
Here, I chose PHP, using the OpenSSL extension. PHP encryption and decryption 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
$key [, int $padding = openssl_pkcs1_padding]) bool
Openssl_private_decrypt (String $data, String & $decrypted, mixed
$key [, int $padding = openssl_pkcs1_padding])

The last parameter is the encryption scheme (completion method). Because PKCS1 is used in go instead of OAEP, the default value is used.

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;}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 ();
This is also used in PHP and decryption Git@github.com/mrkt

2. Go and PHP work together
One thing to note here is that since the encryption is a byte stream, the direct output view will be garbled, so in order to facilitate the language directly to decrypt, the encrypted data is Base64 encoded here.

3. Use
In the example, both PHP and go versions support the-d parameter to pass in a cryptographically good string, decrypt it, and, when not passed, output a cryptographically good and base64 encoded string that can be used for decryption in other languages.

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.