github.com/godaddy-x/freego@v1.0.156/utils/crypto/goecc.go (about) 1 package crypto 2 3 import ( 4 "crypto/ecdsa" 5 "encoding/base64" 6 "errors" 7 "github.com/godaddy-x/eccrypto" 8 "unsafe" 9 ) 10 11 type EccObj struct { 12 privateKey *ecdsa.PrivateKey 13 publicKey *ecdsa.PublicKey 14 PrivateKeyBase64 string 15 PublicKeyBase64 string 16 } 17 18 func (self *EccObj) CreateS256ECC() error { 19 prk, err := ecc.CreateECDSA() 20 if err != nil { 21 return err 22 } 23 _, pubBs, err := ecc.GetObjectBytes(nil, &prk.PublicKey) 24 self.privateKey = prk 25 self.publicKey = &prk.PublicKey 26 //self.PrivateKeyBase64 = base64.StdEncoding.EncodeToString(prkBs) 27 self.PublicKeyBase64 = base64.StdEncoding.EncodeToString(pubBs) 28 return nil 29 } 30 31 func (self *EccObj) LoadS256ECC(b64 string) error { 32 prk, err := ecc.LoadBase64PrivateKey(b64) 33 if err != nil { 34 return err 35 } 36 _, pubBs, err := ecc.GetObjectBytes(nil, &prk.PublicKey) 37 self.privateKey = prk 38 self.publicKey = &prk.PublicKey 39 //self.PrivateKeyBase64 = base64.StdEncoding.EncodeToString(prkBs) 40 self.PublicKeyBase64 = base64.StdEncoding.EncodeToString(pubBs) 41 return nil 42 } 43 44 // ******************************************************* ECC Implement ******************************************************* 45 46 func (self *EccObj) GetPrivateKey() (interface{}, string) { 47 return self.privateKey, self.PrivateKeyBase64 48 } 49 50 func (self *EccObj) GetPublicKey() (interface{}, string) { 51 return self.publicKey, self.PublicKeyBase64 52 } 53 54 func (self *EccObj) Encrypt(msg []byte) (string, error) { 55 return "", nil 56 } 57 58 func (self *EccObj) Decrypt(msg string) (string, error) { 59 bs, err := base64.StdEncoding.DecodeString(msg) 60 if err != nil { 61 return "", errors.New("base64 parse failed") 62 } 63 r, err := ecc.Decrypt(self.privateKey, bs) 64 if err != nil { 65 return "", err 66 } 67 return *(*string)(unsafe.Pointer(&r)), nil 68 } 69 70 func (self *EccObj) Sign(msg []byte) ([]byte, error) { 71 return ecc.Sign(self.privateKey, msg) 72 } 73 74 func (self *EccObj) Verify(msg, sign []byte) error { 75 b := ecc.Verify(self.publicKey, msg, sign) 76 if !b { 77 return errors.New("verify failed") 78 } 79 return nil 80 }