69 lines
2.1 KiB
Go
69 lines
2.1 KiB
Go
package handler
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
const encryptedValuePrefixV1 = "enc:v1:"
|
|
|
|
type encryptRequest struct {
|
|
Plaintext string `json:"plaintext"`
|
|
Value string `json:"value"`
|
|
Message string `json:"message"`
|
|
}
|
|
|
|
// EncryptData encrypts a plaintext value and returns the ciphertext.
|
|
// @Summary Encrypt data
|
|
// @Description Encrypts a plaintext value and returns the ciphertext.
|
|
// @Tags crypto
|
|
// @Accept json
|
|
// @Produce json
|
|
// @Param payload body map[string]string true "Plaintext payload"
|
|
// @Success 200 {object} models.StatusMessageResponse "Ciphertext response"
|
|
// @Failure 400 {object} models.ErrorResponse "Invalid request"
|
|
// @Failure 500 {object} models.ErrorResponse "Server error"
|
|
// @Router /api/encrypt [post]
|
|
func (h *Handler) EncryptData(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
writeJSONError(w, http.StatusMethodNotAllowed, "method not allowed")
|
|
return
|
|
}
|
|
|
|
var req encryptRequest
|
|
if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, 4096)).Decode(&req); err != nil {
|
|
h.Logger.Error("unable to decode encrypt request", "error", err)
|
|
writeJSONError(w, http.StatusBadRequest, "invalid JSON body")
|
|
return
|
|
}
|
|
plaintext := strings.TrimSpace(req.Plaintext)
|
|
if plaintext == "" {
|
|
plaintext = strings.TrimSpace(req.Value)
|
|
}
|
|
if plaintext == "" {
|
|
plaintext = strings.TrimSpace(req.Message)
|
|
}
|
|
if plaintext == "" {
|
|
writeJSONError(w, http.StatusBadRequest, "plaintext is required (accepted keys: plaintext, value, message)")
|
|
return
|
|
}
|
|
|
|
cipherText, err := h.Secret.Encrypt([]byte(plaintext))
|
|
if err != nil {
|
|
h.Logger.Error("unable to encrypt payload", "error", err)
|
|
writeJSONError(w, http.StatusInternalServerError, "encryption failed")
|
|
return
|
|
}
|
|
|
|
h.Logger.Debug("encrypted plaintext payload", "input_length", len(plaintext))
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusOK)
|
|
_ = json.NewEncoder(w).Encode(map[string]string{
|
|
"status": "OK",
|
|
"message": cipherText,
|
|
"prefixed": encryptedValuePrefixV1 + cipherText,
|
|
"ciphertext": cipherText,
|
|
})
|
|
}
|