package chapa import ( "bytes" "crypto/des" "encoding/base64" "encoding/json" "errors" "fmt" "strings" ) var ErrChapaEncryptionNotConfigured = errors.New("chapa encryption key is not configured") func encryptChapaDirectChargePayload(encryptionKey, requestID, otp string) (string, error) { key, err := decodeTripleDESKey(encryptionKey) if err != nil { return "", err } payload, err := json.Marshal(map[string]string{ "requestID": requestID, "otp": otp, }) if err != nil { return "", fmt.Errorf("marshal chapa encrypt payload: %w", err) } encrypted, err := tripleDESECBEncrypt(key, payload) if err != nil { return "", err } return base64.StdEncoding.EncodeToString(encrypted), nil } func decodeTripleDESKey(raw string) ([]byte, error) { raw = stringsTrim(raw) if raw == "" { return nil, ErrChapaEncryptionNotConfigured } if decoded, err := base64.StdEncoding.DecodeString(raw); err == nil && len(decoded) == 24 { return decoded, nil } key := []byte(raw) if len(key) < 24 { padded := make([]byte, 24) copy(padded, key) return padded, nil } if len(key) > 24 { return key[:24], nil } return key, nil } func tripleDESECBEncrypt(key, plaintext []byte) ([]byte, error) { block, err := des.NewTripleDESCipher(key) if err != nil { return nil, fmt.Errorf("invalid chapa 3des key: %w", err) } padded := pkcs7Pad(plaintext, block.BlockSize()) out := make([]byte, len(padded)) for i := 0; i < len(padded); i += block.BlockSize() { block.Encrypt(out[i:i+block.BlockSize()], padded[i:i+block.BlockSize()]) } return out, nil } func pkcs7Pad(data []byte, blockSize int) []byte { if blockSize <= 0 { return data } padLen := blockSize - (len(data) % blockSize) if padLen == 0 { padLen = blockSize } padding := bytes.Repeat([]byte{byte(padLen)}, padLen) return append(append([]byte(nil), data...), padding...) } func stringsTrim(s string) string { return strings.TrimSpace(s) }