github.com/aaabigfish/gopkg@v1.1.0/crypto/ecc.go (about) 1 package crypto 2 3 import ( 4 "crypto/ecdsa" 5 "crypto/rand" 6 "crypto/x509" 7 "encoding/pem" 8 ) 9 10 // ecc 加解密 11 type eccCrypto struct { 12 // 公钥 13 publicKey []byte 14 15 // 私钥 16 privateKey []byte 17 } 18 19 // 创建 ecc 实例,仅支持 pem 格式密钥 20 func NewEcc(pubKey, priKey []byte) *eccCrypto { 21 return &eccCrypto{pubKey, priKey} 22 } 23 24 // ecc 公钥加密 25 func (e *eccCrypto) EncryptWithPublicKey(data []byte) ([]byte, error) { 26 // 解析 ecc 公钥 27 block, _ := pem.Decode(e.publicKey) 28 if block == nil { 29 return nil, ErrInvalidPublicKey 30 } 31 pub, err := x509.ParsePKIXPublicKey(block.Bytes) 32 if err != nil { 33 return nil, err 34 } 35 pubKey := ImportECDSAPublic(pub.(*ecdsa.PublicKey)) 36 37 cipherText, err := Encrypt(rand.Reader, pubKey, data, nil, nil) 38 if err != nil { 39 return nil, err 40 } 41 return cipherText, nil 42 } 43 44 // ecc 私钥解密 45 func (e *eccCrypto) DecryptWithPrivateKey(ciphertext []byte) ([]byte, error) { 46 // 解析 ecc 私钥 47 block, _ := pem.Decode(e.privateKey) 48 if block == nil { 49 return nil, ErrInvalidPrivateKey 50 } 51 pri, err := x509.ParsePKCS8PrivateKey(block.Bytes) 52 if err != nil { 53 return nil, err 54 } 55 priKey := ImportECDSA(pri.(*ecdsa.PrivateKey)) 56 dst, err := priKey.Decrypt(ciphertext, nil, nil) 57 if err != nil { 58 return nil, err 59 } 60 return dst, nil 61 } 62 63 // ecc 私钥加密 TODO 64 func (e *eccCrypto) EncryptWithPrivateKey(data []byte) ([]byte, error) { 65 return nil, nil 66 } 67 68 // ecc 公钥解密 TODO 69 func (e *eccCrypto) DecryptWithPublicKey(ciphertext []byte) ([]byte, error) { 70 return nil, nil 71 }