fix api
This commit is contained in:
parent
01b8951dd5
commit
10ebc59ffb
17 changed files with 1087 additions and 238 deletions
68
crypto/token.go
Normal file
68
crypto/token.go
Normal file
|
@ -0,0 +1,68 @@
|
|||
package crypto
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
)
|
||||
|
||||
// TokenEncryptor 用于加密和解密令牌的结构体
|
||||
type TokenEncryptor struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
// NewTokenEncryptor 创建一个新的TokenEncryptor实例
|
||||
func NewTokenEncryptor(key []byte) (*TokenEncryptor, error) {
|
||||
if len(key) != 32 {
|
||||
return nil, fmt.Errorf("key must be 32 bytes")
|
||||
}
|
||||
return &TokenEncryptor{key: key}, nil
|
||||
}
|
||||
|
||||
// EncryptTokenSecret 加密令牌密钥
|
||||
func (te *TokenEncryptor) EncryptTokenSecret(secret string) (string, error) {
|
||||
block, err := aes.NewCipher(te.key)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating cipher: %v", err)
|
||||
}
|
||||
|
||||
plaintext := []byte(secret)
|
||||
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
||||
return "", fmt.Errorf("error generating IV: %v", err)
|
||||
}
|
||||
|
||||
stream := cipher.NewCFBEncrypter(block, iv)
|
||||
stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
|
||||
|
||||
return base64.StdEncoding.EncodeToString(ciphertext), nil
|
||||
}
|
||||
|
||||
// DecryptTokenSecret 解密令牌密钥
|
||||
func (te *TokenEncryptor) DecryptTokenSecret(encrypted string) (string, error) {
|
||||
ciphertext, err := base64.StdEncoding.DecodeString(encrypted)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error decoding base64: %v", err)
|
||||
}
|
||||
|
||||
block, err := aes.NewCipher(te.key)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("error creating cipher: %v", err)
|
||||
}
|
||||
|
||||
if len(ciphertext) < aes.BlockSize {
|
||||
return "", fmt.Errorf("ciphertext too short")
|
||||
}
|
||||
|
||||
iv := ciphertext[:aes.BlockSize]
|
||||
ciphertext = ciphertext[aes.BlockSize:]
|
||||
|
||||
stream := cipher.NewCFBDecrypter(block, iv)
|
||||
stream.XORKeyStream(ciphertext, ciphertext)
|
||||
|
||||
return string(ciphertext), nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue