How to use kernel libcrc32c (or same functions) in userspace programmes?

前端 未结 1 1030
忘了有多久
忘了有多久 2021-02-02 02:29

I want to do some CRC check in my own userspace programme. And I find that the kernel crypto lib is already in the system, and come with SSE4.2 support.

I tried to direc

相关标签:
1条回答
  • 2021-02-02 03:04

    You can use kernel crypto CRC32c (and other hash/cipher functions) from user-space via socket family AF_ALG on Linux:

    #include <unistd.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <stdint.h>
    #include <sys/socket.h>
    #include <linux/if_alg.h>
    #include <sys/param.h>
    #include <string.h>
    #include <strings.h>
    
    int
    main (int argc, char **argv) {
    
        int sds[2] = { -1, -1 };
    
        struct sockaddr_alg sa = {
            .salg_family = AF_ALG,
            .salg_type   = "hash",
            .salg_name   = "crc32c"
        };
    
        if ((sds[0] = socket(AF_ALG, SOCK_SEQPACKET, 0)) == -1 )
            return -1;
    
        if( bind(sds[0], (struct sockaddr *) &sa, sizeof(sa)) != 0 )
            return -1;
    
        if( (sds[1] = accept(sds[0], NULL, 0)) == -1 )
            return -1;
    
        char *s = "hello";
        size_t n = strlen(s);
        if (send(sds[1], s, n, MSG_MORE) != n)
            return -1;
    
        int crc32c = 0x00000000;
        if(read(sds[1], &crc32c, 4) != 4)
            return -1;
    
        printf("%08X\n", crc32c);
        return 0;
    }
    

    If you're hashing files or socket data you can speed it up using zero-copy approach to avoid kernel -> user-space buffer copy with sendfile and/or splice.

    Happy coding.

    0 讨论(0)
提交回复
热议问题