java / intermediate
Snippet
Primitive Byte Array Chunking and Hashing in Spring Endpoints
Direct primitive array handling allows high-throughput binary processing. Iterating over fixed-size subarray slices using offset and length bounds computes digests efficiently without intermediate heap object allocations.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@RestController@RequestMapping("/api/chunks")public class ChunkProcessingController {@PostMapping("/checksum")public ResponseEntity<String> computeChecksum(@RequestBody byte[] rawPayload) {int chunkSize = 1024;int totalLength = rawPayload.length;MessageDigest digest = getSha256Digest();for (int offset = 0; offset < totalLength; offset += chunkSize) {int currentChunkLength = Math.min(chunkSize, totalLength - offset);digest.update(rawPayload, offset, currentChunkLength);}return ResponseEntity.ok(HexFormat.of().formatHex(digest.digest()));}private MessageDigest getSha256Digest() {try {return MessageDigest.getInstance("SHA-256");} catch (NoSuchAlgorithmException e) {throw new IllegalStateException("SHA-256 unavailable", e);}}}
spring
Breakdown
1
public ResponseEntity<String> computeChecksum(@RequestBody byte[] rawPayload) {
Receives raw binary payload directly as a primitive byte array without wrapper overhead.
2
for (int offset = 0; offset < totalLength; offset += chunkSize) {
Iterates through array segments in step increments defined by chunk size.
3
digest.update(rawPayload, offset, currentChunkLength);
Feeds specific subarray ranges directly into the cryptographic digest using array pointers.