Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Reader activity
0 Useful 3 Views 22 min Read — No ratings
Backend Development
22 min read

AI Generates Sign/Verify in 1 Min — Why Production Java Engineering Still Matters

This article contrasts AI-generated signature verification code with production-grade Java implementation, detailing canonical string normalization, algorithm selection (HMAC/RSA/SM2), replay protection, key rotation, quality gates, and CI/CD practices to show where engineering value lies beyond code generation.

1. What AI Actually Saves — And What It Doesn't

Generating DTOs, signature utilities, and basic unit tests for a 30-field sign/verify flow takes AI about one minute and negligible cost. A senior engineer typically spends an hour. The difference is not typing speed.

The author breaks down a typical payment-gateway integration into six phases and estimates how much AI can replace:

Requirements Clarification — Field semantics, nullability, currency units, legacy protocols. AI replaceability: Rare — requires product and counter-party confirmation.

Contract Design — Sorting, encoding, null handling, nested structures, version rules. AI replaceability: Can draft, but cannot finalize agreement between parties.

Coding Implementation — DTOs, normalization, signature algorithms, basic tests. AI replaceability: Mostly.

Integration Verification — Packet capture, cross-language sign/verify, edge cases. AI replaceability: Can assist, cannot perceive real environment.

Security Hardening — Replay protection, key management, audit, idempotency. AI replaceability: Often misses critical constraints.

Release & Operations — Canary, monitoring, rollback, production debugging. AI replaceability: Ultimately remains the engineer's responsibility.

AI turns "writing code" into a commodity, but it does not bundle cross-team alignment, correctness proofs, or incident accountability. A ten-cent draft is not a delivery. When signatures break, the model won't join the 2 AM alert channel or the post-mortem.

2. Why AI's Draft "Runs But Can't Ship"

A typical AI-generated HMAC-SHA256 snippet:

public String sign(Map<String, Object> params, String secret) {
    String base = params.entrySet().stream()
            .map(e -> e.getKey() + "=" + e.getValue())
            .collect(Collectors.joining("&"));
    return DigestUtils.md5Hex(base + secret);
}

Even when AI adds sorting, the code hides a string of production accidents:

HashMap order unstable — Same data produces different signatures. Fix: Dictionary order or protocol-specified order.

null, empty string, missing field not distinguished — Both ends concatenate differently, verification fails sporadically or entirely. Fix: Encode null-handling policy into contract and tests.

"null" string treated as real value — Java vs frontend/PHP behavior diverges. Fix: Explicitly decide whether to filter; no implicit agreements.

Amount appears as 1, 1.0, 1.00 — Signature drift, even amount precision errors. Fix: BigDecimal fixed precision or unified zero-stripping.

Collections/objects directly toString() — JDK, library versions, and Map order cause instability. Fix: Canonical JSON or recursive normalization.

&, =, newline not escaped — Parameter boundaries become ambiguous. Fix: URL Encode or canonical JSON.

Chinese and space encoding inconsistent — UTF-8, GBK, +, %20 mixed. Fix: End-to-end UTF-8, unified encoding rules.

MD5 with key concatenation — Weak algorithm and insecure key usage. Fix: HMAC-SHA256, RSA, or SM2.

String.equals compares signatures — Timing side-channel risk. Fix: MessageDigest.isEqual.

No timestamp and nonce — Valid messages replayable indefinitely. Fix: Time window + atomic nonce deduplication.

Keys hard-coded or logged — Leak compromises all interfaces. Fix: KMS, HSM, Vault, or encrypted config.

No algorithm/key version — Algorithm or key change causes mass verification failures. Fix: signVersion, kid, and dual-verification transition.

Only returns "verification failed" — Production debugging becomes guesswork. Fix: Graded error codes, digest audit, distributed tracing.

New systems should use standard HMAC; don't invent your own MD5(data + secret).

AI outputs "code that most likely looks right"; engineering delivery demands "proven correct, with someone accountable".

AI's output ceiling depends on the completeness of constraints you feed it. Real counterparties often say: "Just follow industry standard," "Same as that old interface," "You write first, I'll check." Industry standards won't tell you that three years ago a merchant's extInfo was excluded from signing, and changing it now breaks all legacy merchants.

