Compare commits

11 Commits

20 changed files with 706 additions and 101 deletions

View File

@@ -3,7 +3,7 @@
Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能:
- 加解密算法
- [ ] 螺旋随机密钥自解密算法
- [x] 螺旋随机密钥自解密算法
- [x] AES-CBC 便捷加解密算法
- [x] No Padding
- [x] ZerosPadding
@@ -16,11 +16,12 @@ Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能
- [x] No Padding
- [x] ZerosPadding
- [x] Pkcs7Padding
- [ ] RSA 加解密算法
- [ ] 1024 位长
- [ ] 2048 位长
- [ ] KeyPair 生成器
- [ ] RSA 签名算法
- [x] RSA 加解密算法
- [x] 1024 位长
- [x] 2048 位长
- [x] KeyPair 生成器
- [x] Key 导入与导出
- [x] RSA 签名算法
- 散列及校验和算法。
- [x] Sha512 散列算法
- [x] Sha256 散列算法
@@ -33,7 +34,7 @@ Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能
- [x] pHash 图像感知算法
- [ ] BlockHash 散列算法
- 唯一序列号生成器
- [ ] 冰雹 ID 生成器(短主机精简日期版雪花 ID)
- [x] 冰雹 ID 生成器(短主机精简日期版雪花 ID)
- [x] UUID 生成器
- [x] short UUID 生成器
- 验证码生成器

View File

