Compute the SHA-256 of a file in-process (no external hashing tool — those * differ per OS, may be absent, and mis-quote paths under cmd.exe). Writes a * 64-char hex digest + NUL to out. Returns 0 on success. Not static: * exercised directly by the self-update checksum regression test. */
| 7018 | * 64-char hex digest + NUL to out. Returns 0 on success. Not static: |
| 7019 | * exercised directly by the self-update checksum regression test. */ |
| 7020 | int cbm_cli_sha256_file(const char *path, char *out, size_t out_size) { |
| 7021 | if (out_size < SHA256_BUF_SIZE) { |
| 7022 | return CLI_ERR; |
| 7023 | } |
| 7024 | FILE *fp = cbm_fopen(path, "rb"); |
| 7025 | if (!fp) { |
| 7026 | return CLI_ERR; |
| 7027 | } |
| 7028 | cbm_sha256_ctx ctx; |
| 7029 | cbm_sha256_init(&ctx); |
| 7030 | unsigned char buf[CLI_BUF_1K]; |
| 7031 | size_t n; |
| 7032 | while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) { |
| 7033 | cbm_sha256_update(&ctx, buf, n); |
| 7034 | } |
| 7035 | int read_err = ferror(fp); |
| 7036 | fclose(fp); |
| 7037 | if (read_err) { |
| 7038 | return CLI_ERR; |
| 7039 | } |
| 7040 | uint8_t digest[CBM_SHA256_DIGEST_LEN]; |
| 7041 | cbm_sha256_final(&ctx, digest); |
| 7042 | static const char hex[] = "0123456789abcdef"; |
| 7043 | for (int i = 0; i < CBM_SHA256_DIGEST_LEN; i++) { |
| 7044 | out[i * 2] = hex[digest[i] >> 4]; |
| 7045 | out[i * 2 + 1] = hex[digest[i] & 0x0f]; |
| 7046 | } |
| 7047 | out[SHA256_HEX_LEN] = '\0'; |
| 7048 | return 0; |
| 7049 | } |
| 7050 | |
| 7051 | static int cli_checksum_hex_nibble(unsigned char value) { |
| 7052 | if (value >= (unsigned char)'0' && value <= (unsigned char)'9') { |