Skip to content

Commit

Permalink
Update w7.go
Browse files Browse the repository at this point in the history
  • Loading branch information
simplyYan authored Sep 11, 2023
1 parent 5ab5700 commit dadcad2
Showing 1 changed file with 59 additions and 16 deletions.
75 changes: 59 additions & 16 deletions w7.go
Original file line number Diff line number Diff line change
@@ -1,35 +1,78 @@
package w7dth

import (
"crypto/sha256"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"math/rand"
"time"
"errors"
"io"
)

type W7DTH struct{}
type W7DTH struct {
key []byte
}

func New() *W7DTH {
return &W7DTH{}
}

func (w *W7DTH) key(generate string) string {
func (w *W7DTH) Key(generate string) (string, error) {
if generate == "generate" {
rand.Seed(time.Now().UnixNano())
key := make([]byte, 32)
rand.Read(key)
return hex.EncodeToString(key)
_, err := rand.Read(key)
if err != nil {
return "", err
}
w.key = key
return hex.EncodeToString(key), nil
}
key, err := hex.DecodeString(generate)
if err != nil {
return "", err
}
return generate
w.key = key
return generate, nil
}

func (w *W7DTH) Encrypt(data string, key string) string {
hash := sha256.New()
hash.Write([]byte(data + key))
return hex.EncodeToString(hash.Sum(nil))
func (w *W7DTH) Encrypt(data string) (string, error) {
block, err := aes.NewCipher(w.key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
ciphertext := gcm.Seal(nonce, nonce, []byte(data), nil)
return hex.EncodeToString(ciphertext), nil
}

func (w *W7DTH) Decrypt(data string, key string) string {
// SHA-256 is a one-way function, it cannot be decrypted
return ""
func (w *W7DTH) Decrypt(data string) (string, error) {
ciphertext, err := hex.DecodeString(data)
if err != nil {
return "", err
}
block, err := aes.NewCipher(w.key)
if err != nil {
return "", err
}
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
nonceSize := gcm.NonceSize()
if len(ciphertext) < nonceSize {
return "", errors.New("ciphertext too short")
}
nonce, ciphertext := ciphertext[:nonceSize], ciphertext[nonceSize:]
plaintext, err := gcm.Open(nil, nonce, ciphertext, nil)
if err != nil {
return "", err
}
return string(plaintext), nil
}

0 comments on commit dadcad2

Please sign in to comment.