/** * A simple program that loads a private key and a file and * outputs SHA1 signature of the file to the stdout. * * Written by Stjepan Gros . Use this * code as it suites you. */ #include #include #include #include gnutls_datum_t *load_file(const char *file) { FILE *f; size_t filelen, size; gpointer ptr = NULL; gnutls_datum_t *loaded_file = NULL; if ((f = fopen(file, "r")) != NULL) { if (fseek(f, 0, SEEK_END) != 0) { perror("fseek"); goto out; } if ((filelen = ftell(f)) < 0) { perror("ftell"); goto out; } if (fseek(f, 0, SEEK_SET) != 0) { perror("fseek"); goto out; } ptr = g_malloc(filelen); if ((size = fread(ptr, 1, filelen, f)) < filelen) { if (size < 0) perror("fread"); goto out; } loaded_file = g_malloc0(sizeof(gnutls_datum_t)); loaded_file->data = ptr; loaded_file->size = filelen; out: fclose(f); } else perror ("fopen"); return loaded_file; } void unload_file(gnutls_datum_t *file) { g_free(file->data); g_free(file); } void dump_hex(unsigned char *buf, size_t size) { int i, cols; unsigned int ch; for (i = 0, cols=0; i < size; i++, cols++) { if (cols == 16) { printf("\n"); cols = 0; } ch = (unsigned int)((unsigned char)buf[i] & 0xF0) >> 4; if (ch < 10) ch += '0'; else ch += 'A' - 10; printf("%c", ch); ch = (unsigned char)buf[i] & 0x0F; if (ch < 10) ch += '0'; else ch += 'A' - 10; printf("%c ", ch); } printf ("\n"); } #define SIGNATURE_MAX_SIZE 1024 int main(int argc, char **argv) { gnutls_x509_privkey_t privkey; gnutls_datum_t *key_file = NULL; gnutls_datum_t *data = NULL; unsigned char signature[SIGNATURE_MAX_SIZE]; size_t signature_size = SIGNATURE_MAX_SIZE; int ret; if (argc != 3) { fprintf (stderr, "Usage: %s \n", argv[0]); return 1; } if ((key_file = load_file(argv[1])) == NULL) return 1; gnutls_global_init(); gnutls_x509_privkey_init(&privkey); ret = gnutls_x509_privkey_import(privkey, key_file, GNUTLS_X509_FMT_PEM); unload_file(key_file); if (ret < 0) { fprintf(stderr, "Error: %s\n", gnutls_strerror(ret)); return 1; } if ((data = load_file(argv[2])) == NULL) return 1; ret = gnutls_x509_privkey_sign_data(privkey, GNUTLS_MAC_SHA1, 0, data, signature, &signature_size); if (ret < 0) { fprintf(stderr, "Error: %s\n", gnutls_strerror(ret)); return 1; } dump_hex(signature, signature_size); return 0; }