golang实现RSA加密解密

非对称加密示意图:

非对称加密算法流程图

在此可以看到,非对称加密是通过两个密钥(公钥-私钥)来实现对数据的加密和解密的。公钥用于加密,私钥用于解密。

RSA加密流程

RSA公钥和私钥生成:

package main

import (

"crypto/rsa"

"crypto/rand"

"fmt"

"crypto/x509"

"encoding/pem"

"os"

"flag"

)

func RSAKeyGen(bits int) error {

privatekey, err := rsa.GenerateKey(rand.Reader, bits)

if err != nil {

fmt.Println("私钥文件生成失败")

}

fmt.Println("私钥为:", privatekey)

derStream := x509.MarshalPKCS1PrivateKey(privatekey)

block := &pem.Block{

Type:"RSA Private key",

Bytes: derStream,

}

privatefile, err := os.Create("myprivatekey.pem")

defer privatefile.Close()

err = pem.Encode(privatefile, block)

if err != nil {

fmt.Println(err.Error())

return err

}

publickey := &privatekey.PublicKey;

fmt.Println("公钥为:", publickey)

derpkix, err := x509.MarshalPKIXPublicKey(publickey)

block = &pem.Block{

Type:"RSA Public key",

Bytes: derpkix,

}

if err != nil {

fmt.Println(err.Error())

return err

}

publickfile, err := os.Create("mypublic.pem")

defer publickfile.Close()

err = pem.Encode(publickfile, block)

if err != nil {

fmt.Println(err.Error())

return err

}

return nil

}

func main() {

var bits int

flag.IntVar(&bits,"b",1024,"密码默认长度1024")

err := RSAKeyGen(bits)

if err != nil{

fmt.Println("RSA密码文件生成失败")

}

fmt.Println("RSA密码生成成功")

}

利用公钥和私钥进行加密解密:

package main

import (

"encoding/pem"

"errors"

"crypto/x509"

"crypto/rsa"

"crypto/rand"

"fmt"

"encoding/base64"

"os"

)

var publickey = FileLoad("mypublic.pem")

var privatekey = FileLoad("myprivatekey.pem")

func RSAEncrypt(orgidata []byte) ([]byte, error) {

block, _ := pem.Decode(publickey)

if block == nil {

return nil, errors.New("public key is bad")

}

pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)

if err != nil {

return nil, err

}

pub := pubInterface.(*rsa.PublicKey)

return rsa.EncryptPKCS1v15(rand.Reader, pub, orgidata)//加密

}

func RSADecrypt(cipertext []byte) ([]byte, error) {

block, _ := pem.Decode(privatekey)

if block == nil {

return nil, errors.New("public key is bad")

}

priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)

if err != nil {

return nil, err

}

return rsa.DecryptPKCS1v15(rand.Reader, priv, cipertext)

}

func FileLoad(filepath string) ([]byte) {

privatefile,err := os.Open(filepath)

defer privatefile.Close()

if err!=nil{

return nil

}

privateKey := make([]byte,2048)

num,err := privatefile.Read(privateKey)

return privateKey[:num]

}

func main() {

var data []byte

var err error

data, err = RSAEncrypt([]byte("QQ77025077"))

if err != nil {

fmt.Println("错误", err)

}

fmt.Println("加密:", base64.StdEncoding.EncodeToString(data))

origData, err := RSADecrypt(data)//解密

  if err != nil {

fmt.Println("错误", err)

}

fmt.Println("解密:", string(origData))

//pk := FileLoad("myprivatekey.pem")

//fmt.Println(string(pk))

}

你可能感兴趣的:(golang实现RSA加密解密)