3. The Real Moat: Turning Ambiguous Requirements into Deterministic Contracts

An engineer's value isn't remembering one more HMAC API, but nailing down every vague question:

Is the request body JSON, Form, or Query?

Do all 30 fields participate in signing?

Whitelist or blacklist for signature fields?

Are sign, secret, privateKey explicitly excluded?

Field order by key dictionary or protocol-specified?

Nested objects recursive or only first level?

Arrays preserve order or sort?

Null values skipped or converted to empty string?

Timestamp in seconds or milliseconds?

Date to timestamp or ISO-8601?

Amount in yuan or fen, how many decimals?

URL encoding before or after concatenation?

How to support old clients?

Key leak, rotation, revocation — how handled?

These answers belong in interface docs, schemas, annotations, tests, and cross-language golden vectors — not chat logs.

3.1 Declare Field Rules in Code with Annotations

Instead of hand-concatenating 30 fields, let fields declare their own contract. A Java 17 @SignField annotation:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SignField {
    int order() default 0; // >0 = protocol order; all 0 = ASCII sort
    boolean required() default true; // reject if null
    boolean ignoreEmpty() default true; // skip null/empty, rule must be global
    boolean exclude() default false; // sensitive field exclusion must be in bilateral protocol
    Fmt fmt() default Fmt.RAW;
    enum Fmt { RAW, MONEY_2, TRIM, URL_ENCODE, EPOCH_SECOND, ISO_INSTANT }
}

Request model example:

public record PaySignRequest(
    @SignField(order = 1) String appId,
    @SignField(order = 2) String method,
    @SignField(order = 3) String nonce,
    @SignField(order = 4) long timestamp,
    @SignField(order = 5, fmt = SignField.Fmt.MONEY_2) BigDecimal amount,
    @SignField(order = 6, fmt = SignField.Fmt.TRIM) String merchantName,
    @SignField(order = 7, required = false) String extInfo,
    @SignField(exclude = true) String sensitivePlaintext,
    String sign
) {}

Security note: "Excluded from signing" does not mean "unprotected". If tamper-proofing is still needed, sign ciphertext, token, or irreversible digest — not plaintext.

3.2 Single Canonical String Exit for the Whole System

Signing and verification must reuse the same normalizer — no Stream on one side, StringBuilder on the other, hoping integration tests catch mismatches.

