Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Crypto Sm Laravel Package

pohoc/crypto-sm

pohoc/crypto-sm is a PHP/Laravel package for working with SM cryptographic algorithms, offering helpers for encryption, hashing, and secure data handling. It provides a simple, framework-friendly API for integrating Chinese crypto standards into your applications.

View on GitHub
Deep Wiki
Context7

Getting Started

Install and lock the version — pre-1.0 crypto packages should be pinned, not floated:

composer require your-vendor/gm-crypto:"~0.3.0"

Check the README for the required PHP version and math backend (pure-PHP SM2/SM3 typically want gmp or bcmath); verify with php -m on every environment, including CI and your queue workers, since a missing extension usually surfaces as a fatal error on the first sign/verify call rather than at boot.

Look at these in order:

  1. src/ — map the SM2 / SM3 / SM4 / key-exchange entry points you actually need. Ignore the rest on day one.
  2. tests/ — the release adds GM/T official-vector tests and GM/T 0003.3 Appendix A key-exchange examples. Read those tests as executable documentation of correct parameter usage; they encode the calling conventions the README glosses over.
  3. CHANGELOG.md / deprecation list — v0.3.0 starts issuing runtime deprecation notices for APIs slated for removal in the next major.

First use case, and the most common one in a Laravel app: verifying an inbound SM2-signed request from a Chinese partner (payment gateway, bank, or government API). Wrap the package in one service class, bind it as a singleton, and inject it into a middleware or form request:

// app/Services/GmCryptoService.php
final class GmCryptoService
{
    public function verify(string $payload, string $signatureHex, string $peerPublicKey): bool
    {
        // delegate to the package's SM2 verify; normalize signature format first
    }
}

Do not call the package directly from controllers — you want one seam to change when the deprecations land.

Implementation Patterns

Config + container binding, not env(). Put curve parameters, default signature encoding (ASN.1 vs raw r||s), and key sources in config/gm.php, bind the service as a singleton, and resolve keys at call time. Anything calling env() in package-adjacent code breaks under php artisan config:cache.

Model cast for SM4-encrypted columns. Mirror Laravel's encrypted cast so PII/financial fields are transparent:

protected function casts(): array
{
    return ['id_number' => Sm4Encrypted::class];
}

Use SM4-GCM (newly correct — see Gotchas) for new data: it gives you authentication, so tampering fails loudly instead of decrypting to garbage. Reserve SM4-CCM (new in 0.3.0) for counterparties or hardware that specify it.

SM2 signing for outbound calls. Sign a canonical string (sorted params + timestamp + nonce), not the raw JSON, and include the timestamp in the signed payload to prevent replay. Store the counterparty's compressed public key if that's what they publish — v0.3.0 adds compressed-key import, which matters for QR codes, certificates with size limits, and partner onboarding docs that ship only the 33-byte form. Be explicit about signature encoding: ASN.1 DER for partners that expect OpenSSL-style output, raw r||s for those that expect fixed-length hex. Make it a config value per integration.

Key exchange for session keys. With GM/T 0003.3 key exchange now implemented and vector-tested, you can negotiate a session key with a bank/UnionPay-style endpoint instead of shipping a static SM4 key. Keep the exchange inside a single job/service — both sides must derive the same key from the same transcript, so any retry, reordering, or parallel call on the same ephemeral key will desync.

HMAC-SM3 for webhook signatures. Verify with hash_equals(), never ===. Reject when the timestamp skew exceeds a few minutes.

Queue and job hygiene. Never serialize private keys into a job payload. Pass an identifier and resolve the key from config or a vault inside handle().

Testing. Fake your GmCryptoService in feature tests so suites stay fast — pure-PHP SM2 is slow. Keep a separate @group crypto test set that runs the package's official vectors against your wrapper, and assert round-trip encrypt/decrypt plus a negative case (tampered tag must throw).

Gotchas and Tips

The critical GHASH fix is a data-compatibility event, not just a bug fix. Before 0.3.0, SM4-GCM authentication tags did not conform to RFC 8998 due to GHASH domain mixing. Consequences: (a) ciphertext+tags produced by earlier versions may not verify on 0.3.0, and (b) any peer that copied the old behaviour will now fail against you. Inventory everything encrypted with SM4-GCM — DB columns, cached blobs, queued payloads, files, exported archives — and plan a decrypt-with-old / re-encrypt-with-new migration, or accept re-collection. Do this before deploying, because a decrypt failure at read time is a production incident, not a test failure. Coordinate the upgrade window with integration partners.

Treat the feat! marker seriously even at 0.x. Semver pre-1.0 permits breakage, and 0.3.0 deliberately added runtime deprecation notices (P3, pre-major cleanup). Run your suite with deprecations surfaced (E_ALL, and check storage/logs/laravel.log in staging) to enumerate exactly which calls you rely on, then migrate them now rather than at the next major.

Never reuse a GCM/CCM nonce. Generate a fresh random_bytes() IV per encryption, store it alongside the ciphertext, and never derive it from a counter you can reset. Note the changelog's own admission that the benchmark script had GCM IV reuse — if you copy patterns from benchmarks/, do not copy the IV handling.

Bench before you trust published numbers. The docs release explicitly corrects "distorted performance data," which tells you prior figures were unreliable. Re-run the benchmark on your target PHP version and hardware before committing SM2/SM3 to a hot path. Pure-PHP SM2 verify is on the order of milliseconds — fine for a webhook, not fine for a tight loop or a per-row operation over 100k records. Batch, cache signatures, or move to an extension/HSM if you hit that wall.

Key parsing is expensive. Cache parsed key objects in the singleton; re-parsing a PEM/hex key on every request is the most common accidental cost in these integrations.

Don't use SM3 for passwords. It's a fast hash — use bcrypt/argon2 via Laravel's Hash facade. SM3 belongs in checksums, HMAC signatures, and KDF use.

Validate imported points. With compressed-public-key import new in this release, confirm the package rejects off-curve and invalid-subgroup points; assert a negative test yourself rather than assuming. Malicious keys in ECDH are a real attack class.

Error handling. Decryption/verification failures should throw, and you should catch and return a generic 4xx — don't echo library messages that leak tag or key details. Log the failure with a correlation ID only.

Keep the PHPUnit source config. The release added coverage source config to phpunit.xml. If you maintain a fork or a vendored patch (realistic for crypto packages awaiting upstream fixes), preserve it, or your coverage numbers silently go to zero.

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk
martialbe/flysystem-oss
chondal/3312client
jeroen-g/flickr
opscale-co/nova-genbi
itsjustvita/laravel-retention
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log