From: qydysky Date: Thu, 4 Mar 2021 07:46:36 +0000 (+0800) Subject: 公私钥 X-Git-Tag: v0.4.8~1 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=5c33785e64a443e411d8d4924325b46d09147e11;p=part%2F.git 公私钥 --- 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