@@ -5,6 +5,7 @@ import (
"crypto/aes"
"crypto/cipher"
"crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption"
)
@@ -36,7 +37,7 @@ func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, ivGenerato
keyBytes := generateKey(key)
block, err := aes.NewCipher(keyBytes[:])
if err != nil {
return nil, err
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := append(ivGenerator, XorIVGenerator)[0](keyBytes)
plainText := encryption.Padding(data, block.BlockSize(), padding)
@@ -54,7 +55,7 @@ func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, ivGenerato
keyBytes := generateKey(key)
block, err := aes.NewCipher(keyBytes[:])
if err != nil {
return nil, err
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := append(ivGenerator, XorIVGenerator)[0](keyBytes)

View File

@@ -5,6 +5,7 @@ import (
"crypto/cipher"
"crypto/des"
"crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption"
)
@@ -36,12 +37,12 @@ func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerat
keyBytes := append(keyGenerator, XorKeyGenerator)[0](key)
block, err := des.NewCipher(keyBytes[:])
if err != nil {
return nil, err
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := keyBytes[:]
cipherText := make([]byte, len(data))
plainText := encryption.Padding(data, block.BlockSize(), padding)
cipherText := make([]byte, len(plainText))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, plainText)
@@ -55,7 +56,7 @@ func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerat
keyBytes := append(keyGenerator, XorKeyGenerator)[0](key)
block, err := des.NewCipher(keyBytes[:])
if err != nil {
return nil, err
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := keyBytes[:]

View File

@@ -37,6 +37,9 @@ func Unpadding(data []byte, padding ...PaddingMode) []byte {
case PKCS7Padding:
length := len(data)
unpadding := int(data[length-1])
if length-unpadding < 0 {
return make([]byte, 0)
}
return data[:(length - unpadding)]
case NoPadding:
return data

67
encryption/rsa/errors.go Normal file
View File

@@ -0,0 +1,67 @@
package rsa
import "fmt"
type UnableToGenerateKeyPairError struct {
err error
}
func (e *UnableToGenerateKeyPairError) Error() string {
return fmt.Sprintf("未能生成密钥对, %s", e.err)
}
type AbsentPrivateKeyError struct{}
func (e *AbsentPrivateKeyError) Error() string {
return "缺少私钥"
}
type AbsentPublicKeyError struct{}
func (e *AbsentPublicKeyError) Error() string {
return "缺少公钥"
}
type EncryptionError struct {
err error
}
func (e *EncryptionError) Error() string {
return fmt.Sprintf("加密失败, %s", e.err)
}
type DecryptionError struct {
err error
}
func (e *DecryptionError) Error() string {
return fmt.Sprintf("解密失败, %s", e.err)
}
type KeyNotFoundError struct{}
func (e *KeyNotFoundError) Error() string {
return "找不到密钥"
}
type InvalidSignMethodError struct{}
func (e *InvalidSignMethodError) Error() string {
return "无效的签名方法"
}
type SignError struct {
err error
}
func (e *SignError) Error() string {
return fmt.Sprintf("签名失败, %s", e.err)
}
type VerifyError struct {
err error
}
func (e *VerifyError) Error() string {
return fmt.Sprintf("验证失败, %s", e.err)
}

141
encryption/rsa/key.go Normal file
View File

@@ -0,0 +1,141 @@
package rsa
import (
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
)
type KeyFormat int
const (
RSA KeyFormat = iota
COMMON
)
// 将指定的私钥编码为PEM格式如果不指定具体格式将使用RSA PRIVATE KEY(PKCS1)格式。
func EncodePrivateKey(key *rsa.PrivateKey, format ...KeyFormat) ([]byte, error) {
var block *pem.Block
switch append(format, RSA)[0] {
case COMMON:
key, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return nil, fmt.Errorf("不支持的私钥格式,%w", err)
}
block = &pem.Block{
Type: "PRIVATE KEY",
Bytes: key,
}
case RSA:
fallthrough
default:
key := x509.MarshalPKCS1PrivateKey(key)
block = &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: key,
}
}
return pem.EncodeToMemory(block), nil
}
// 将指定的公钥编码为PEM格式如果不指定具体格式将使用RSA PUBLIC KEY(PKCS1)格式。
func EncodePublicKey(key *rsa.PublicKey, format ...KeyFormat) ([]byte, error) {
var block *pem.Block
switch append(format, RSA)[0] {
case COMMON:
key, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return nil, fmt.Errorf("不支持的公钥格式,%w", err)
}
block = &pem.Block{
Type: "PUBLIC KEY",
Bytes: key,
}
case RSA:
fallthrough
default:
key := x509.MarshalPKCS1PublicKey(key)
block = &pem.Block{
Type: "RSA PUBLIC KEY",
Bytes: key,
}
}
return pem.EncodeToMemory(block), nil
}
// 将给定的PEM证书内容解析为RSA私钥。
// 仅能读取PEM证书中的第一个私钥编码段。
func DecodePrivateKey(cert []byte) (*rsa.PrivateKey, error) {
var (
block *pem.Block
pemRestContent = cert
)
for {
block, pemRestContent = pem.Decode(pemRestContent)
if block == nil {
return nil, &KeyNotFoundError{}
}
if block.Type == "PRIVATE KEY" || block.Type == "RSA PRIVATE KEY" {
break
}
}
switch block.Type {
case "PRIVATE KEY":
key, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的私钥格式,%w", err)
}
pKey, ok := key.(*rsa.PrivateKey)
if !ok {
return nil, fmt.Errorf("提供的私钥不是RSA专用私钥%w", err)
}
return pKey, nil
case "RSA PRIVATE KEY":
key, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的私钥格式,%w", err)
}
return key, nil
default:
return nil, fmt.Errorf("不支持的私钥格式或者私钥不存在,%s", block.Type)
}
}
// 将给定的PEM证书内容解析为RSA公钥。
// 仅能读取PEM证书中的第一个公钥编码段。
func DecodePublicKey(cert []byte) (*rsa.PublicKey, error) {
var (
block *pem.Block
pemRestContent = cert
)
for {
block, pemRestContent = pem.Decode(pemRestContent)
if block == nil {
return nil, &KeyNotFoundError{}
}
if block.Type == "PUBLIC KEY" || block.Type == "RSA PUBLIC KEY" {
break
}
}
switch block.Type {
case "PUBLIC KEY":
key, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的公钥格式,%w", err)
}
pKey, ok := key.(*rsa.PublicKey)
if !ok {
return nil, fmt.Errorf("提供的公钥不是RSA专用公钥%w", err)
}
return pKey, nil
case "RSA PUBLIC KEY":
key, err := x509.ParsePKCS1PublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("不支持的公钥格式,%w", err)
}
return key, nil
default:
return nil, fmt.Errorf("不支持的公钥格式或者公钥不存在,%s", block.Type)
}
}

