package util import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "io" "log" "os" ) var publicKey []byte var privateKey []byte func init() { publicFile, err := os.Open("rsa_public.pem") if err != nil { log.Fatalf("can not open publicFile, err: %+v", err) } publicBuf := bytes.Buffer{} if _, err := io.Copy(&publicBuf, publicFile); err != nil { log.Fatalf("can not read publicFile, err: %+v", err) } publicKey = publicBuf.Bytes() privateFile, err := os.Open("rsa_private.pem") if err != nil { log.Fatalf("can not open privateFile, err: %+v", err) } privateBuf := bytes.Buffer{} if _, err := io.Copy(&privateBuf, privateFile); err != nil { log.Fatalf("can not read privateFile, err: %+v", err) } privateKey = privateBuf.Bytes() } 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 { log.Printf("can not public") return nil, err } pub := pubInterface.(*rsa.PublicKey) return rsa.EncryptPKCS1v15(rand.Reader, pub, origData) } 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) }