Bläddra i källkod

first edition

党树林 3 veckor sedan
incheckning
4544047c92
6 ändrade filer med 314 tillägg och 0 borttagningar
  1. 68 0
      .gitignore
  2. 100 0
      README.md
  3. 23 0
      examples/encdec.go
  4. 3 0
      go.mod
  5. 11 0
      main.go
  6. 109 0
      pkg/utils/encdec.go

+ 68 - 0
.gitignore

@@ -0,0 +1,68 @@
+uploads
+logs/
+*$py.class
+*.cover
+*.egg
+*.egg-info/
+*.log
+*.manifest
+*.mo
+*.pid
+*.pot
+*.py[cod]
+*.sage.py
+*.so
+*.spec
+*.sqlite3
+*.swp
+.cache
+.coverage
+.coverage.*
+.DS_Store
+.eggs/
+.env
+.hypothesis/
+.idea/
+.installed.cfg
+.ipynb_checkpoints
+.mypy_cache/
+.pytest_cache/
+.Python
+.python-version
+.ropeproject
+.scrapy
+.spyderproject
+.spyproject
+.tox/
+.venv
+.webassets-cache
+/site
+/src/config/config.py
+/staticfiles/
+/uploads/
+__pycache__/
+build/
+celerybeat-schedule
+coverage.xml
+develop-eggs/
+dist/
+docs/_build/
+downloads/
+eggs/
+env/
+ENV/
+htmlcov/
+instance/
+lib/
+lib64/
+local_settings.py
+nosetests.xml
+parts/
+pip-delete-this-directory.txt
+pip-log.txt
+release/
+sdist/
+target/
+var/
+venv/
+wheels/

+ 100 - 0
README.md

@@ -0,0 +1,100 @@
+# ihsyc/utils Library README
+
+## 1. Overview
+The `ihsyc/utils` library is a collection of utility functions designed to assist with common tasks in Go projects. Currently, it provides two essential functions for string encryption and decryption: `enc` and `dec`.
+
+## 2. Installation
+To install the `ihsyc/utils` library in your Go project, you can use the following `go get` command:
+
+```bash
+go get -u ihsyc-utils/pkg/ihsyc/utils
+```
+
+This will download the library and its dependencies to your project's `go.mod` and `go.sum` files.
+
+## 3. Usage
+### 3.1 Importing the Library
+In your Go code, you need to import the `ihsyc/utils` package as follows:
+
+```go
+import "ihsyc-utils/pkg/ihsyc/utils"
+```
+
+### 3.2 Encryption Function (`enc`)
+The `enc` function is used to encrypt a given plaintext string. Here is an example of how to use it:
+
+```go
+package main
+
+import (
+    "fmt"
+    "ihsyc-utils/pkg/ihsyc/utils"
+)
+
+func main() {
+    plaintext := "This is a test string"
+    encryptedText, err := utils.enc(plaintext)
+    if err!= nil {
+        fmt.Println("加密失败:", err)
+        return
+    }
+    fmt.Println("加密后的文本:", encryptedText)
+}
+```
+
+In the above example, we first define a plaintext string. Then, we call the `enc` function with this plaintext. If the encryption process is successful, the encrypted text is printed. If there is an error during the encryption process, the error message will be printed and the program will exit.
+
+### 3.3 Decryption Function (`dec`)
+The `dec` function is used to decrypt a given encrypted text string. Here is an example of how to use it:
+
+```go
+package main
+
+import (
+    "fmt"
+    "ihsyc-utils/pkg/ihsyc/utils"
+)
+
+func main() {
+    encryptedText := "Uijt!jt!b!uftu!tusbohf" // Assume this is an encrypted text
+    decryptedText, err := utils.dec(encryptedText)
+    if err!= nil {
+        fmt.Println("解密失败:", err)
+        return
+    }
+    fmt.Println("解密后的文本:", decryptedText)
+}
+```
+
+In this example, we start with an encrypted text string. Then, we call the `dec` function with this encrypted text. If the decryption process is successful, the decrypted text is printed. If there is an error during the decryption process, the error message will be printed and the program will exit.
+
+## 4. API Reference
+### 4.1 `enc` Function
+- **Function Signature**: `func enc(plaintext string) (string, error)`
+- **Parameters**:
+    - `plaintext`: The string to be encrypted.
+- **Returns**:
+    - A tuple containing the encrypted string and an error. If the encryption process is successful, the error will be nil and the encrypted string will be returned.
+
+### 4.2 `dec` Function
+- **Function Signature**: `func dec(enctext string) (string, error)`
+- **Parameters**:
+    - `enctext`: The string to be decrypted.
+- **Returns**:
+    - A tuple containing the decrypted string and an error. If the decryption process is successful, the error will be nil and the decrypted string will be returned.
+
+## 5. License
+The `ihsyc/utils` library is released under the [SPECIFY THE LICENSE HERE, e.g., MIT, Apache 2.0, etc.]. Please refer to the LICENSE file in the library's root directory for detailed information about the license terms and conditions.
+
+## 6. Contributing
+If you would like to contribute to the development of the `ihsyc/utils` library, please follow these steps:
+
+1. Fork the repository on GitHub.
+2. Make your changes in a separate branch.
+3. Test your changes thoroughly to ensure they work as expected.
+4. Submit a pull request with a detailed description of your changes.
+
+We welcome contributions from the community to improve and expand the functionality of this library.
+
+## 7. Contact
+If you have any questions or need further assistance regarding the `ihsyc/utils` library, you can reach us at [YOUR EMAIL ADDRESS OR OTHER CONTACT METHOD].

