Compare commits
7 Commits
c083d6e8e0
...
v0.1.0
Author | SHA1 | Date | |
---|---|---|---|
|
5e284f320d | ||
|
b004e952c4 | ||
|
955d3a96f2 | ||
|
2e276ca33c | ||
|
3df5dbfd36 | ||
|
da4d1ebf3a | ||
|
14c5ff45cd |
15
README.md
15
README.md
@@ -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 生成器
|
||||
- 验证码生成器
|
||||
|
@@ -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)
|
||||
|
||||
|
@@ -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
67
encryption/rsa/errors.go
Normal 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
141
encryption/rsa/key.go
Normal 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
181
encryption/rsa/rsa.go
Normal 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{}
|
||||
}
|
||||
}
|
56
encryption/spiral/spiral.go
Normal file
56
encryption/spiral/spiral.go
Normal 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
|
||||
}
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
@@ -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
|
||||
}
|
||||
|
7
serial_code/hail/errors.go
Normal file
7
serial_code/hail/errors.go
Normal 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
73
serial_code/hail/hail.go
Normal 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())
|
||||
}
|
Reference in New Issue
Block a user