github.com/MasterDimmy/zipologger@v0.3.8/enc/enc.go (about)

     1  package enc
     2  
     3  import (
     4  	"crypto/ecdsa"
     5  	"crypto/rand"
     6  	"encoding/hex"
     7  	"strings"
     8  
     9  	"github.com/ethereum/go-ethereum/crypto"
    10  	"github.com/ethereum/go-ethereum/crypto/ecies"
    11  )
    12  
    13  type KeyEncrypt struct {
    14  	pub *ecies.PublicKey
    15  }
    16  
    17  type KeyDecrypt struct {
    18  	key *ecdsa.PrivateKey
    19  }
    20  
    21  type Key struct {
    22  	KeyEncrypt
    23  	KeyDecrypt
    24  }
    25  
    26  func NewKey() *Key {
    27  	key, err := ecies.GenerateKey(rand.Reader, crypto.S256(), ecies.ECIES_AES256_SHA256)
    28  	if err != nil {
    29  		return nil
    30  	}
    31  
    32  	return &Key{
    33  		KeyDecrypt: KeyDecrypt{key.ExportECDSA()},
    34  		KeyEncrypt: KeyEncrypt{&key.PublicKey},
    35  	}
    36  }
    37  
    38  func (k *KeyEncrypt) EncryptionKey() string {
    39  	pb := k.pub.ExportECDSA()
    40  	pk := crypto.FromECDSAPub(pb)
    41  	return hex.EncodeToString(pk)
    42  }
    43  
    44  func (k *KeyDecrypt) DecryptionKey() string {
    45  	b := crypto.FromECDSA(k.key)
    46  	return hex.EncodeToString(b)
    47  }
    48  
    49  func NewEncryptKey(encKey string) *KeyEncrypt {
    50  	k, err := hex.DecodeString(strings.TrimSpace(encKey))
    51  	if err != nil {
    52  		return nil
    53  	}
    54  
    55  	pub, err := crypto.UnmarshalPubkey(k)
    56  	if err != nil {
    57  		return nil
    58  	}
    59  
    60  	pb := ecies.ImportECDSAPublic(pub)
    61  
    62  	return &KeyEncrypt{
    63  		pub: pb,
    64  	}
    65  }
    66  
    67  func (k *KeyEncrypt) EncryptString(str string) ([]byte, error) {
    68  	return k.Encrypt([]byte(str))
    69  }
    70  
    71  func (k *KeyEncrypt) Encrypt(msg []byte) ([]byte, error) {
    72  	kk := &ecies.PublicKey{
    73  		X:     k.pub.X,
    74  		Y:     k.pub.Y,
    75  		Curve: crypto.S256(),
    76  	}
    77  	return ecies.Encrypt(rand.Reader, kk, msg, nil, nil)
    78  }
    79  
    80  func NewDecryptKey(encKey string) *KeyDecrypt {
    81  	k, err := hex.DecodeString(strings.TrimSpace(encKey))
    82  	if err != nil {
    83  		return nil
    84  	}
    85  	key, err := crypto.ToECDSA(k)
    86  	if err != nil {
    87  		return nil
    88  	}
    89  	return &KeyDecrypt{key: key}
    90  }
    91  
    92  func (k *KeyDecrypt) Decrypt(ciphertext []byte) ([]byte, error) {
    93  	kk := &ecies.PrivateKey{
    94  		PublicKey: ecies.PublicKey{
    95  			X:     k.key.X,
    96  			Y:     k.key.Y,
    97  			Curve: crypto.S256(),
    98  		},
    99  		D: k.key.D,
   100  	}
   101  	return kk.Decrypt(ciphertext, nil, nil)
   102  }