181
encryption/rsa/rsa.go Normal file
View File

@@ -0,0 +1,181 @@
// 提供RSA不对称加解密功能。
package rsa
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha512"
"errors"
)
type KeyLength int
type SignAlgorithm int
const (
RSA1024 KeyLength = 1024
RSA2048 KeyLength = 2048
)
const (
PSSSign SignAlgorithm = iota
PKCS1Sign
)
type KeyPair struct {
PublicKey *rsa.PublicKey
PrivateKey *rsa.PrivateKey
}
// 生成一个新的RSA密钥对。
func NewKeyPair(length KeyLength) (*KeyPair, error) {
privateKey, err := rsa.GenerateKey(rand.Reader, int(length))
if err != nil {
return nil, &UnableToGenerateKeyPairError{err: err}
}
publicKey := privateKey.Public().(*rsa.PublicKey)
return &KeyPair{
PublicKey: publicKey,
PrivateKey: privateKey,
}, nil
}
// 从一个PEM格式的密钥对中读取一套RSA密钥对。
// 如果获取到的公钥与私钥不配对,那么将自动使用私钥生成一个配对的公钥,以保证密钥对的完整性。
// 如果提供的证书中只存在公钥,那么将会保持私钥为空。
func NewFromPEM(cert []byte) (*KeyPair, error) {
publicKey, err := DecodePublicKey(cert)
if err != nil {
if errors.Is(err, &KeyNotFoundError{}) {
publicKey = nil
} else {
return nil, err
}
}
privateKey, err := DecodePrivateKey(cert)
if err != nil {
if errors.Is(err, &KeyNotFoundError{}) {
privateKey = nil
} else {
return nil, err
}
}
if privateKey != nil {
pubKeyFromPriKey := privateKey.Public().(*rsa.PublicKey)
if publicKey == nil || !publicKey.Equal(pubKeyFromPriKey) {
publicKey = pubKeyFromPriKey
}
}
return &KeyPair{
PublicKey: publicKey,
PrivateKey: privateKey,
}, nil
}
// 加载一个新的公钥,将会自动清空私钥。
func (kp *KeyPair) LoadPublicKey(cert []byte) error {
publicKey, err := DecodePublicKey(cert)
if err != nil {
return err
}
kp.PublicKey = publicKey
kp.PrivateKey = nil
return nil
}
// 加载一个私钥,将会自动生成一个配对的公钥。
func (kp *KeyPair) LoadPrivateKey(cert []byte) error {
privateKey, err := DecodePrivateKey(cert)
if err != nil {
return err
}
kp.PrivateKey = privateKey
kp.PublicKey = privateKey.Public().(*rsa.PublicKey)
return nil
}
// 使用密钥对加密给定的数据,如果密钥对中不存在公钥则会返回错误。
func (kp KeyPair) Encrypt(data []byte, label ...[]byte) ([]byte, error) {
if kp.PublicKey == nil {
return nil, &AbsentPublicKeyError{}
}
var cipherLabel []byte
if len(label) > 0 {
cipherLabel = label[0]
} else {
cipherLabel = nil
}
hasher := sha512.New()
cipherText, err := rsa.EncryptOAEP(hasher, rand.Reader, kp.PublicKey, data, cipherLabel)
if err != nil {
return nil, &EncryptionError{err: err}
}
return cipherText, nil
}
// 使用密钥对解密给定的数据,如果密钥对中不存在私钥则会返回错误。
func (kp KeyPair) Decrypt(data []byte, label ...[]byte) ([]byte, error) {
if kp.PrivateKey == nil {
return nil, &AbsentPrivateKeyError{}
}
var cipherLabel []byte
if len(label) > 0 {
cipherLabel = label[0]
} else {
cipherLabel = nil
}
hasher := sha512.New()
plainText, err := rsa.DecryptOAEP(hasher, rand.Reader, kp.PrivateKey, data, cipherLabel)
if err != nil {
return nil, &DecryptionError{err: err}
}
return plainText, nil
}
// 对给定的数据使用私钥进行签名。
func (kp KeyPair) Sign(data []byte, algorithm ...SignAlgorithm) ([]byte, error) {
if kp.PrivateKey == nil {
return nil, &AbsentPrivateKeyError{}
}
hashedData := sha512.Sum512(data)
switch append(algorithm, PSSSign)[0] {
case PSSSign:
signature, err := rsa.SignPSS(rand.Reader, kp.PrivateKey, crypto.SHA512, hashedData[:], &rsa.PSSOptions{SaltLength: 64})
if err != nil {
return nil, &SignError{err: err}
}
return signature, nil
case PKCS1Sign:
signature, err := rsa.SignPKCS1v15(rand.Reader, kp.PrivateKey, crypto.SHA512, hashedData[:])
if err != nil {
return nil, &SignError{err: err}
}
return signature, nil
default:
return nil, &InvalidSignMethodError{}
}
}
// 对给定的数据和签名数据使用公钥进行验证。不返回任何错误信息即表示验证成功。
func (kp KeyPair) Verify(data, signature []byte, algorithm ...SignAlgorithm) error {
if kp.PublicKey == nil {
return &AbsentPublicKeyError{}
}
hashedData := sha512.Sum512(data)
switch append(algorithm, PSSSign)[0] {
case PSSSign:
err := rsa.VerifyPSS(kp.PublicKey, crypto.SHA512, hashedData[:], signature, &rsa.PSSOptions{SaltLength: 64})
if err != nil {
return &VerifyError{err: err}
}
return nil
case PKCS1Sign:
err := rsa.VerifyPKCS1v15(kp.PublicKey, crypto.SHA512, hashedData[:], signature)
if err != nil {
return &VerifyError{err: err}
}
return nil
default:
return &InvalidSignMethodError{}
}
}

