// Copyright 2019 autocareai.com. All rights reserved. // Use of this source code is governed by autocareai.com. package config import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/pem" "fmt" "net/url" ) func Base64Encode(src []byte) []byte { return []byte(base64.StdEncoding.EncodeToString(src)) } func Base64Decode(src []byte) ([]byte, error) { return base64.StdEncoding.DecodeString(string(src)) } func split(buf []byte, lim int) [][]byte { var chunk []byte chunks := make([][]byte, 0, len(buf)/lim+1) for len(buf) >= lim { chunk, buf = buf[:lim], buf[lim:] chunks = append(chunks, chunk) } if len(buf) > 0 { chunks = append(chunks, buf[:len(buf)]) } return chunks } func RasDescrpto(data, privateKey []byte) ([]byte, error) { var err error var block *pem.Block block, _ = pem.Decode(privateKey) if block == nil { return nil, fmt.Errorf("私钥错误") } prkI, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("解析私钥错误") } pri := prkI.(*rsa.PrivateKey) partLen := pri.N.BitLen() / 8 raw, err := Base64Decode(data) chunks := split([]byte(raw), partLen) buffer := bytes.NewBufferString("") for _, chunk := range chunks { decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, pri, chunk) if err != nil { return nil, err } buffer.Write(decrypted) } r, err := url.QueryUnescape(buffer.String()) if err != nil { return nil, err } return []byte(r), err } func Base64RsaEncrypt(data, publicKey []byte) ([]byte, error) { var err error var block *pem.Block block, _ = pem.Decode(publicKey) if block == nil { return nil, fmt.Errorf("公钥错误") } prkI, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, fmt.Errorf("解析公钥错误") } pub := prkI.(*rsa.PublicKey) partLen := pub.N.BitLen()/8 - 11 chunks := split(data, partLen) buffer := bytes.NewBufferString("") for _, chunk := range chunks { bytes, err := rsa.EncryptPKCS1v15(rand.Reader, pub, chunk) if err != nil { return nil, err } buffer.Write(bytes) } cipherText := Base64Encode(buffer.Bytes()) return cipherText, nil }