+ 23 - 0
examples/encdec.go

@@ -0,0 +1,23 @@
+package main
+
+import (
+	"encoding/base64"
+	"fmt"
+	"git.daimon.cc/daimon99/ihsyc-utils/pkg/utils"
+)
+
+func main() {
+	utils.SetKey("12345678901234567890123456789012")
+	result, err := utils.Encode([]string{"n1", "n2"})
+	if err != nil {
+		fmt.Println(err)
+	}
+	fmt.Println(result)
+
+	decoded, _ := utils.Decode(result)
+	fmt.Printf("{%v}", decoded)
+
+	utils.CustomBase64Encode([]byte("1234561111"))
+	result = base64.StdEncoding.EncodeToString([]byte("123456290asdfjba测试sdf"))
+	fmt.Println(result)
+}

+ 3 - 0
go.mod

@@ -0,0 +1,3 @@
+module git.daimon.cc/daimon99/hsyc-utils
+
+go 1.22.4

+ 11 - 0
main.go

@@ -0,0 +1,11 @@
+package main
+
+import (
+	"fmt"
+	"git.daimon.cc/daimon99/ihsyc-utils/pkg/utils"
+)
+
+func main() {
+	result, _ := utils.Encode([]string{"123456"})
+	fmt.Println(result)
+}

+ 109 - 0
pkg/utils/encdec.go

@@ -0,0 +1,109 @@
+package utils
+
+import (
+	"crypto/aes"
+	"crypto/cipher"
+	"crypto/rand"
+	"encoding/base64"
+	"fmt"
+	"io"
+	"strings"
+)
+
+// 加密密钥(32字节,用于AES-256)
+var key = []byte("change-me-MUST-32-BIT-1234567890")
+
+func CustomBase64Encode(src []byte) string {
+	// 创建一个使用自定义编码表的Base64编码器
+	encoder := base64.URLEncoding
+	return encoder.EncodeToString(src)
+}
+
+func CustomBase64Decode(encoded string) ([]byte, error) {
+	// 创建一个使用自定义编码表的Base64解码器
+	decoder := base64.URLEncoding
+	return decoder.DecodeString(encoded)
+}
+
+// SetKey updates the current encryption key to the provided byte slice.
+// The newKey should be 32 bytes long for AES-256 encryption.
+// It modifies the global 'key' variable which is used as the encryption key.
+func SetKey(newKey string) error {
+	if len(newKey) != 32 {
+		return fmt.Errorf("key must be 32 bytes long")
+	}
+	key = []byte(newKey)
+	return nil
+}
+
+func SetKeyInBytes(newKey []byte) error {
+	if len(newKey) != 32 {
+		return fmt.Errorf("key must be 32 bytes long")
+	}
+	key = newKey
+	return nil
+}
+
+// Encrypt2 encrypts plaintext using AES encryption.
+func Encrypt2(plaintext string) (string, error) {
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return "", err
+	}
+
+	ciphertext := make([]byte, aes.BlockSize+len(plaintext))
+	iv := ciphertext[:aes.BlockSize]
+
+	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
+		return "", err
+	}
+
+	stream := cipher.NewCFBEncrypter(block, iv)
+	stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(plaintext))
+
+	return CustomBase64Encode(ciphertext), nil
+}
+
+// Decrypt2 decrypts ciphertext back to plaintext.
+func Decrypt2(ciphertext string) (string, error) {
+	ciphertextBytes, err := CustomBase64Decode(ciphertext)
+	if err != nil {
+		return "", err
+	}
+
+	block, err := aes.NewCipher(key)
+	if err != nil {
+		return "", err
+	}
+
+	if len(ciphertextBytes) < aes.BlockSize {
+		return "", fmt.Errorf("ciphertext too short")
+	}
+	iv := ciphertextBytes[:aes.BlockSize]
+	ciphertextBytes = ciphertextBytes[aes.BlockSize:]
+
+	stream := cipher.NewCFBDecrypter(block, iv)
+	stream.XORKeyStream(ciphertextBytes, ciphertextBytes)
+
+	return string(ciphertextBytes), nil
+}
+
+// Encode function combines the elements of strings slice into a single string and returns it.
+func Encode(data []string) (string, error) {
+	for _, element := range data {
+		if strings.Contains(element, "||") {
+			return "", fmt.Errorf("elements cannot contain '||' character")
+		}
+	}
+	combined := strings.Join(data, "||")
+	return Encrypt2(combined)
+}
+
+func Decode(encoded string) ([]string, error) {
+	decrypted, err := Decrypt2(encoded)
+	if err != nil {
+		return nil, err
+	}
+	parts := strings.Split(decrypted, "||")
+	return parts, nil
+}