public final class SignNormalizer {
    private static final Map<Class<?>, List<Field>> CACHE = new ConcurrentHashMap<>();
    private static final ObjectMapper JSON = new ObjectMapper()
            .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS)
            .enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);

    public static String canonical(Object request) {
        return metadataOf(request.getClass()).stream()
                .map(field -> toPart(field, request))
                .filter(Objects::nonNull)
                .collect(Collectors.joining("&"));
    }

    private static List<Field> metadataOf(Class<?> type) {
        return CACHE.computeIfAbsent(type, SignNormalizer::resolveFields);
    }

    private static List<Field> resolveFields(Class<?> type) {
        List<Field> fields = new ArrayList<>();
        for (Class<?> c = type; c != null && c != Object.class; c = c.getSuperclass()) {
            for (Field field : c.getDeclaredFields()) {
                if (Modifier.isStatic(field.getModifiers()) || field.isSynthetic()) continue;
                SignField rule = field.getAnnotation(SignField.class);
                if (rule == null || rule.exclude()) continue;
                if (Set.of("sign", "secret", "privateKey").contains(field.getName())) continue;
                fields.add(field);
            }
        }
        boolean explicitOrder = fields.stream()
                .allMatch(f -> f.getAnnotation(SignField.class).order() > 0);
        if (explicitOrder) {
            fields.sort(Comparator.comparingInt(f -> f.getAnnotation(SignField.class).order()));
            long distinctOrders = fields.stream()
                    .map(f -> f.getAnnotation(SignField.class).order())
                    .distinct().count();
            if (distinctOrders != fields.size()) throw new IllegalStateException("duplicate sign order");
        } else {
            fields.sort(Comparator.comparing(Field::getName));
        }
        return List.copyOf(fields);
    }

    private static String toPart(Field field, Object request) {
        try {
            field.setAccessible(true);
            Object value = field.get(request);
            SignField rule = field.getAnnotation(SignField.class);
            if (value == null) {
                if (rule.required()) throw new IllegalArgumentException("missing sign field: " + field.getName());
                return null;
            }
            String text = format(value, rule.fmt());
            if (rule.ignoreEmpty() && (text.isBlank() || "null".equalsIgnoreCase(text))) return null;
            String encoded = rule.fmt() == SignField.Fmt.URL_ENCODE ? text : rfc3986(text);
            return rfc3986(field.getName()) + "=" + encoded;
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    private static String format(Object value, SignField.Fmt fmt) {
        return switch (fmt) {
            case MONEY_2 -> ((BigDecimal) value).setScale(2, RoundingMode.HALF_UP).toPlainString();
            case TRIM -> value.toString().strip().replace('\u3000', ' ');
            case URL_ENCODE -> rfc3986(value.toString());
            case EPOCH_SECOND -> {
                Instant instant = toInstant(value);
                yield String.valueOf(instant.getEpochSecond());
            }
            case ISO_INSTANT -> DateTimeFormatter.ISO_INSTANT.format(toInstant(value));
            case RAW -> normalizeRaw(value);
        };
    }

    private static String normalizeRaw(Object value) {
        if (value instanceof BigDecimal number) return number.stripTrailingZeros().toPlainString();
        if (value instanceof Number number) return new BigDecimal(number.toString()).stripTrailingZeros().toPlainString();
        if (value instanceof byte[] bytes) return Base64.getEncoder().encodeToString(bytes);
        if (value instanceof Enum<?> enumValue) return enumValue.name();
        if (value instanceof Map<?, ?> || value instanceof Collection<?>) {
            try { return JSON.writeValueAsString(value); } // Map keys sorted, Collection preserves order
            catch (JsonProcessingException e) { throw new IllegalStateException("bad sign value", e); }
        }
        return String.valueOf(value);
    }

    private static String rfc3986(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8)
                .replace("+", "%20")
                .replace("*", "%2A")
                .replace("%7E", "~");
    }

    private static Instant toInstant(Object value) {
        if (value instanceof Instant instant) return instant;
        if (value instanceof Date date) return date.toInstant();
        throw new IllegalArgumentException("unsupported date type");
    }
}

Key points:

Field order, required, null-handling, formatting, and sensitive-field rules explicitly declared. Parent-class fields extracted recursively; new fields don't require utility changes. Metadata cached by Class to avoid repeated reflection under high QPS. Money, dates, byte arrays, enums, collections, nested objects all have deterministic text forms. Encoding follows RFC 3986, avoiding Java URLEncoder's space-to-+. sign, keys, and private keys never enter the canonical string.

If startup performance or reflection access is a concern, APT + JavaPoet can generate SignMeta at compile time, but reflection metadata caching usually suffices — let load-test data decide before upgrading.

4. Algorithm Selection Isn't Memorizing Names — It's Business Trade-offs

Common schemes: HMAC, RSA, SM2. They differ in trust model, not sophistication.

HMAC-SHA256 — Advantage: Fast, simple, high-QPS friendly. Cost & Limitation: Shared key — verifier can forge, non-repudiation impossible. Fit: Internal services, trusted partners, payment channels.

RSA / RSA-PSS — Advantage: Private key signs, public key verifies — verifier cannot forge. Cost & Limitation: Higher compute, certificate & key lifecycle more complex. Fit: Multi-party public key distribution, non-repudiation needed.

SM2 + SM3 — Advantage: Meets national crypto compliance. Cost & Limitation: Many implementation details, cross-end encoding pitfalls. Fit: Government, finance, national-crypto migration.

HMAC is often orders of magnitude faster than RSA, but don't treat that as physics — implementation, key length, hardware all affect results. Always benchmark your own stack.

4.1 HMAC: Key Not in Canonical String, Instance Reuse Needs Thread Safety

public final class HmacSigner {
    private static final ThreadLocal<Mac> MAC = ThreadLocal.withInitial(() -> {
        try { return Mac.getInstance("HmacSHA256"); }
        catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
    });

