Use the Go language to impersonate a client to send get and post requests to the server

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

Package Main


Import (

//"bytes"

"FMT"

"Io/ioutil"

"Net/http"

"Net/url"

)


var client = &http. client{}


Func Get () {

//Send a GET request to the server

Request, _: = http. Newrequest ("GET", "http://192.168.1.35:9091/?publicKey=-----begin+public+key-----%0d%0 amigfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdzsfv1qscqydy4vy%2bp4e3catmv%0d%0 appxqcrvrf1cb4drkv0hau24y7m5qytt52kr539rdbkkdlam6s20lwy7%2b5c0dgacd%0d%0awywd%2f7pecelyeipzjl07vro7ate8bfjya% 2BWLTGK9%2BXNUIHIUMUKULW4KDX21%2B1NL%0D%0AAUEJ6PEW%2BDAKMJWF6QIDAQAB%0D%0A-----End+public+key-----& Privatekey=&info=sad&message= ", nil)

Response, _: = client. Do (Request)


defer response. Body.close ()


If response. StatusCode = = 200 {

str, _: = Ioutil. ReadAll (response. Body)

Bodystr: = string (str)

FMT. Println (BODYSTR)

}

}


Func Post () {

//post Request

postvalues: = URL. values{}

postvalues.add ("PublicKey", '-----BEGIN public KEY-----

Migfma0gcsqgsib3dqebaquaa4gnadcbiqkbgqdzsfv1qscqydy4vy+p4e3catmv

Ppxqcrvrf1cb4drkv0hau24y7m5qytt52kr539rdbkkdlam6s20lwy7+5c0dgacd

Wywd/7pecelyeipzjl07vro7ate8bfjya+wltgk9+xnuihiumukulw4kdx21+1nl

Auej6pew+dakmjwf6qidaqab

-----END Public KEY-----')

postvalues.add ("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-----')

postvalues.add ("info", "Hello")

postvalues.add ("message", "")


resp, err: = client. Postform ("http://192.168.1.35:9091", Postvalues)


If Err! = Nil {

FMT. Println (Err. Error ())

}

Defer resp. Body.close ()

If resp. StatusCode = = 200 {

Body, _: = Ioutil. ReadAll (resp. Body)

FMT. Println (String (body))

}

}


Func Main () {

Get ()

Post ()

}

Index.go

Package controllers


Import (

"Crypto/rand"

"Crypto/rsa"

"crypto/x509"

"Encoding/base64"

"Encoding/pem"

"Errors"

"FMT"

"Net/http"

)


Process data encryption, decryption, or separate data or decryption


Encode with Base64

Func base64encode (src []byte) []byte {

return []byte (base64. Stdencoding.encodetostring (SRC))

}


Decoding with the Base64

Func base64decode (src []byte) ([]byte, error) {

return base64. Stdencoding.decodestring (String (src))

}


Func toString (value []string) string {

Length: = Len (value)

var sum string

for I: = 0; i < length; i++ {

sum = sum + value[i]

}

return sum

}


var PublicKey []byte

var Privatekey []byte


Get the original text in the form, clear text is the result of decryption

var cont []string


Get the original string

var info string


Get ciphertext information, cipher is the result of encryption

var Meg []string


Get ciphertext string

var message string


Func Get (w http. Responsewriter, R *http. Request) {

//Get information on the form

Display (R)

//Call the deal method

Deal (info, message, PublicKey, Privatekey, W, R)

}


Func Post (w http. Responsewriter, R *http. Request) {

//Get client's data

Display (R)

//Call the deal method

Deal (info, message, PublicKey, Privatekey, W, R)

}


Get the information on the form

Func Display (R *http. Request) {

R.parseform ()//parse parameter, default is not resolved, if not write this sentence, you can not get the requested form above the data


//Get private key

var pri []string = r.form["Privatekey"]


//Get a slice of the private key byte type

Privatekey = []byte (toString (PRI))

//FMT. fprintf (W, "private key: \ n" +string (privatekey) + "\ n")


//Get the public key

var pub []string = r.form["PublicKey"]


//Get a slice of the public key byte type

PublicKey = []byte (toString (pub))


//Get source information in the form, clear text is the result of decryption

cont = r.form["Info"]


//Get source string

info = toString (cont)


//Get ciphertext information, cipher text is the result of encryption

meg = r.form["message"]


//Get ciphertext string

message = toString (MEG)


}


What is the need to handle clients?

Func Deal (info, message string, PublicKey, Privatekey []byte, W http. Responsewriter, R *http. Request) {

//decryption: ciphertext, private key

//encryption: Clear text, common key


//Let me add the decryption

If info! = "" && string (publickey)! = "" && string (privatekey)! = "" && message = = "" {

data, err: = Rsaencrypt ([]byte (info))

If Err! = Nil {

Panic (err)

}

//FMT. fprintf (W, "Public key is: \ n" +string (publickey) + "\ n")

Debyte: = Base64Encode (data)

//FMT. fprintf (W, "ciphertext: \ n" +string (debyte) + "\ n")


origdata, err: = Rsadecrypt (data)

If Err! = Nil {

Panic (err)

}

//FMT. fprintf (W, "private key: \ n" +string (privatekey) + "\ n")

FMT. fprintf (W, "Clear text: \n%s", String (origdata) + "\ n")

FMT. fprintf (W, "ciphertext: \ n" +string (debyte) + "\ n")


//Let me decrypt

} else if message! = "" && string (privatekey)! = "" && info = = "" && string (publickey) = = "" {

//Use private key to parse ciphertext to get plaintext

Conte, err: = Base64decode ([]byte (Message))

If Err! = Nil {

Panic (err)

}

conte, err = Rsadecrypt (conte)

If Err! = Nil {

Panic (err)

}

info = string (conte)


FMT. fprintf (W, "Clear text: \n%s", info+ "\ n")

FMT. fprintf (W, "ciphertext: \ n" +message+ "\ n")

} else if string (publickey)! = "" && info! = "" && message = = "" && string (privatekey) = = "" {//Let me encrypt


data, err: = Rsaencrypt ([]byte (info))

If Err! = Nil {

Panic (err)

}

message = string (Base64Encode (data))


//FMT. Println ("Clear text:", content)


FMT. fprintf (W, "Clear text: \n%s", info+ "\ n")

FMT. fprintf (W, "ciphertext: \ n" +message+ "\ n")

} else {

FMT. fprintf (W, "Please re-enter, do not support this type of input method")

return

}

}


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)

}

Httpweb.go

Package Main


Import (

//"FMT"

"Log"

"Net/http"

"Testrsa2/controllers"

)


Set up service-side processing requests


Determine whether a request is a get or a POST request

Func indexhandle (w http. Responsewriter, R *http. Request) {

m: = R.method

if M = = "GET" {

controllers. Get (W, R)

} else {

controllers. Post (W, R)

}

}


Func Main () {

http. Handlefunc ("/", Indexhandle)//Set Access routing


Err: = http. Listenandserve (": 9091", nil)//set the listening port

If Err! = Nil {

Log. Fatal ("Listenandserve:", err)

}

}


Related Article

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.