Skill: kaiyuelv/encoding-converter (version 1.0.0)

# encoding-converter ## 技能概述 多格式编码转换工具集。支持 Base64、URL 编码、HEX、MD5/SHA 哈希、JWT 解码、HTML 实体编码等常见编码格式的互转与校验。 ## 何时使用 - 需要 Base64 编码/解码数据时 - 需要 URL encode/decode 文本时 - 需要计算文件或字符串的 MD5/SHA 哈希时 - 需要解码 JWT Token 查看 payload 时 - 需要 HTML 实体编码/解码时 - 需要进行进制转换（二进制/八进制/十进制/十六进制）时 ## 使用方法 ### 基础用法 ```python from scripts.encoding_engine import EncodingConverter ec = EncodingConverter() # Base64 编解码 encoded = ec.base64_encode("Hello World") decoded = ec.base64_decode(encoded) # URL 编码 url_encoded = ec.url_encode("你好 世界") # MD5 / SHA256 哈希 md5_hash = ec.md5("secret data") sha256_hash = ec.sha256("secret data") # JWT 解码（不验证签名） payload = ec.jwt_decode("eyJhbGciOiJIUzI1NiIs...") # HTML 实体编码 html = ec.html_encode("<div>Hello & 你好</div>") # 进制转换 hex_val = ec.to_hex(255) # -> "ff" bin_val = ec.to_binary(255) # -> "11111111" ``` ## 文件结构 ``` encoding-converter/ ├── SKILL.md ├── README.md ├── requirements.txt ├── scripts/ │ └── encoding_engine.py # 核心引擎 ├── examples/ │ └── basic_usage.py # 使用示例 └── tests/ └── test_encoding.py # 单元测试 ``` ## 依赖 - Python 内置: `base64`, `urllib.parse`, `hashlib`, `html`, `json`, `binascii` - 可选: `PyJWT` 用于 JWT 编码 ## 标签 encoding, decoding, base64, hash, jwt, developer-tools, security

path: README.md
content: # Encoding Converter

多格式编码转换工具 — 开发调试必备 Swiss Army Knife。

## Features

| 功能 | 说明 |
|------|------|
| Base64 | 编码 / 解码，支持 URL-safe 变体 |
| URL 编码 | encode / decode，支持空格处理 |
| HEX | 字符串与十六进制互转 |
| 哈希 | MD5, SHA1, SHA256, SHA512 |
| JWT 解码 | 解析 header + payload（不验证签名） |
| HTML 实体 | encode / decode |
| 进制转换 | 二/八/十/十六进制互转 |
| 随机生成 | UUID、随机字符串、随机十六进制 |

## Quick Start

```python
from scripts.encoding_engine import EncodingConverter

ec = EncodingConverter()

# Base64
ec.base64_encode("Hello")           # -> "SGVsbG8="
ec.base64_decode("SGVsbG8=")        # -> "Hello"

# URL
eq.url_encode("key=你好 world")      # -> "key%3D%E4%BD%A0%E5%A5%BD+world"

# 哈希
ec.md5("password")                  # -> "5f4dcc3b5aa765d61d8327deb882cf99"
ec.sha256("password")               # -> "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8"

# JWT 解码
ec.jwt_decode("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c")
# -> {"header": {"alg": "HS256", "typ": "JWT"}, "payload": {"sub": "1234567890", "name": "John Doe", "iat": 1516239022}}

# 进制转换
ec.to_hex(255)                      # -> "ff"
ec.to_binary(255)                   # -> "11111111"
ec.hex_to_int("ff")                 # -> 255

# HTML
eq.html_encode("<script>")         # -> "&lt;script&gt;"

# 随机生成
ec.random_uuid()                    # -> "550e8400-e29b-41d4-a716-446655440000"
ec.random_hex(16)                   # -> "a3f7c9d2e8b1045f"
```

## Installation

```bash
pip install -r requirements.txt
```

纯 Python 内置模块实现，无需额外依赖即可运行核心功能。

## License
MIT

path: examples/basic_usage.py
content: """
Encoding Converter - 基础使用示例
"""
from scripts.encoding_engine import EncodingConverter