    public String sign(String content, byte[] secret) {
        try {
            Mac mac = MAC.get();
            mac.init(new SecretKeySpec(secret, "HmacSHA256"));
            byte[] bytes = mac.doFinal(content.getBytes(StandardCharsets.UTF_8));
            return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
        } catch (InvalidKeyException e) { throw new IllegalStateException("sign failed", e); }
    }

    public boolean verify(String expected, String actual) {
        if (actual == null) return false;
        return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), actual.getBytes(StandardCharsets.UTF_8));
    }
}

Mac is not thread-safe; a global singleton shared across threads is unsafe. ThreadLocal reduces object creation but must be evaluated against thread-pool lifecycle; creating a new Mac per call may not be a bottleneck. If output is Hex, normalize case before compare; if Base64, case matters.

4.2 RSA, SM2: Algorithm Must Be Allow-listed

Asymmetric signing abstracted to a unified strategy:

public final class AsymmetricSigner {
    public static String sign(Object request, PrivateKey privateKey, String algorithm) throws GeneralSecurityException {
        String content = SignNormalizer.canonical(request);
        Signature signature = Signature.getInstance(algorithm);
        signature.initSign(privateKey);
        signature.update(content.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(signature.sign());
    }

    public static boolean verify(Object request, PublicKey publicKey, String sign, String algorithm) throws GeneralSecurityException {
        String content = SignNormalizer.canonical(request);
        Signature signature = Signature.getInstance(algorithm);
        signature.initVerify(publicKey);
        signature.update(content.getBytes(StandardCharsets.UTF_8));
        return signature.verify(Base64.getDecoder().decode(sign));
    }
}

algorithm maps to allow-listed values:

SHA256withRSA

RSASSA-PSS with explicit PSS parameters

SM3withSM2 (usually with BouncyCastle)

Never accept algorithm name from the client. Server selects from allow-list based on signVersion to prevent downgrade attacks.

Three common SM2 pitfalls:

Signature output is DER-encoded or raw r || s.

userId default value — both sides must agree.

Public key format: compressed, uncompressed, with or without 04 prefix.

Pin these down upfront; Java self-tests may pass but counterpart verification fails. Encapsulate BouncyCastle utilities and prepare cross-language test vectors.

5. Replay Protection, Key Rotation, Idempotency — The Production Divide

Signing only proves "message unaltered, key holder present". It does not prove "this request should execute once". An attacker can replay a captured packet; the signature remains valid. Real systems need three layers:

timestamp: limit request validity window.

nonce: ensure each random number consumed once.

Business idempotency key: prevent duplicate charges/orders from retries.

Critical detail: appId, kid, signVersion, timestamp, nonce must themselves be included in the canonical string. Otherwise an attacker can modify these security parameters and bypass replay protection or key routing.

5.1 Consume Nonce Only After Verification Succeeds

public record SignEnvelope(&
    String appId,
    String kid,
    String signVersion,
    long timestamp,
    String nonce,
    String sign
) {}
public record VerifyResult(boolean ok, String reason) {}
public final class SignVerifier {
    private static final long WINDOW_SECONDS = 300;
    private final KeyProvider keyProvider;
    private final StringRedisTemplate redis;
    private final AuditLogger audit;

    public VerifyResult verify(Object request, SignEnvelope env) {
        long now = Instant.now().getEpochSecond();
        if (Math.abs(now - env.timestamp()) > WINDOW_SECONDS) return failed(env, "STALE");

        String canonical = SignNormalizer.canonical(request)
                + "&appId=" + env.appId()
                + "&kid=" + env.kid()
                + "&signVersion=" + env.signVersion()
                + "&timestamp=" + env.timestamp()
                + "&nonce=" + env.nonce();

        boolean valid = false;
        try {
            for (byte[] secret : keyProvider.verificationSecrets(env.appId(), env.kid())) {
                String expected = HmacSigner.sign(canonical, secret);
                if (MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), Objects.toString(env.sign(), "").getBytes(StandardCharsets.UTF_8))) {
                    valid = true; break;
                }
            }
        } catch (UnknownKeyVersionException e) { return failed(env, "KEY_VERSION_INVALID"); }
        if (!valid) return failed(env, "BAD_SIGN");

