Compare commits

13 Commits

20 changed files with 797 additions and 97 deletions

View File

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

View File

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

View File

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

View File

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

102
encryption/tdes/tdes.go Normal file
View File

@@ -0,0 +1,102 @@
// 提供3DES-EDE加解密算法本解密算法采用`(K1, K2, K3)`的安全长密钥。
package tdes
import (
"crypto/cipher"
"crypto/des"
"crypto/sha256"
"fmt"
"archgrid.xyz/ag/toolsbox/encryption"
)
type KeyGenerator func([]byte) [3][8]byte
// 直接采用分组的方式将密钥分为4个部分取前三个部分作为3DES的密钥。
func PartitionKeyGenerator(key []byte) [3][8]byte {
hashedKey := sha256.Sum256(key)
return [3][8]byte{
([8]byte)(hashedKey[0:8]),
([8]byte)(hashedKey[8:16]),
([8]byte)(hashedKey[16:24]),
}
}
// 对给定密钥进行Sha256散列以后将散列结果分为三部分分别作为3DES的密钥前三组分别与第四组异或得到3组新的密钥。
func XorKeyGenerator(key []byte) [3][8]byte {
hashedKey := sha256.Sum256(key)
var result [3][8]byte
for i := 0; i < 3; i++ {
for j := 0; j < 8; j++ {
result[i][j] = hashedKey[i*8+j] ^ hashedKey[3*8+j]
}
}
return result
}
// 对给定的数据使用给定的密钥进行加密。IV与密钥相同。
func rawDesEncrypt(data []byte, key [8]byte) ([]byte, error) {
block, err := des.NewCipher(key[:])
if err != nil {
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := key[:]
cipherText := make([]byte, len(data))
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(cipherText, data)
return cipherText, nil
}
// 对给定的数据使用给定的密钥进行解密。IV与密钥相同。
func rawDesDecrypt(data []byte, key [8]byte) ([]byte, error) {
block, err := des.NewCipher(key[:])
if err != nil {
return nil, fmt.Errorf("创建加密单元失败,%w", err)
}
iv := key[:]
plainText := make([]byte, len(data))
mode := cipher.NewCBCDecrypter(block, iv)
mode.CryptBlocks(plainText, data)
return plainText, nil
}
// 对给定的数据进行加密。
// 3DES-EDE加密IV为8字节默认与运算后的密钥相同。
// 参数padding指定了填充方式可选值为NoPadding、ZeroPadding和PKCS7Padding默认采用ZeroPadding。
func Encrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerator ...KeyGenerator) ([]byte, error) {
desKeys := append(keyGenerator, XorKeyGenerator)[0](key)
plainText := encryption.Padding(data, des.BlockSize, padding)
cipher1Text, err := rawDesEncrypt(plainText, desKeys[0])
if err != nil {
return nil, fmt.Errorf("第一阶段加密失败,%w", err)
}
plain2Text, err := rawDesDecrypt(cipher1Text, desKeys[1])
if err != nil {
return nil, fmt.Errorf("第二阶段解密失败,%w", err)
}
cipher3Text, err := rawDesEncrypt(plain2Text, desKeys[2])
if err != nil {
return nil, fmt.Errorf("第三阶段加密失败,%w", err)
}
return cipher3Text, nil
}
// 对给定的数据进行解密。
// 3DES-EDE解密IV为8字节默认与运算后的密钥相同。
// 参数padding指定了填充方式可选值为NoPadding、ZeroPadding和PKCS7Padding默认采用ZeroPadding。
func Decrypt(data []byte, key []byte, padding encryption.PaddingMode, keyGenerator ...KeyGenerator) ([]byte, error) {
desKeys := append(keyGenerator, XorKeyGenerator)[0](key)
plainText, err := rawDesDecrypt(data, desKeys[2])
if err != nil {
return nil, fmt.Errorf("第三阶段解密失败,%w", err)
}
cipher2Text, err := rawDesEncrypt(plainText, desKeys[1])
if err != nil {
return nil, fmt.Errorf("第二阶段加密失败,%w", err)
}
plain3Text, err := rawDesDecrypt(cipher2Text, desKeys[0])
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 ( import (
"encoding/hex" "encoding/hex"
"fmt"
"io" "io"
"os" "os"
"github.com/howeyc/crc16" "github.com/howeyc/crc16"
) )
type CRC16Mode int
const (
CCITT CRC16Mode = iota
CCITT_FALSE
SCSI
IBM
MBUS
)
// 根据给定的校验表类型生成对应的校验器 // 根据给定的校验表类型生成对应的校验器
func hasherSelect(table string) crc16.Hash16 { func hasherSelect(mdoe CRC16Mode) crc16.Hash16 {
switch table { switch mdoe {
case "CCITT": case CCITT:
return crc16.NewCCITT() return crc16.NewCCITT()
case "CCITT-FALSE": case CCITT_FALSE:
return crc16.New(crc16.MakeTable(crc16.CCITTFalse)) return crc16.New(crc16.MakeTable(crc16.CCITTFalse))
case "SCSI": case SCSI:
return crc16.NewSCSI() return crc16.NewSCSI()
case "IBM": case IBM:
return crc16.NewIBM() return crc16.NewIBM()
case "MBUS": case MBUS:
return crc16.New(crc16.MakeTable(crc16.MBUS)) return crc16.New(crc16.MakeTable(crc16.MBUS))
default: default:
return crc16.NewIBM() return crc16.NewIBM()
@@ -28,37 +39,37 @@ func hasherSelect(table string) crc16.Hash16 {
} }
// 计算给定字节数组的CRC16校验和返回字节数组 // 计算给定字节数组的CRC16校验和返回字节数组
func CRC16(data []byte, table ...string) []byte { func CRC16(data []byte, mode ...CRC16Mode) []byte {
crcTable := append(table, "IBM") crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0]) hasher := hasherSelect(crcTable[0])
hasher.Write(data) hasher.Write(data)
return hasher.Sum(nil) return hasher.Sum(nil)
} }
// 计算给定字节数组的CRC16校验和返回十六进制字符串 // 计算给定字节数组的CRC16校验和返回十六进制字符串
func CRC16Hex(data []byte, table ...string) string { func CRC16Hex(data []byte, mode ...CRC16Mode) string {
return hex.EncodeToString(CRC16(data, table...)) return hex.EncodeToString(CRC16(data, mode...))
} }
// 计算指定文件的CRC16校验和返回字节数组 // 计算指定文件的CRC16校验和返回字节数组
func SumFile(file string, table ...string) ([]byte, error) { func SumFile(file string, mode ...CRC16Mode) ([]byte, error) {
f, err := os.Open(file) f, err := os.Open(file)
if err != nil { if err != nil {
return nil, err return nil, fmt.Errorf("未能打开指定文件,%w", err)
} }
defer f.Close() defer f.Close()
crcTable := append(table, "IBM") crcTable := append(mode, IBM)
hasher := hasherSelect(crcTable[0]) hasher := hasherSelect(crcTable[0])
if _, err := io.Copy(hasher, f); err != nil { if _, err := io.Copy(hasher, f); err != nil {
return nil, err return nil, fmt.Errorf("未能读取指定文件的内容,%w", err)
} }
return hasher.Sum(nil), nil return hasher.Sum(nil), nil
} }
// 计算指定文件的CRC16校验和返回十六进制字符串 // 计算指定文件的CRC16校验和返回十六进制字符串
func SumFileHex(file string, table ...string) (string, error) { func SumFileHex(file string, mode ...CRC16Mode) (string, error) {
hash, err := SumFile(file, table...) hash, err := SumFile(file, mode...)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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