mirror of
https://github.com/stasenso/sha256_c_client.git
synced 2026-10-25 17:13:37 +03:00
96 lines
2.3 KiB
C
96 lines
2.3 KiB
C
#include <stdint.h>
|
|
#include <stdlib.h>
|
|
#include <stdio.h>
|
|
#include <string.h>
|
|
|
|
#include "sha.h"
|
|
|
|
static void print_digest_words(const sha256_digest_t digest) {
|
|
for (int i = 0; i < 8; ++i) {
|
|
printf("%08x", digest[i]);
|
|
}
|
|
putchar('\n');
|
|
}
|
|
|
|
int main(void) {
|
|
char path[4096] = {0};
|
|
sha256_digest_t digest = {0};
|
|
|
|
if (fgets(path, (int)sizeof(path), stdin) == NULL) {
|
|
fprintf(stderr, "Failed to read file path from stdin\n");
|
|
return 1;
|
|
}
|
|
|
|
path[strcspn(path, "\r\n")] = '\0';
|
|
if (path[0] == '\0') {
|
|
fprintf(stderr, "Empty file path\n");
|
|
return 1;
|
|
}
|
|
|
|
FILE *fp = fopen(path, "rb");
|
|
if (fp == NULL) {
|
|
fprintf(stderr, "Failed to open file: %s\n", path);
|
|
return 1;
|
|
}
|
|
|
|
if (_fseeki64(fp, 0, SEEK_END) != 0) {
|
|
fprintf(stderr, "Failed to seek file end: %s\n", path);
|
|
fclose(fp);
|
|
return 1;
|
|
}
|
|
|
|
const long long file_size_ll = _ftelli64(fp);
|
|
if (file_size_ll < 0) {
|
|
fprintf(stderr, "Failed to get file size: %s\n", path);
|
|
fclose(fp);
|
|
return 1;
|
|
}
|
|
|
|
if (_fseeki64(fp, 0, SEEK_SET) != 0) {
|
|
fprintf(stderr, "Failed to seek file start: %s\n", path);
|
|
fclose(fp);
|
|
return 1;
|
|
}
|
|
|
|
const uint64_t full_size = (uint64_t)file_size_ll;
|
|
size_t alloc_size = (size_t)full_size;
|
|
if ((uint64_t)alloc_size != full_size) {
|
|
fprintf(stderr, "File is too large for this client: %s\n", path);
|
|
fclose(fp);
|
|
return 1;
|
|
}
|
|
if (alloc_size == 0) {
|
|
alloc_size = 1;
|
|
}
|
|
|
|
unsigned char *data = (unsigned char *)malloc(alloc_size);
|
|
if (data == NULL) {
|
|
fprintf(stderr, "Out of memory while reading: %s\n", path);
|
|
fclose(fp);
|
|
return 1;
|
|
}
|
|
|
|
if (full_size > 0) {
|
|
const size_t read_size = fread(data, 1, (size_t)full_size, fp);
|
|
if (read_size != (size_t)full_size) {
|
|
fprintf(stderr, "Failed to read file: %s\n", path);
|
|
free(data);
|
|
fclose(fp);
|
|
return 1;
|
|
}
|
|
}
|
|
fclose(fp);
|
|
|
|
void *rc = Sha256(data, full_size, full_size, digest, 1);
|
|
free(data);
|
|
if (rc != 0) {
|
|
fprintf(stderr, "Sha256 failed, rc=%p\n", rc);
|
|
return 1;
|
|
}
|
|
|
|
printf("Digest (library word order): ");
|
|
print_digest_words(digest);
|
|
|
|
return 0;
|
|
}
|