        // Consume nonce AFTER verification — prevents attacker from burning legitimate nonce with bad signature
        String nonceKey = "sign:nonce:" + env.appId() + ":" + env.nonce();
        Boolean first = redis.opsForValue().setIfAbsent(nonceKey, "1", Duration.ofMinutes(6)); // TTL > time window
        if (!Boolean.TRUE.equals(first)) return failed(env, "REPLAY");

        audit.success(env.appId(), env.kid(), env.signVersion());
        return new VerifyResult(true, "OK");
    }

    private VerifyResult failed(SignEnvelope env, String reason) {
        audit.failure(env.appId(), env.kid(), env.signVersion(), reason);
        return new VerifyResult(false, reason);
    }
}

Order matters:

Check time window first — fast reject expired requests.

Verify signature — confirm nonce comes from legitimate message.

Atomically consume nonce with Redis SET NX EX.

Business layer continues with order/idempotency key check.

If you write nonce first, an attacker can forge bad signatures to occupy legitimate nonces, causing denial of service. Local ConcurrentHashMap or Caffeine works for single instance; multi-instance requires Redis with appId scope.

5.2 Key Rotation: "Sign With New, Verify With Old"

public interface KeyProvider {
    byte[] activeSecret(String appId); // signing uses only active version
    List<byte[]> verificationSecrets(String appId, String kid); // verification accepts current + previous
}

Smooth rotation steps:

New requests start using v2 signatures.

Verifier accepts both v2 and v1 during transition.

Canary by appId and kid batches.

Observe a full release cycle until old requests vanish.

Retire old key, keep emergency rollback capability.

Keys sourced from KMS, HSM, Vault, or encrypted config center, with local cache and hot reload. Private keys never leave KMS/HSM; keys never in Git, plaintext config, or logs. Dual-signature transition must define how both signatures and versions are carried — verifier must not iterate unlimited historical keys, or performance and governance spiral.

6. Performance, Compatibility, Debuggability — Determines How Long This Code Survives

Functional test pass is just the start. Production issues emerge under high concurrency, legacy clients, and "intermittent failures".

6.1 Performance Optimization by Data, Not Gut Feeling

Reflection overhead — Parse List<SignMeta> at startup, cache immutable metadata by Class. Caveat: No repeated getDeclaredFields() on hot path.

HMAC instance — ThreadLocal<Mac> or per-call creation per benchmark. Caveat: Mac not thread-safe.

Key retrieval — Short-term local cache for KMS keys. Caveat: Must support revocation, hot reload, expiry refresh.

String concatenation — Pre-size StringBuilder (e.g., 256) for 30 fields. Caveat: Micro-optimization, don't over-obsess.

Serialization — Avoid duplicate JSON parse and re-normalization. Caveat: Nested structure rules must be stable.

RSA verification — Load-test, connection pools, result caching, capacity planning. Caveat: Cache key must include full context — never cache a security hole.

Monitoring tasks — Audit, metrics async. Caveat: Security verification itself cannot be async to "allow-then-check".

6.2 Legacy Compatibility — Don't Just Watch Unit Tests Pass

Version both protocol and keys:

signVersion: determines normalization rules and algorithm.

kid: determines key version.

appId: isolates each integration's historical contracts.

Before launch, replay sanitized production traffic — run old and new implementations on the same real requests, compare signatures and verification results. Deploy via "shadow diff → 1% canary → phased rollout → full", keeping a rollback switch. Shadow diff's value: surfaces "undocumented legacy quirks" early. Full-width spaces, GBK legacy payloads, semantic difference between missing field and empty string — ordinary unit tests rarely imagine these.

6.3 Verification Failures Must Be Explainable, But Not an Attack Oracle

At minimum distinguish:

STALE: request expired

REPLAY: duplicate request

BAD_SIGN: signature mismatch

KEY_VERSION_INVALID: key version error

SIGN_VERSION_UNSUPPORTED: algorithm/protocol version unsupported