def main():
    ec = EncodingConverter()

    print("=" * 50)
    print("示例 1: Base64 编解码")
    print("=" * 50)
    original = "Hello World 你好世界"
    encoded = ec.base64_encode(original)
    decoded = ec.base64_decode(encoded)
    print(f"原文: {original}")
    print(f"Base64 编码: {encoded}")
    print(f"Base64 解码: {decoded}")

    print("\n" + "=" * 50)
    print("示例 2: URL 编码")
    print("=" * 50)
    text = "key=你好 world&value=测试"
    encoded = ec.url_encode(text)
    decoded = ec.url_decode(encoded)
    print(f"原文: {text}")
    print(f"URL 编码: {encoded}")
    print(f"URL 解码: {decoded}")

    print("\n" + "=" * 50)
    print("示例 3: 哈希计算")
    print("=" * 50)
    data = "password123"
    print(f"MD5:    {ec.md5(data)}")
    print(f"SHA1:   {ec.sha1(data)}")
    print(f"SHA256: {ec.sha256(data)}")

    print("\n" + "=" * 50)
    print("示例 4: JWT 解码")
    print("=" * 50)
    # 示例 JWT token
    [REDACTED_SECRET]"
    decoded = ec.jwt_decode(token)
    print(f"JWT [REDACTED_SECRET]")
    print(f"解码结果: {decoded}")

    print("\n" + "=" * 50)
    print("示例 5: 进制转换")
    print("=" * 50)
    num = 255
    print(f"十进制: {num}")
    print(f"二进制: {ec.to_binary(num)}")
    print(f"八进制: {ec.to_octal(num)}")
    print(f"十六进制: {ec.to_hex(num)}")
    print(f"十六进制还原: {ec.hex_to_int('ff')}")

    print("\n" + "=" * 50)
    print("示例 6: HTML 实体编码")
    print("=" * 50)
    html_text = "<div>Hello & 你好</div>"
    encoded = ec.html_encode(html_text)
    decoded = ec.html_decode(encoded)
    print(f"原文: {html_text}")
    print(f"编码: {encoded}")
    print(f"解码: {decoded}")

    print("\n" + "=" * 50)
    print("示例 7: 随机生成")
    print("=" * 50)
    print(f"UUID: {ec.random_uuid()}")
    print(f"随机 HEX: {ec.random_hex(16)}")
    print(f"随机字符串: {ec.random_string(16)}")


if __name__ == "__main__":
    main()


path: requirements.txt
content: # 纯 Python 内置模块，无硬性依赖
# 可选增强：
# PyJWT>=2.8.0


path: scripts/encoding_engine.py
content: """
Encoding Converter - 多格式编码转换工具引擎
"""
import base64
import urllib.parse
import hashlib
import html
import json
import binascii
import uuid
import secrets
from typing import Dict, Any, Optional, Union


class EncodingConverter:
    """支持 Base64、URL 编码、哈希、JWT 解码、HTML 实体、进制转换的工具集"""

    def base64_encode(self, data: Union[str, bytes], url_safe: bool = False) -> str:
        """Base64 编码"""
        if isinstance(data, str):
            data = data.encode('utf-8')
        if url_safe:
            return base64.urlsafe_b64encode(data).decode('utf-8').rstrip('=')
        return base64.b64encode(data).decode('utf-8')

    def base64_decode(self, data: str, url_safe: bool = False) -> str:
        """Base64 解码"""
        if url_safe:
            # 补齐 padding
            padding = 4 - len(data) % 4
            if padding != 4:
                data += '=' * padding
            decoded = base64.urlsafe_b64decode(data)
        else:
            decoded = base64.b64decode(data)
        return decoded.decode('utf-8') if isinstance(decoded, bytes) else decoded

    def url_encode(self, text: str, safe: str = '') -> str:
        """URL 编码"""
        return urllib.parse.quote(text, safe=safe)

    def url_decode(self, text: str) -> str:
        """URL 解码"""
        return urllib.parse.unquote(text)

    def to_hex(self, data: Union[str, int, bytes]) -> str:
        """转换为十六进制表示"""
        if isinstance(data, int):
            return hex(data)[2:]
        if isinstance(data, str):
            return data.encode('utf-8').hex()
        if isinstance(data, bytes):
            return data.hex()
        return str(data)

    def from_hex(self, hex_string: str) -> str:
        """十六进制字符串还原为文本"""
        try:
            return bytes.fromhex(hex_string).decode('utf-8')
        except (ValueError, UnicodeDecodeError):
            return hex_string

    def hex_to_int(self, hex_string: str) -> int:
        """十六进制转整数"""
        return int(hex_string, 16)

    def to_binary(self, num: int) -> str:
        """整数转二进制字符串"""
        return bin(num)[2:]

    def from_binary(self, binary: str) -> int:
        """二进制字符串转整数"""
        return int(binary, 2)

    def to_octal(self, num: int) -> str:
        """整数转八进制字符串"""
        return oct(num)[2:]

    def from_octal(self, octal: str) -> int:
        """八进制字符串转整数"""
        return int(octal, 8)

    def md5(self, data: Union[str, bytes]) -> str:
        """计算 MD5 哈希"""
        if isinstance(data, str):
            data = data.encode('utf-8')
        return hashlib.md5(data).hexdigest()

    def sha1(self, data: Union[str, bytes]) -> str:
        """计算 SHA1 哈希"""
        if isinstance(data, str):
            data = data.encode('utf-8')
        return hashlib.sha1(data).hexdigest()

    def sha256(self, data: Union[str, bytes]) -> str:
        """计算 SHA256 哈希"""
        if isinstance(data, str):
            data = data.encode('utf-8')
        return hashlib.sha256(data).hexdigest()

    def sha512(self, data: Union[str, bytes]) -> str:
        """计算 SHA512 哈希"""
        if isinstance(data, str):
            data = data.encode('utf-8')
        return hashlib.sha512(data).hexdigest()

    def hmac_sha256(self, key: Union[str, bytes], message: Union[str, bytes]) -> str:
        """计算 HMAC-SHA256"""
        import hmac
        if isinstance(key, str):
            key = key.encode('utf-8')
        if isinstance(message, str):
            message = message.encode('utf-8')
        return hmac.new(key, message, hashlib.sha256).hexdigest()

    def jwt_decode(self, token: str) -> Dict[str, Any]:
        """解码 JWT Token（不验证签名）"""
        try:
            parts = token.split('.')
            if len(parts) != 3:
                return {"error": "Invalid JWT format"}

            def decode_part(part: str) -> Dict:
                # 补齐 padding
                padding = 4 - len(part) % 4
                if padding != 4:
                    part += '=' * padding
                decoded = base64.urlsafe_b64decode(part)
                return json.loads(decoded)

            return {
                "header": decode_part(parts[0]),
                "payload": decode_part(parts[1]),
                "signature": parts[2],
            }
        except Exception as e:
            return {"error": str(e)}

    def html_encode(self, text: str) -> str:
        """HTML 实体编码"""
        return html.escape(text)

    def html_decode(self, text: str) -> str:
        """HTML 实体解码"""
        return html.unescape(text)

    def random_uuid(self) -> str:
        """生成随机 UUID"""
        return str(uuid.uuid4())

    def random_hex(self, length: int = 32) -> str:
        """生成随机十六进制字符串"""
        return secrets.token_hex(length // 2 if length % 2 == 0 else (length + 1) // 2)[:length]

    def random_string(self, length: int = 16) -> str:
        """生成随机安全字符串"""
        import string
        alphabet = string.ascii_letters + string.digits
        return ''.join(secrets.choice(alphabet) for _ in range(length))

    def crc32(self, data: Union[str, bytes]) -> str:
        """计算 CRC32 校验值"""
        import zlib
        if isinstance(data, str):
            data = data.encode('utf-8')
        return format(zlib.crc32(data) & 0xffffffff, '08x')


path: tests/test_encoding.py
content: """
Encoding Converter 单元测试
"""
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))

