# Crypto


<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## PKCS#7 填充

WeCom 使用 AES-256-CBC
加密，要求明文长度为块大小（32字节）的整数倍。[`_pkcs7_pad`](https://TheSecondStep.github.io/solveit_wxbot/crypto.html#_pkcs7_pad)
在末尾追加填充字节，[`_pkcs7_unpad`](https://TheSecondStep.github.io/solveit_wxbot/crypto.html#_pkcs7_unpad)
则将其还原。

## 消息签名

WeCom 通过对若干字段排序后拼接再 SHA1
哈希来验证请求来源。[`msg_sig`](https://TheSecondStep.github.io/solveit_wxbot/crypto.html#msg_sig)
封装了这一逻辑，供 URL 验证和消息接收两处复用。

------------------------------------------------------------------------

<a
href="https://github.com/TheSecondStep/solveit_wxbot/blob/main/solveit_wxbot/crypto.py#L29"
target="_blank" style="float:right; font-size:smaller">source</a>

### msg_sig

``` python

def msg_sig(
    parts:str, # Strings to sort, concatenate, and SHA1-hash
)->str:

```

*WeCom message signature: sort `parts`, join, and return SHA1 hex
digest.*

## 加解密

[`decrypt`](https://TheSecondStep.github.io/solveit_wxbot/crypto.html#decrypt)
将 WeCom 下发的 Base64 密文还原为 XML 明文和企业
ID；[`encrypt`](https://TheSecondStep.github.io/solveit_wxbot/crypto.html#encrypt)
则将明文 XML 加密为 Base64，用于被动回复。两者均使用 AES-256-CBC，IV
取自 `AES_KEY` 前16字节。

------------------------------------------------------------------------

<a
href="https://github.com/TheSecondStep/solveit_wxbot/blob/main/solveit_wxbot/crypto.py#L45"
target="_blank" style="float:right; font-size:smaller">source</a>

### encrypt

``` python

def encrypt(
    xml:str, # Plaintext XML to encrypt for a WeCom passive reply
)->str:

```

*Encrypt `xml` using AES-256-CBC for WeCom; returns a Base64 string.*

------------------------------------------------------------------------

<a
href="https://github.com/TheSecondStep/solveit_wxbot/blob/main/solveit_wxbot/crypto.py#L36"
target="_blank" style="float:right; font-size:smaller">source</a>

### decrypt

``` python

def decrypt(
    encrypted:str, # Base64-encoded AES-256-CBC ciphertext from WeCom
)->tuple:

```

*Decrypt a WeCom message; returns `(xml_text, corp_id)`.*