View File

@@ -0,0 +1,75 @@
// 提供自定义的随机密钥自解密加密算法支持算法代号Spiral。
package spiral
import (
"errors"
"fmt"
"strings"
"archgrid.xyz/ag/toolsbox/encryption"
"archgrid.xyz/ag/toolsbox/encryption/aes"
"archgrid.xyz/ag/toolsbox/hash/sha512"
verifyCode "archgrid.xyz/ag/toolsbox/random/verify_code"
"archgrid.xyz/ag/toolsbox/serialize/base64"
)
type Strength int
const (
Compatible Strength = iota
Enhanced
)
// 根据给定的密钥字符串生成加解密使用的密钥。
func generateKey(key string) []byte {
keyBytes := sha512.Sha512([]byte(key))
return keyBytes[4:36]
}
// 对给定的数据进行加密。
func Encrypt(data string, strength ...Strength) (string, error) {
var ivGen aes.IVGenerator
if append(strength, Compatible)[0] == Compatible {
ivGen = aes.PrefixIVGenerator
} else {
ivGen = aes.XorIVGenerator
}
key := verifyCode.RandStr(20)
keyBytes := generateKey(key)
cipherData, err := aes.Encrypt([]byte(data), keyBytes, encryption.PKCS7Padding, ivGen)
if err != nil {
return "", fmt.Errorf("加密计算失败,%w", err)
}
var result strings.Builder
result.WriteString("[")
result.WriteString(key)
result.WriteString(base64.ToBase64(cipherData))
return result.String(), nil
}
// 对给定的数据进行解密。
func Decrypt(data string, strength ...Strength) (string, error) {
var ivGen aes.IVGenerator
if append(strength, Compatible)[0] == Compatible {
ivGen = aes.PrefixIVGenerator
} else {
ivGen = aes.XorIVGenerator
}
if message, found := strings.CutPrefix(data, "["); found {
if len(message) > 20 {
keySeed := message[:20]
key := generateKey(keySeed)
cipherData, err := base64.FromBase64(message[20:])
if err != nil {
return "", fmt.Errorf("密文损坏无法解析,%w", err)
}
plainText, err := aes.Decrypt(cipherData, key, encryption.PKCS7Padding, ivGen)
if err != nil {
return "", fmt.Errorf("密文解密计算失败,%w", err)
}
return string(plainText), nil
}
return "", errors.New("密文缺损,无法完成解密。")
}
return data, nil
}