from scripts.encoding_engine import EncodingConverter


def test_base64():
    ec = EncodingConverter()
    original = "Hello World"
    encoded = ec.base64_encode(original)
    decoded = ec.base64_decode(encoded)
    assert decoded == original

    # URL-safe
    encoded_safe = ec.base64_encode(original, url_safe=True)
    decoded_safe = ec.base64_decode(encoded_safe, url_safe=True)
    assert decoded_safe == original
    print("✓ test_base64 passed")


def test_url_encoding():
    ec = EncodingConverter()
    text = "hello world"
    encoded = ec.url_encode(text)
    decoded = ec.url_decode(encoded)
    assert decoded == text
    print("✓ test_url_encoding passed")


def test_hex():
    ec = EncodingConverter()
    assert ec.to_hex(255) == "ff"
    assert ec.hex_to_int("ff") == 255
    assert ec.to_hex("ABC") == "414243"
    assert ec.from_hex("414243") == "ABC"
    print("✓ test_hex passed")


def test_binary():
    ec = EncodingConverter()
    assert ec.to_binary(255) == "11111111"
    assert ec.from_binary("11111111") == 255
    print("✓ test_binary passed")


def test_hash():
    ec = EncodingConverter()
    data = "test"
    assert len(ec.md5(data)) == 32
    assert len(ec.sha1(data)) == 40
    assert len(ec.sha256(data)) == 64
    assert len(ec.sha512(data)) == 128
    # 一致性检查
    assert ec.md5(data) == ec.md5(data)
    print("✓ test_hash passed")


def test_jwt_decode():
    ec = EncodingConverter()
    [REDACTED_SECRET]"
    result = ec.jwt_decode(token)
    assert "error" not in result
    assert result["header"]["alg"] == "HS256"
    assert result["payload"]["name"] == "John Doe"
    print("✓ test_jwt_decode passed")


def test_html_encoding():
    ec = EncodingConverter()
    text = "<div>Hello & 你好</div>"
    encoded = ec.html_encode(text)
    decoded = ec.html_decode(encoded)
    assert "&lt;" in encoded
    assert decoded == text
    print("✓ test_html_encoding passed")


def test_random():
    ec = EncodingConverter()
    uuid1 = ec.random_uuid()
    uuid2 = ec.random_uuid()
    assert uuid1 != uuid2
    assert len(ec.random_hex(16)) == 16
    assert len(ec.random_string(16)) == 16
    print("✓ test_random passed")


def test_hmac():
    ec = EncodingConverter()
    result = ec.hmac_sha256("key", "message")
    assert len(result) == 64
    print("✓ test_hmac passed")


if __name__ == "__main__":
    test_base64()
    test_url_encoding()
    test_hex()
    test_binary()
    test_hash()
    test_jwt_decode()
    test_html_encoding()
    test_random()
    test_hmac()
    print("\n所有测试通过! ✅")


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: clean (LOW)