From 5c33785e64a443e411d8d4924325b46d09147e11 Mon Sep 17 00:00:00 2001 From: qydysky Date: Thu, 4 Mar 2021 15:46:36 +0800 Subject: [PATCH] =?utf8?q?=E5=85=AC=E7=A7=81=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit --- crypto/Crypto.go | 77 +++++++++++++++++++++++++++++++++++++++++++ crypto/Crypto_test.go | 22 +++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 crypto/Crypto.go create mode 100644 crypto/Crypto_test.go diff --git a/crypto/Crypto.go b/crypto/Crypto.go new file mode 100644 index 0000000..36f715a --- /dev/null +++ b/crypto/Crypto.go @@ -0,0 +1,77 @@ +package main + +import ( + "os" + "io/ioutil" + "errors" + "crypto/rand" + "crypto/sha256" + "crypto/rsa" + "crypto/x509" + "encoding/pem" +) + +type Crypto struct { + pubKey *rsa.PublicKey + priKey *rsa.PrivateKey +} + +func FileLoad(path string) (data []byte, err error) { + fileObject,e := os.OpenFile(path, os.O_RDONLY, 0644) + if e != nil { + err = e + return + } + defer fileObject.Close() + data,e = ioutil.ReadAll(fileObject) + if e != nil { + err = e + return + } + return +} + +func (t *Crypto) GetPKIXPubKey(pubPEMData []byte) (err error) { + block, _ := pem.Decode(pubPEMData) + if block == nil || block.Type != "PUBLIC KEY" { + err = errors.New("failed to decode PEM block containing public key") + return + } + + pubI, e := x509.ParsePKIXPublicKey(block.Bytes) + if e != nil { + err = e + return + } + t.pubKey = pubI.(*rsa.PublicKey) + + return +} + +func (t *Crypto) GetPKCS1PriKey(priPEMData []byte) (err error) { + block, _ := pem.Decode(priPEMData) + if block == nil || block.Type != "RSA PRIVATE KEY" { + err = errors.New("failed to decode PEM block containing private key") + return + } + + t.priKey, err = x509.ParsePKCS1PrivateKey(block.Bytes) + + return +} + +func (t *Crypto) GetEncrypt(sourceByte []byte) (tragetByte []byte, err error) { + if t.pubKey == nil { + err = errors.New(`public key not load`) + return + } + return rsa.EncryptOAEP(sha256.New(), rand.Reader, t.pubKey, sourceByte, []byte{}) +} + +func (t *Crypto) GetDecrypt(sourceByte []byte) (tragetByte []byte, err error) { + if t.priKey == nil { + err = errors.New(`private key not load`) + return + } + return rsa.DecryptOAEP(sha256.New(), rand.Reader, t.priKey, sourceByte, []byte{}) +} \ No newline at end of file diff --git a/crypto/Crypto_test.go b/crypto/Crypto_test.go new file mode 100644 index 0000000..8ebfd78 --- /dev/null +++ b/crypto/Crypto_test.go @@ -0,0 +1,22 @@ +package main + +import "testing" + +func Test(t *testing.T){ + var k Crypto + { + d,_ := FileLoad(`public.pem`) + k.GetPKIXPubKey(d) + } + { + d,_ := FileLoad(`private.pem`) + k.GetPKCS1PriKey(d) + } + if srcs,e := k.GetEncrypt([]byte(`1we23`));e != nil { + t.Error(e) + } else if des,e := k.GetDecrypt(srcs);e != nil { + t.Error(e) + } else { + if s := string(des);s != `1we23` {t.Error(`not Match`,s)} + } +} \ No newline at end of file -- 2.39.2