MISSING_SIGN_FIELD: required sign field absent

Internal logs capture traceId, appId, kid, signVersion, error code, latency, field digest; optionally sample sanitized canonical string or per-field hashes. External responses can be coarser to prevent attackers probing field-by-field.

Log red line: never print keys, private keys, full sensitive payloads, or unsanitized canonical strings. Debuggability comes from traceable digests and graded error codes — not dumping secrets into ELK.

During integration, provide an internal self-service verification tool: paste parameters, get canonical string, rule version, signature result. Cross-team sign/verify often shrinks from hours to minutes. Tool must be authenticated, sanitized, and forbid production private keys.

7. AI Code Into Main Branch? Pass These Gates First

The stronger AI gets, the more valuable the validation system. Otherwise AI gives you ten versions in an hour; by the time you review the eleventh, you've forgotten why the first was right.

7.1 Turn Requirements into Executable Contracts

@Test
void signContractIsExecutableSpec() {
    var fields = Arrays.stream(ApiSignReq.class.getDeclaredFields())
            .filter(f -> f.isAnnotationPresent(SignField.class))
            .toList();
    assertThat(fields).hasSize(30); // 30 business fields must all participate
    assertThat(fields.stream()
            .map(f -> f.getAnnotation(SignField.class).order())
            .filter(order -> order > 0)
            .distinct())
            .hasSize(30); // explicit order no duplicates
    assertThat(fields).noneMatch(f -> Set.of("sign", "secret", "privateKey").contains(f.getName()));
}
@Test
void dtoMustMatchSchema() {
    Schema doc = Schema.load("sign-api-v3.json");
    assertThat(Arrays.stream(SignRequest.class.getDeclaredFields())
            .map(Field::getName)
            .toList())
            .allSatisfy(name -> assertThat(doc.field(name)).as(name).isNotNull());
}

If security fields (appId/kid/timestamp/nonce) are fixed before business fields, assert "30 business fields + 4 security fields = 34 sign items" to prevent AI from dropping replay parameters.

7.2 Golden Vectors: All Languages Share One Correct Answer

@Test
void goldenVector() {
    Map<String, Object> params = new LinkedHashMap<>();
    params.put("amount", new BigDecimal("100.00"));
    params.put("currency", "CNY");
    params.put("timestamp", 1700000000L);
    String actual = signer.sign(params, "test-secret");
    assertThat(actual).isEqualTo(snapshot.read("pay-sign-v1.golden"));
}

Golden vectors frozen after human review; Java, Go, Node, PHP, frontend all use them. Field order, UTF-8, space encoding, money precision, date format, nested JSON, array order — any AI change turns the test red. Separate cases for normal, null, Chinese, special chars, timeout, bad signature, old key, new key, illegal algorithm, duplicate nonce.

7.3 Property-Based Testing: Verify Invariants, Not Just Examples

@Property
void signIsStableUnderKeyOrder(@ForAll Map<String, Object> params) {
    String a = signer.sign(shuffledCopy(params), TEST_SECRET);
    String b = signer.sign(params, TEST_SECRET);
    assertThat(a).isEqualTo(b).as("Signature must not depend on field insertion order");
}
@Property
void tamperedParamMustFail(@ForAll Map<String, Object> params) {
    String sign = signer.sign(params, TEST_SECRET);
    Map<String, Object> tampered = new HashMap<>(params);
    tampered.put("amount", "0.01");
    assertThat(signer.verify(tampered, sign, TEST_SECRET)).isFalse();
}

Golden vectors ensure "matches this standard answer"; property tests ensure "no matter how input perturbs, security properties hold". They complement, not replace.

7.4 CI Quality Gates in Practice

ai-quality-gate:
  script:
    - mvn -q verify -Pcontract-test
    - mvn -q test -Dtest=ArchUnitRules
    - mvn -q jacoco:check
    - gitleaks detect
    - mvn sonar:sonar -Dsonar.qualitygate.wait=true

Five gates solve:

Contract tests: 30 fields, order, encoding, schema — no drift.

ArchUnit: business code cannot bypass unified crypto, key, verification modules.

JaCoCo: incremental coverage threshold, e.g., ≥80%.