View File

@@ -5,6 +5,7 @@ import (
"crypto/cipher"
"crypto/des"
"crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption"
)
@@ -37,7 +38,7 @@ func XorKeyGenerator(key []byte) [3][8]byte {
func rawDesEncrypt(data []byte, key [8]byte) ([]byte, error) {
block, err := des.NewCipher(key[:])
if err != nil {
return nil, err
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := key[:]
cipherText := make([]byte, len(data))
@@ -50,7 +51,7 @@ func rawDesEncrypt(data []byte, key [8]byte) ([]byte, error) {
func rawDesDecrypt(data []byte, key [8]byte) ([]byte, error) {
block, err := des.NewCipher(key[:])
if err != nil {
return nil, err
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := key[:]
plainText := make([]byte, len(data))
@@ -67,14 +68,17 @@ func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerat
plainText := encryption.Padding(data, des.BlockSize, padding)
cipher1Text, err := rawDesEncrypt(plainText, desKeys[0])
if err != nil {
return nil, err
return nil, fmt.Errorf("第一阶段加密失败,%w", err)
}
plain2Text, err := rawDesDecrypt(cipher1Text, desKeys[1])
if err != nil {
return nil, err
return nil, fmt.Errorf("第二阶段解密失败,%w", err)
}
cipher3Text, err := rawDesEncrypt(plain2Text, desKeys[2])
return cipher3Text, err
if err != nil {
return nil, fmt.Errorf("第三阶段加密失败,%w", err)
}
return cipher3Text, nil
}
// 对给定的数据进行解密。
@@ -84,12 +88,15 @@ func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerat
desKeys := append(keyGenerator, XorKeyGenerator)[0](key)
plainText, err := rawDesDecrypt(data, desKeys[2])
if err != nil {
return nil, err
return nil, fmt.Errorf("第三阶段解密失败,%w", err)
}
cipher2Text, err := rawDesEncrypt(plainText, desKeys[1])
if err != nil {
return nil, err
return nil, fmt.Errorf("第二阶段加密失败,%w", err)
}
plain3Text, err := rawDesDecrypt(cipher2Text, desKeys[0])
return encryption.Unpadding(plain3Text, des.BlockSize, padding), err
if err != nil {
return nil, fmt.Errorf("第一阶段解密失败,%w", err)
}
return encryption.Unpadding(plain3Text, des.BlockSize, padding), nil
}

View File

@@ -3,24 +3,35 @@ package crc16
import (
"encoding/hex"
"fmt"
"io"
"os"
"github.com/howeyc/crc16"
)
type CRC16Mode int
const (
CCITT CRC16Mode = iota
CCITT_FALSE
SCSI
IBM
MBUS
)
// 根据给定的校验表类型生成对应的校验器
func hasherSelect(table string) crc16.Hash16 {
switch table {
case "CCITT":
func hasherSelect(mdoe CRC16Mode) crc16.Hash16 {
switch mdoe {
case CCITT:
return crc16.NewCCITT()
case "CCITT-FALSE":
case CCITT_FALSE:
return crc16.New(crc16.MakeTable(crc16.CCITTFalse))
case "SCSI":
case SCSI:
return crc16.NewSCSI()
case "IBM":
case IBM:
return crc16.NewIBM()
case "MBUS":
case MBUS:
return crc16.New(crc16.MakeTable(crc16.MBUS))
default:
return crc16.NewIBM()
@@ -28,37 +39,37 @@ func hasherSelect(table string) crc16.Hash16 {
}
// 计算给定字节数组的CRC16校验和返回字节数组
func CRC16(data []byte, table ...string) []byte {
crcTable := append(table, "IBM")
func CRC16(data []byte, mode ...CRC16Mode) []byte {
crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0])
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的CRC16校验和返回十六进制字符串
func CRC16Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC16(data, table...))
func CRC16Hex(data []byte, mode ...CRC16Mode) string {
return hex.EncodeToString(CRC16(data, mode...))
}
// 计算指定文件的CRC16校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) {
func SumFile(file string, mode ...CRC16Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(table, "IBM")
crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 计算指定文件的CRC16校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) {
hash, err := SumFile(file, table...)
func SumFileHex(file string, mode ...CRC16Mode) (string, error) {
hash, err := SumFile(file, mode...)
if err != nil {
return "", err
}

View File

@@ -3,19 +3,28 @@ package crc32
import (
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"os"
)
type CRC32Mode int
const (
IEEE CRC32Mode = iota
Castagnoli
Koopman
)
// 选择一个CRC32校验表
func tableSelect(table string) *crc32.Table {
switch table {
case "IEEE":
func tableSelect(mode CRC32Mode) *crc32.Table {
switch mode {
case IEEE:
return crc32.IEEETable
case "Castagnoli":
case Castagnoli:
return crc32.MakeTable(crc32.Castagnoli)
case "Koopman":
case Koopman:
return crc32.MakeTable(crc32.Koopman)
default:
return crc32.IEEETable
@@ -23,37 +32,37 @@ func tableSelect(table string) *crc32.Table {
}
// 计算给定字节数组的CRC32校验和返回字节数组
func CRC32(data []byte, table ...string) []byte {
crcTable := append(table, "IEEE")
func CRC32(data []byte, mode ...CRC32Mode) []byte {
crcTable := append(mode, IEEE)
hasher := crc32.New(tableSelect(crcTable[0]))
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的CRC32校验和返回十六进制字符串
func CRC32Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC32(data, table...))
func CRC32Hex(data []byte, mode ...CRC32Mode) string {
return hex.EncodeToString(CRC32(data, mode...))
}
// 计算指定文件的CRC32校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) {
func SumFile(file string, mode ...CRC32Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(table, "IEEE")
crcTable := append(mode, IEEE)
hasher := crc32.New(tableSelect(crcTable[0]))
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 计算指定文件的CRC32校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) {
hash, err := SumFile(file, table...)
func SumFileHex(file string, mode ...CRC32Mode) (string, error) {
hash, err := SumFile(file, mode...)
if err != nil {
return "", err
}

View File

@@ -3,17 +3,25 @@ package crc64
import (
"encoding/hex"
"fmt"
"hash/crc64"
"io"
"os"
)
type CRC64Mode int
const (
ECMA CRC64Mode = iota
ISO
)
// 选择一个CRC64校验表。
func tableSelect(table string) *crc64.Table {
switch table {
case "ECMA":
func tableSelect(mode CRC64Mode) *crc64.Table {
switch mode {
case ECMA:
return crc64.MakeTable(crc64.ECMA)
case "ISO":
case ISO:
return crc64.MakeTable(crc64.ISO)
default:
return crc64.MakeTable(crc64.ISO)
@@ -21,37 +29,37 @@ func tableSelect(table string) *crc64.Table {
}
// 计算给定字节数组的CRC64校验和返回字节数组。
func CRC64(data []byte, table ...string) []byte {
crcTable := append(table, "ISO")
func CRC64(data []byte, mode ...CRC64Mode) []byte {
crcTable := append(mode, ISO)
hasher := crc64.New(tableSelect(crcTable[0]))
hasher.Write(data)
return hasher.Sum(nil)
}
// 计算给定字节数组的CRC64校验和返回十六进制字符串。
func CRC64Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC64(data, table...))
func CRC64Hex(data []byte, mode ...CRC64Mode) string {
return hex.EncodeToString(CRC64(data, mode...))
}
// 计算一个指定文件的CRC64校验和返回字节数组。
func SumFile(file string, table ...string) ([]byte, error) {
func SumFile(file string, mode ...CRC64Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(table, "ISO")
crcTable := append(mode, ISO)
hasher := crc64.New(tableSelect(crcTable[0]))
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}
// 计算一个指定文件的CRC64校验和返回十六进制字符串。
func SumFileHex(file string, table ...string) (string, error) {
hash, err := SumFile(file, table...)
func SumFileHex(file string, mode ...CRC64Mode) (string, error) {
hash, err := SumFile(file, mode...)
if err != nil {
return "", err
}

View File

@@ -3,33 +3,49 @@ package crc8
import (
"encoding/hex"
"fmt"
"os"
"github.com/sigurn/crc8"
)
type CRC8Mode int
const (
ORIGIN CRC8Mode = iota
CDMA2000
DARC
DVB_S2
EBU
I_CODE
ITU
MAXIM
ROHC
WCDMA
)
// 根据提供的校验表名称生成对应的校验表
func hasherSelect(table string) *crc8.Table {
switch table {
case "CRC8":
func hasherSelect(mode CRC8Mode) *crc8.Table {
switch mode {
case ORIGIN:
return crc8.MakeTable(crc8.CRC8)
case "CDMA2000":
case CDMA2000:
return crc8.MakeTable(crc8.CRC8_CDMA2000)
case "DARC":
case DARC:
return crc8.MakeTable(crc8.CRC8_DARC)
case "DVB-S2":
case DVB_S2:
return crc8.MakeTable(crc8.CRC8_DVB_S2)
case "EBU":
case EBU:
return crc8.MakeTable(crc8.CRC8_EBU)
case "I-CODE":
case I_CODE:
return crc8.MakeTable(crc8.CRC8_I_CODE)
case "ITU":
case ITU:
return crc8.MakeTable(crc8.CRC8_ITU)
case "MAXIM":
case MAXIM:
return crc8.MakeTable(crc8.CRC8_MAXIM)
case "ROHC":
case ROHC:
return crc8.MakeTable(crc8.CRC8_ROHC)
case "WCDMA":
case WCDMA:
return crc8.MakeTable(crc8.CRC8_WCDMA)
default:
return crc8.MakeTable(crc8.CRC8)
@@ -37,35 +53,35 @@ func hasherSelect(table string) *crc8.Table {
}
// 计算给定字节数组的CRC8校验和返回字节数组
func CRC8(data []byte, table ...string) []byte {
crcTable := append(table, "CRC8")
func CRC8(data []byte, mode ...CRC8Mode) []byte {
crcTable := append(mode, ORIGIN)
return []byte{crc8.Checksum(data, hasherSelect(crcTable[0]))}
}
// 计算给定字节数组的CRC8校验和返回十六进制字符串
func CRC8Hex(data []byte, table ...string) string {
return hex.EncodeToString(CRC8(data, table...))
func CRC8Hex(data []byte, mode ...CRC8Mode) string {
return hex.EncodeToString(CRC8(data, mode...))
}
// 计算指定文件的CRC8校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) {
func SumFile(file string, mode ...CRC8Mode) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
crcTable := append(table, "CRC8")
crcTable := append(mode, ORIGIN)
var buf = make([]byte, 0)
if _, err := f.Read(buf); err != nil {
return nil, err
return nil, fmt.Errorf("读取指定文件内容出错,%w", err)
}
return []byte{crc8.Checksum(buf, hasherSelect(crcTable[0]))}, nil
}
// 计算指定文件的CRC8校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) {
crc, err := SumFile(file, table...)
func SumFileHex(file string, mode ...CRC8Mode) (string, error) {
crc, err := SumFile(file, mode...)
if err != nil {
return "", err
}

View File

@@ -4,6 +4,7 @@ package md5
import (
"crypto/md5"
"encoding/hex"
"fmt"
"io"
"os"
)
@@ -24,13 +25,13 @@ func MD5Hex(data []byte) string {
func SumFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
hasher := md5.New()
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}

View File

@@ -4,6 +4,7 @@ package phash
import (
"encoding/binary"
"encoding/hex"
"fmt"
"image"
"os"
@@ -27,13 +28,13 @@ func HashHex(image image.Image) string {
func HashFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
img, _, err := image.Decode(f)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能解码指定图像文件,%w", err)
}
return Hash(img), nil
}

View File

@@ -4,6 +4,7 @@ package sha1
import (
"crypto/sha1"
"encoding/hex"
"fmt"
"io"
"os"
)
@@ -24,13 +25,13 @@ func Sha1Hex(data []byte) string {
func SumFile(file string) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
hasher := sha1.New()
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}

View File

@@ -4,6 +4,7 @@ package sha256
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
@@ -45,8 +46,7 @@ func Sha256_224Hex(data []byte) string {
// 根据给定位数计算一个字节数组的Sha256校验和返回字节数组。
func Sum256(data []byte, bitSize ...int) []byte {
length := append(bitSize, 256)
hasher := hasherSelect(length[0])
hasher := hasherSelect(append(bitSize, 256)[0])
hasher.Write(data)
return hasher.Sum(nil)
}
@@ -60,13 +60,13 @@ func Sum256Hex(data []byte, bitSize ...int) string {
func SumFile256(file string, bitSize ...int) ([]byte, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
hasher := hasherSelect(bitSize[0])
hasher := hasherSelect(append(bitSize, 256)[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}

View File

@@ -4,6 +4,7 @@ package sha512
import (
"crypto/sha512"
"encoding/hex"
"fmt"
"hash"
"io"
"os"
@@ -76,14 +77,14 @@ func Sum512Hex(data []byte, bitSize ...int) string {
func SumFile512(path string, bitSize ...int) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
return nil, fmt.Errorf("未能打开指定文件,%w", err)
}
defer f.Close()
length := append(bitSize, 512)
var hasher = hasherSelect(length[0])
if _, err := io.Copy(hasher, f); err != nil {
return nil, err
return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
}
return hasher.Sum(nil), nil
}

View File

@@ -0,0 +1,7 @@
package hail
type HailAlgorithmNotInitializedError struct{}
func (e *HailAlgorithmNotInitializedError) Error() string {
return "冰雹ID生成算法尚未初始化"
}

73
serial_code/hail/hail.go Normal file
View File

@@ -0,0 +1,73 @@
// 提供基于雪花ID生成算法改进的短日期短主机板冰雹ID生成算法
package hail
import (
"fmt"
"sync"
"time"
"archgrid.xyz/ag/toolsbox/types"
)
// 用于记录当前冰雹ID组成内容的数据结构
type _HailAlgorithm struct {
hostSerial int64
lastTimestamp int64
lastSequence int64
lock sync.Mutex
}
var hailAlgorithmInstance *_HailAlgorithm
// 获取当前已经完成初始化的冰雹ID生成算法实例如果尚未完成初始化则会返回未初始化的错误。
func Get() (*_HailAlgorithm, error) {
if hailAlgorithmInstance == nil {
return nil, &HailAlgorithmNotInitializedError{}
}
return hailAlgorithmInstance, nil
}
// 指定一个主机编号并完成冰雹ID生成算法的初始化。
func Initialize(hostSerial int64) {
hailAlgorithmInstance = &_HailAlgorithm{
hostSerial: hostSerial,
lastTimestamp: types.Timestamp(),
lastSequence: 0,
lock: sync.Mutex{},
}
}
// 返回一个可用的时间戳,如果主机发生了时间回拨,那么将等待一秒钟。
func (h *_HailAlgorithm) timestamp() int64 {
for {
timestamp := types.Timestamp()
if timestamp == h.lastTimestamp {
h.lastTimestamp = timestamp
return timestamp
} else if timestamp > h.lastTimestamp {
h.lastTimestamp = timestamp
h.lastSequence = 0
return timestamp
}
time.Sleep(1 * time.Second)
}
}
// 生成一个冰雹ID。
func (h *_HailAlgorithm) Generate() int64 {
h.lock.Lock()
defer h.lock.Unlock()
timestamp := h.timestamp()
h.lastSequence++
return (timestamp << 20) | ((h.hostSerial & 0xffff) << 16) | (h.lastSequence & 0xffff_ffff)
}
// 生成一个冰雹ID并将其转换为字符串。
func (h *_HailAlgorithm) GenerateString() string {
return fmt.Sprintf("%017d", h.Generate())
}
// 生成一个冰雹ID将其转换为字符串并附加指定的前缀
func (h *_HailAlgorithm) GeneratePrefixedString(prefix string) string {
return fmt.Sprintf("%s%s", prefix, h.GenerateString())
}