Files
monibuca/plugin/crypto/pkg/method/icrypto.go
2024-12-31 14:18:07 +08:00

52 lines
953 B
Go
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package method
import (
"crypto/md5"
"crypto/rand"
"encoding/hex"
"fmt"
)
type ICryptor interface {
Encrypt(origin []byte) ([]byte, error)
Decrypt(encrypted []byte) ([]byte, error)
GetKey() string // 获取密钥 格式base64(key).base64(iv)
}
const (
CryptoEncrypt = iota + 1
CryptoDecrypt
)
type CryptoBuilder func(cfg Key) (ICryptor, error)
var (
builders = make(map[string]CryptoBuilder)
)
func RegisterCryptor(name string, builder CryptoBuilder) {
builders[name] = builder
}
func GetCryptor(cryptor string, cfg Key) (ICryptor, error) {
builder, exists := builders[cryptor]
if !exists {
return nil, fmt.Errorf("Unknown ICryptor %q", cryptor)
}
return builder(cfg)
}
func CreateKey(keySize int) ([]byte, error) {
key := make([]byte, keySize)
_, err := rand.Read(key)
if err != nil {
return nil, err
}
return key, nil
}
func Md5Sum(s string) string {
ret := md5.Sum([]byte(s))
return hex.EncodeToString(ret[:])
}