chovy-3012 commented on issue #13377:
URL: https://github.com/apache/seatunnel/issues/13377#issuecomment-7066866340
Thanks @DanielLeens for the quick triage and the precise gate. Below is the
proposed contract — no code until this is agreed.
## Proposed signatures
```
SM4_ENCRYPT(value, key[, iv]) -> BINARY
SM4_DECRYPT(ciphertext, key[, iv]) -> STRING
```
This refines the signatures sketched in the issue: with the envelope pinned
down, the encrypt result is raw ciphertext bytes, so the return type is BINARY;
the decrypt side accepts BINARY ciphertext and returns the decrypted UTF-8
plaintext as STRING. The names mirror the existing `AES_ENCRYPT` /
`AES_DECRYPT` / `DES_ENCRYPT` family, and the mode, IV and key handling mirror
the merged `AES_ENCRYPT` / `AES_DECRYPT` contract in `CryptoFunction`.
## Usage examples
```sql
-- 2-arg form: a fresh random IV per call, returned as the IV || ciphertext
prefix.
-- For a 16-byte value: 48 raw bytes (16 IV + 32 ciphertext) -> 64 Base64
chars.
SELECT TO_BASE64(SM4_ENCRYPT(phone, 'base64:MDEyMzQ1Njc4OWFiY2RlZg==')) AS
phone_cipher FROM orders;
-- TO_BASE64 only bridges to text columns / display; the function itself
returns BINARY.
-- 2-arg decrypt: the IV is recovered from the prefix — no third argument
needed.
SELECT SM4_DECRYPT(FROM_BASE64(phone_cipher),
'base64:MDEyMzQ1Njc4OWFiY2RlZg==') FROM orders;
-- -> the original UTF-8 text. A raw BINARY column is passed directly,
without FROM_BASE64.
-- 3-arg form: the caller supplies the 16-byte IV; the output is the bare
ciphertext,
-- byte-for-byte interchangeable with any conforming external SM4/CBC system.
SELECT TO_BASE64(SM4_ENCRYPT(phone, 'base64:MDEyMzQ1Njc4OWFiY2RlZg==',
'1234567890123456')) FROM orders;
-- For a 16-byte value: 32 ciphertext bytes only -> 44 Base64 chars.
SELECT SM4_DECRYPT(FROM_BASE64(phone_cipher),
'base64:MDEyMzQ1Njc4OWFiY2RlZg==', '1234567890123456') FROM orders;
-- Passphrase key: derived via a single unsalted SHA-256, first 16 bytes.
-- The same form must be used to decrypt; the two key forms are not
interchangeable.
SELECT SM4_ENCRYPT(phone, 'order-pipeline-key') FROM orders;
```
## 1. The contract, argument by argument
The five elements requested — mode, padding rule, IV layout, key-input rule
and envelope — are all pinned below, organized by argument so the contract
reads the way the function is actually used.
| Argument | Contract | Example |
|---|---|---|
| `value` | For `SM4_ENCRYPT`: a scalar string, encrypted as UTF-8. For
`SM4_DECRYPT`: a BINARY ciphertext. NULL → NULL out. Non-scalar (array/map)
input → error. Binary-to-binary encryption is out of scope for v1. |
`SM4_ENCRYPT('', key)` is valid and round-trips (padding always emits one full
block); a map or array value → error. |
| `key` | Two accepted forms, not interchangeable. A `base64:` prefix →
Base64-decoded raw key, which must decode to exactly 16 bytes (SM4 is 128-bit
only, no 192/256 variants) — the length is validated, never silently
zero-padded or folded to fit. Any other input is a passphrase, derived via a
single unsalted SHA-256 using the first 16 bytes — the same derivation AES
uses. Derived keys are cached (bounded, like the AES key cache) so a constant
key is derived once, not per row. Docs will recommend random `base64:` keys for
strong protection. | `'base64:MDEyMzQ1Njc4OWFiY2RlZg=='` decodes to the 16
ASCII bytes of `0123456789abcdef` and is used as the raw key.
`'order-pipeline-key'` is a passphrase: one unsalted SHA-256, first 16 digest
bytes. A `base64:` key that decodes to 8 or 32 bytes → error, not a padded or
folded key. |
| `iv` (optional) | Omitted: a fresh random 16-byte IV is generated per call
and returned as the `IV ‖ ciphertext` prefix — no built-in or fixed IV is ever
used, and `SM4_DECRYPT` (2-arg) recovers it from that prefix with no third
argument. Supplied: must be exactly 16 bytes, measured in UTF-8 bytes —
anything shorter or longer is an error, never silently adjusted. An explicit
`NULL` IV is rejected, so a column of mixed NULL/non-NULL IVs cannot silently
produce two different layouts. | `SM4_ENCRYPT(v, k)` called twice → two
different BINARY values, yet both decrypt with just `SM4_DECRYPT(value, k)`.
`SM4_ENCRYPT(v, k, '1234567890123456')` → the same 32 bytes on every call —
deterministic, caller-owned. A 10-byte IV → error. |
| mode | There is no mode argument and no session-level mode switch: the
transformation is fixed at `SM4/CBC/PKCS5Padding` — the same mode family as the
shipped `AES/CBC/PKCS5Padding`. No ECB in v1: ECB is per-block deterministic
and leaks plaintext equality, and we do not want a weaker default than the
existing AES family. | PKCS#5 always pads to the next 16-byte boundary: a
16-byte value encrypts to 32 ciphertext bytes, an empty string to 16. CBC
chains every block through the previous one, so a repeated plaintext block
never yields a repeated ciphertext block. |
| Return value (envelope) | Raw binary — the long-standing SQL convention
for block-cipher functions (`aes_encrypt` in MySQL and Hive also returns raw
ciphertext bytes), with the existing `TO_BASE64()` / `FROM_BASE64()` available
for display and for text-column storage. The 3-arg form emits plain
`SM4/CBC/PKCS#5` bytes (PKCS#5 and PKCS#7 padding are identical for a 16-byte
block), so values interoperate with any conforming SM4/CBC implementation with
no proprietary envelope to strip. `AES_ENCRYPT` keeps its merged envelope
unchanged, so no existing behavior shifts. | 2-arg on a 16-byte value → a
48-byte BINARY `IV ‖ ciphertext`; `TO_BASE64()` renders it as 64 chars for a
VARCHAR column and `FROM_BASE64()` restores the BINARY for decryption. The
3-arg form returns just the bare 32 ciphertext bytes. |
| Failure semantics | Only a NULL input value yields NULL. Every failure —
NULL or blank key, a `base64:` key of the wrong length, an explicit NULL IV,
non-scalar input, a STRING passed where binary ciphertext is expected,
malformed ciphertext — is an explicit error; failures are never signaled by
silently returning NULL. | `key = ''` → error; a Base64 STRING fed to
`SM4_DECRYPT` → an error pointing at `FROM_BASE64()` first; a ciphertext
shorter than the 16-byte IV prefix → error. |
The boundaries, made precise for the corner cases users will actually hit:
- **Empty value**: `SM4_ENCRYPT('', key)` is valid — PKCS#5 padding always
emits at least one full block, so the result is a well-formed 16-byte
ciphertext that decrypts back to the empty string.
- **Encrypt input type**: the value to encrypt must be a scalar string,
encoded as UTF-8; a BINARY value is rejected — binary-to-binary encryption
stays out of scope for v1.
- **Explicit IV length**: the explicit IV must be exactly 16 bytes, measured
in UTF-8 bytes — a multi-byte string is accepted as long as it encodes to
exactly 16 bytes; anything shorter or longer is an error.
- **Malformed `base64:` key**: a `base64:` key whose remainder is not valid
Base64, or does not decode to exactly 16 bytes, is an error — the same
validation the AES functions apply.
- **Malformed ciphertext layout**: 2-arg decrypt rejects input shorter than
the 16-byte IV prefix; every decrypt rejects an empty ciphertext and a
ciphertext portion whose length is not a multiple of the 16-byte block size —
reported as errors, not garbage.
- **Garbage that passes the padding check**: in the documented ~1/256
wrong-key case the decrypted bytes need not be valid UTF-8; they are decoded
with the same lenient charset behavior the existing functions use (invalid
sequences replaced), not an extra throw.
## 2. Provider / packaging plan
A pure-Java implementation of the SM4 block cipher per GB/T 32907-2016
(fixed S-box and linear transforms, ~300 lines, written from the public
standard — no third-party code) inside the existing transforms-v2 module. **No
new dependency, no shading, no licensing impact.** This is why we prefer it
over BouncyCastle: BC would add a new third-party dependency (and
shading/conflict review) to deliver an algorithm whose standard is public and
self-contained. The block layer will be exercised by the standard's published
test vectors.
## 3. Engine exposure
Same registration point as `AES_ENCRYPT`: function-name constants plus
dispatch in `ZetaSQLFunction` (`computeForValue`), evaluated inside the SQL
Transform itself; the BINARY return uses the evaluator's existing bytes→BINARY
handling. No per-engine UDF registrations.
## 4. Secret handling
SM4 will follow the convention already documented and enforced for AES:
exception messages and logs carry only non-sensitive metadata (argument count,
byte length, type name) and never the key, derived key material, plaintext,
ciphertext, or IV — the shared `CommonError.illegalArgument` pattern.
## 5. Acceptance mapping
- **Fixed-IV published test vectors**: the worked example published in GB/T
32907-2016 Annex A as a known-answer test for the block layer, plus fixed
key/IV triples for the CBC function layer asserted on raw bytes.
- **Generated-IV round trips**: encrypt (2-arg) → decrypt (2-arg) over
multiple rows.
- **Raw and `base64:` 16-byte key validation**: valid raw key accepted;
non-16-byte decoded length rejected; passphrase form accepted and round-trips.
- **Null handling**: NULL value → NULL; NULL/blank key → error; explicit
NULL IV → error.
- **Malformed/tampered ciphertext**: non-binary input, ciphertext shorter
than the 16-byte IV prefix, empty ciphertext, a ciphertext portion not a
multiple of the 16-byte block size, corrupted padding → error, not garbage. One
caveat, documented the same way as for AES: CBC is unauthenticated, so a wrong
key or tampered ciphertext may (~1/256) still decrypt to garbage instead of
throwing.
- **Wrong-key failure**: decrypting with a different key fails (error, or
the documented garbage case).
- **EN/ZH documentation**: both languages updated with the function entries,
key/IV conventions, the two envelope layouts (2-arg vs 3-arg), and the
`TO_BASE64()` display note.
If this contract looks right, I'll open the implementation PR against it.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]