schorsch-tech.de
Software, programming and stuff
Kernel Hash Funktionen wie SHA256
Wie nutzt man die Kernel Hash Funktionen wie etwa SHA256?
#include <unistd.h>
#include <string.h> // memcpy
#include <sys/socket.h>
#include <sys/sendfile.h>
#include <linux/if_alg.h>
#include <linux/socket.h>
#include <array>
#include <memory>
using sha256_t = std::array<unsigned char, 32>;
sha256_t sha256sum(int in, size_t buffer_size = 2048)
{
std::unique_ptr<char> buffer(new char[buffer_size]);
sha256_t digest;
struct sockaddr_alg sa;
sa.salg_family = AF_ALG;
memcpy(sa.salg_type, "hash", 5);
memcpy(sa.salg_name, "sha256", 7);
int i, sockfd, fd;
sockfd = socket(AF_ALG, SOCK_SEQPACKET, 0);
if (bind(sockfd, (struct sockaddr *)&sa, sizeof(sa)) < 0) {
perror("bind");
exit(EXIT_FAILURE);
}
fd = accept(sockfd, NULL, 0);
if (fd < 0) {
perror("accept");
exit(EXIT_FAILURE);
}
// "pipe" the in fd to the hash algorithm
int pos;
int bytes_read;
while ((bytes_read = read(in, buffer.get(), buffer_size)) > 0)
{
pos = 0;
while (pos < bytes_read)
{
int sent = send(fd, buffer.get()+pos, bytes_read-pos, MSG_MORE);
if (sent < 0)
{
perror("send");
exit(EXIT_FAILURE);
}
pos += wrote;
}
}
send(fd, nullptr, 0, 0); // "flush" the hash
pos = 0;
while (pos < sizeof(sha256_t))
{
int bytes = read(fd, digest.data()+pos, sizeof(sha256_t)-pos);
if (bytes < 0) {
perror("read");
exit(EXIT_FAILURE);
}
pos += bytes;
}
close(fd);
close(sockfd);
return digest;
}
int main(void)
{
sha256_t digest = sha256sum(STDIN_FILENO);
for (size_t i = 0; i < sizeof(sha256_t); i++) {
printf("%02x",digest[i]);
}
printf("\n");
return 0;
}
Categories
software
Permanent link to this post: https://www.schorsch-tech.de//posts/kernel-hash-funktionen-wie-sha256