go-加解密

使用起来比C++方便多了

random

rand.Seed(time.Now().Unix())
fmt.Println(rand.Int()) // int随机值,返回值为int
ver.nonce = rand.Uint64()
fmt.Println(rand.Float64()) // 64位float随机值,返回值为float64

RSA加解密

import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"errors"
"fmt"
"flag"
"encoding/hex"
)

// 加密
func RsaEncrypt(publicKey []byte, 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)
}

// 解密
func RsaDecrypt(privateKey []byte, ciphertext []byte) ([]byte, error) {
//解码pem格式的私钥------BEGIN RSA PRIVATE KEY----- -----END RSA PRIVATE KEY-----
block, _ := pem.Decode(privateKey)
if block == nil {
return nil, errors.New("private key error!")
}

//打印出私钥类型
//fmt.Println(block.Type)
//fmt.Println(block.Headers)
var key interface{}
var errParsePK error
if block.Type == "RSA PRIVATE KEY" {
//RSA PKCS1
key, errParsePK = x509.ParsePKCS1PrivateKey(block.Bytes)
} else if block.Type == "PRIVATE KEY" {
//pkcs8格式的私钥解析
key, errParsePK = x509.ParsePKCS8PrivateKey(block.Bytes)
}

if errParsePK != nil {
return nil, errParsePK
}
priv := key.(*rsa.PrivateKey)

return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}


func GenRsaKey(bits int) error {
// 生成私钥文件
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
return err
}
derStream := x509.MarshalPKCS1PrivateKey(privateKey)
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: derStream,
}
file, err := os.Create("private.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
// 生成公钥文件
publicKey := &privateKey.PublicKey
derPkix, err := x509.MarshalPKIXPublicKey(publicKey)
if err != nil {
return err
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: derPkix,
}
file, err = os.Create("public.pem")
if err != nil {
return err
}
err = pem.Encode(file, block)
if err != nil {
return err
}
return nil
}


func main() {

plainMsg := flag.String("plainMsg", "", "plain message to encrypt")
encMsg := flag.String("encMsg", "", "ecrypted message to decrypt")
isEnc := flag.Bool("isEnc", false, "1 is encrypt, 0 is decrypt")
flag.Parse()

if *plainMsg == "" && *encMsg == "" {
fmt.Println("Error@!@: no param")
return
}

if *isEnc {
encData, err := RsaEncrypt([]byte(pub), []byte(*plainMsg))
if err != nil {
fmt.Println("Error@!@")
fmt.Println(err.Error())
}
fmt.Println(hex.EncodeToString(encData))
} else {
bData, err := hex.DecodeString(*encMsg)
if err != nil {
fmt.Println("Error@!@")
fmt.Println(err.Error())
return
}
origData, err := RsaDecrypt([]byte(priv), bData)
if err != nil {
fmt.Println("Error@!@")
fmt.Println(err.Error())
return
}
fmt.Println(string(origData))
}
}