Gitleaks: zero secrets leakage.

SonarQube: cyclomatic complexity, security hotspots, quality gate.

80% coverage ≠ security correctness. It's a baseline. Security code needs critical branches, attack cases, and cross-language consistency verification.

8. Integrate AI Into the Pipeline, Not as a Code Wish-Granter

Current workflow: AI is a lightning-fast, unstable intern; the engineer is its Tech Lead.

This collaboration flow has three iron laws:

Spec first. Write field rules and golden cases first, then let AI write implementation; reverse the order and it can only guess.

AI artifacts don't go straight to canary. Must pass automated gates, human review, and shadow traffic diff.

Failure must be explainable. Error codes, traces, digest audit, and rollback plan — not a single "verification failed" to debug.

Human review need not distribute effort evenly. DTOs and boilerplate can be scanned quickly; focus on:

Signature scope completeness

Null, money, array, encoding rule changes

Timestamp and nonce included in signature

Nonce consumed atomically

Key leakage or incorrect rotation

New compatibility and release risks

9. The Programmer's Moat Is Shifting from "Code Output" to These Five Things

1. Problem Definition: Translate Fuzzy Requirements into Precise Spec

Includes requirements clarification, domain modeling, interface contracts, historical context untangling. AI can complete code from local context, but doesn't know which historical baggage must not be touched, nor will it proactively pull product, counterparty, and security teams to clarify ambiguities.

2. Architectural Decisions: Trade-offs Within Constraints

HMAC or RSA? Performance, non-repudiation, compliance — which priority? Keys in KMS or config center? Support legacy clients? These aren't if-else; they're trade-offs among cost, performance, security, extensibility, and organizational constraints.

3. Quality Safety Net: Turn "Looks Right" into "System Proves Right"

Contract tests, golden vectors, property tests, dual-run diff, canary, rollback, observability — all turn personal experience into team assets. Getting it right once isn't skill; six months later adding the 31st field, swapping algorithm, rotating keys, and not breaking it — that's engineering capability.

4. Production Ownership: Willing to Sign for the Result

Online wrong accounts, erroneous approvals, key leaks, system avalanches — responsibility ultimately lands on engineers and teams. Being accountable, able to locate issues, organize recovery, and turn post-mortems into mechanisms — this capability won't depreciate because tokens got cheaper.

5. AI Engineering: Not Just Calling LLM APIs

Java developers moving toward AI don't necessarily need to train models. Closer-to-business capabilities include:

Prompt, Spec, and context engineering

RAG integration of signature specs, historical interfaces, domain knowledge

Agent orchestration of code generation, regression testing, integration flow

Building eval sets for continuous model output assessment

Output schema validation, guardrails, tool allow-lists

Preventing prompt injection, tool call escalation, sensitive data leakage

Tracing, cost, latency, and model effectiveness monitoring

It's not one person using AI to write fast; it's the whole team locking AI's uncertainty into a deterministic software engineering system.

10. Practical Advice: Don't Race AI on Typing Speed — Move Upstream and Downstream

Individuals can do three things now:

Hand CRUD, DTOs, utilities, test drafts, doc generation to AI.

Invest saved time into requirements clarification, security, distributed systems, high concurrency, performance tuning, stability engineering.

Train review skills — especially spotting boundary omissions, security flaws, compatibility risks.

Teams should gradually build:

Unified interface and signature specifications

Reusable signing/verification scaffolding

Schema, contract tests, golden vector library

Unit tests, architecture checks, security scans, coverage gates

Sanitized replay, dual-run diff, canary rollback, monitoring audit

Back to the opening interview question, I'd close with:

AI writes sign/verify in one minute, proving coding is being commoditized. But the programmer's real moat is defining correctness, verifying correctness, controlling release, and owning the final outcome. AI turns "implementation" into a commodity, and raises judgment and engineering closure into scarce goods. The future danger isn't people who can't use AI — it's people who can't tell where AI went wrong.

For attribution, corrections or content rights, contactadmin@besthub.dev

Report an issue with this article

Discussion 0

Write a comment

Sign in to join the discussion

No public comments on this page. Sign in to comment