chore: clean code

This commit is contained in:
Hintay 2025-02-08 00:02:59 +09:00
parent 9cbbd429d9
commit 70f4f63524
No known key found for this signature in database
GPG key ID: 120FC7FF121F2F2D
3 changed files with 16 additions and 16 deletions

View file

@ -15,11 +15,11 @@ import (
)
const (
CacheKey = "sign"
CacheKey = "crypto"
timeout = 10 * time.Minute
)
type Sign struct {
type Params struct {
PrivateKey string `json:"-"`
PublicKey string `json:"public_key"`
}
@ -43,34 +43,34 @@ func GenerateRSAKeyPair() (privateKeyPEM, publicKeyPEM []byte, err error) {
// GetCryptoParams registers a new key pair in the cache if it doesn't exist
// otherwise, it returns the existing nonce and public key
func GetCryptoParams() (sign *Sign, err error) {
func GetCryptoParams() (params *Params, err error) {
// Check if the key pair exists in then cache
if sign, ok := cache.Get(CacheKey); ok {
return sign.(*Sign), nil
if value, ok := cache.Get(CacheKey); ok {
return value.(*Params), nil
}
// Generate a nonce = hash(publicKey)
privateKeyPEM, publicKeyPEM, err := GenerateRSAKeyPair()
if err != nil {
return nil, err
}
sign = &Sign{
params = &Params{
PrivateKey: string(privateKeyPEM),
PublicKey: string(publicKeyPEM),
}
cache.Set(CacheKey, sign, timeout)
cache.Set(CacheKey, params, timeout)
return
}
// Decrypt decrypts the data with the private key (nonce, paramEncrypted)
func Decrypt(paramEncrypted string) (data map[string]interface{}, err error) {
// Get sign params from cache
sign, ok := cache.Get(CacheKey)
// Get crypto params from cache
value, ok := cache.Get(CacheKey)
if !ok {
return nil, ErrTimeout
}
signParams := sign.(*Sign)
block, _ := pem.Decode([]byte(signParams.PrivateKey))
params := value.(*Params)
block, _ := pem.Decode([]byte(params.PrivateKey))
if block == nil {
return nil, fmt.Errorf("failed to decode PEM block containing private key")
}

View file

@ -19,7 +19,7 @@ var (
func EncryptedParams() gin.HandlerFunc {
return func(c *gin.Context) {
// 1. Read the encrypted payload
// read the encrypted payload
var encryptedReq struct {
EncryptedParams string `json:"encrypted_params"`
}
@ -29,14 +29,14 @@ func EncryptedParams() gin.HandlerFunc {
return
}
// 2. Decrypt the parameters (implement your decryption logic)
// decrypt the parameters
decryptedData, err := crypto.Decrypt(encryptedReq.EncryptedParams)
if err != nil {
c.AbortWithStatusJSON(http.StatusBadRequest, ErrDecryptionFailed)
return
}
// 3. Replace request body with decrypted data
// replace request body with decrypted data
newBody, _ := json.Marshal(decryptedData)
c.Request.Body = io.NopCloser(bytes.NewReader(newBody))
c.Request.ContentLength = int64(len(newBody))