Compare commits

9 Commits

19 changed files with 672 additions and 33 deletions

View File

@@ -3,7 +3,7 @@
Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能:
- 加解密算法
- [ ] 螺旋随机密钥自解密算法
- [x] 螺旋随机密钥自解密算法
- [x] AES-CBC 便捷加解密算法
- [x] No Padding
- [x] ZerosPadding
@@ -12,15 +12,16 @@ Golang 中可以使用的常用辅助功能工具箱。主要配备以下功能
- [x] No Padding
- [x] ZerosPadding
- [x] Pkcs7Padding
- [ ] 3DES-CBC 便捷加解密算法
- [ ] No Padding
- [ ] ZerosPadding
- [ ] Pkcs7Padding
- [ ] RSA 加解密算法
- [ ] 1024 位长
- [ ] 2048 位长
- [ ] KeyPair 生成器
- [ ] RSA 签名算法
- [x] 3DES-CBC 便捷加解密算法
- [x] No Padding
- [x] ZerosPadding
- [x] Pkcs7Padding
- [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,7 +37,7 @@ 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[:]
@@ -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[:]

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,56 @@
// 提供自定义的随机密钥自解密加密算法支持算法代号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"
)
// 根据给定的密钥字符串生成加解密使用的密钥。
func generateKey(key string) []byte {
keyBytes := sha512.Sha512([]byte(key))
return keyBytes[4:36]
}
// 对给定的数据进行加密。
func Encrypt(data string) (string, error) {
key := verifyCode.RandStr(20)
keyBytes := generateKey(key)
cipherData, err := aes.Encrypt([]byte(data), keyBytes, encryption.PKCS7Padding)
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) (string, error) {
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)
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,6 +3,7 @@ package crc16
import (
"encoding/hex"
"fmt"
"io"
"os"
@@ -44,14 +45,14 @@ func CRC16Hex(data []byte, table ...string) string {
func SumFile(file string, table ...string) ([]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")
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
}

View File

@@ -3,6 +3,7 @@ package crc32
import (
"encoding/hex"
"fmt"
"hash/crc32"
"io"
"os"
@@ -39,14 +40,14 @@ func CRC32Hex(data []byte, table ...string) string {
func SumFile(file string, table ...string) ([]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")
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
}

View File

@@ -3,6 +3,7 @@ package crc64
import (
"encoding/hex"
"fmt"
"hash/crc64"
"io"
"os"
@@ -37,14 +38,14 @@ func CRC64Hex(data []byte, table ...string) string {
func SumFile(file string, table ...string) ([]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")
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
}

View File

@@ -3,6 +3,7 @@ package crc8
import (
"encoding/hex"
"fmt"
"os"
"github.com/sigurn/crc8"
@@ -51,14 +52,14 @@ func CRC8Hex(data []byte, table ...string) string {
func SumFile(file string, table ...string) ([]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")
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
}

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"
@@ -60,13 +61,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])
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())
}