Exemple #1
0
/* This function verifies that the data specified hashes to the hash value
 * specified.
 * This function sets the KMO error string. It returns -1 on failure.
 */
static int check_hash(struct kmocrypt_signature2 *self, uint8_t *hash, uint8_t *data, uint32_t len) {
    uint8_t digest[MAX_DIGEST_LEN];
    
    assert(MAX_DIGEST_LEN >= gcry_md_get_algo_dlen(self->hash_algo));
    gcry_md_hash_buffer(self->hash_algo, digest, data, len);
    
    if (memcmp(hash, digest, gcry_md_get_algo_dlen(self->hash_algo))) {
        kmo_seterror("hash verification failed");
	return -1;
    }
    
    return 0;
}
static gboolean
verify_decrypted_buffer (EggBuffer *buffer)
{
        guchar digest[16];

	/* In case the world changes on us... */
	g_return_val_if_fail (gcry_md_get_algo_dlen (GCRY_MD_MD5) == sizeof (digest), 0);

	gcry_md_hash_buffer (GCRY_MD_MD5, (void*)digest,
			     (guchar*)buffer->buf + 16, buffer->len - 16);

	return memcmp (buffer->buf, digest, 16) == 0;
}
Exemple #3
0
/*
 * crypt_sha_one() -
 *   return:
 *   thread_p(in):
 *   src(in): 
 *   src_len(in): 
 *   dest_len_p(out):
 * Note:
 */
int
crypt_sha_one (THREAD_ENTRY * thread_p, const char *src, int src_len, char **dest_p, int *dest_len_p)
{
  int hash_length;
  char *dest = NULL;
  char *dest_hex = NULL;
  int dest_len;
  int dest_hex_len;
  int error_status = NO_ERROR;

  assert (src != NULL);

  if (thread_p == NULL)
    {
      thread_p = thread_get_thread_entry_info ();
    }

  *dest_p = NULL;

  if (init_gcrypt () != NO_ERROR)
    {
      return ER_ENCRYPTION_LIB_FAILED;
    }

  hash_length = gcry_md_get_algo_dlen (GCRY_MD_SHA1);
  dest = (char *) db_private_alloc (thread_p, hash_length);
  if (dest == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  dest_len = hash_length;
  gcry_md_hash_buffer (GCRY_MD_SHA1, dest, src, src_len);
  dest_hex = str_to_hex (thread_p, dest, dest_len, &dest_hex, &dest_hex_len);
  if (dest_hex == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  *dest_p = dest_hex;
  *dest_len_p = dest_hex_len;

exit_and_free:
  if (dest != NULL)
    {
      db_private_free_and_init (thread_p, dest);
    }
  return error_status;
}
Exemple #4
0
void sha512(char *string, int length, char *result)
{

	int msg_length = length;
	int hash_length = gcry_md_get_algo_dlen(GCRY_MD_SHA512);
	unsigned char hash[hash_length];
	gcry_md_hash_buffer(GCRY_MD_SHA512, hash, string, msg_length);
	int i;
	for (i = 0; i < hash_length; i++, result += 2) {
		snprintf(result, 3, "%02x", hash[i]);
	}
	return;

}
Exemple #5
0
/* Algorithms 4.42 and 4.43 in the "Guide to Elliptic Curve Cryptography"     */
static void ECIES_KDF(char *key, const gcry_mpi_t Zx, 
		      const struct affine_point *R, int elemlen)
{
  char *buf;
  if (!(buf = gcry_malloc_secure(3 * elemlen))) {
    fprintf(stderr, "Failed to malloc secure memory in ECIES_KDF()\n");
    return;;
  }
  serialize_mpi(buf + 0 * elemlen, elemlen, DF_BIN, Zx);
  serialize_mpi(buf + 1 * elemlen, elemlen, DF_BIN, R->x);
  serialize_mpi(buf + 2 * elemlen, elemlen, DF_BIN, R->y);
  gcry_md_hash_buffer(GCRY_MD_SHA512, key, buf, 3 * elemlen);
  gcry_free(buf);
}
Exemple #6
0
int my_hash(const char alg[], const unsigned char input[], const unsigned int input_len, unsigned char output[]) {
	int md = gcry_md_map_name(alg);
	unsigned int mdlen = gcry_md_get_algo_dlen(md);
	gchar *keybuf = g_new0(gchar, mdlen);
	memset(keybuf, 0, mdlen);
	gcry_md_hash_buffer(md, keybuf, input, input_len);
	
	//copy
	size_t i = 0;
	for(i = 0; i<mdlen; ++i) {
		output[i] = keybuf[ i%mdlen ];
	}
	return 0;
}
Exemple #7
0
NGram::NGramData::shadigest_vect_t
NGram::NGramData::hashsum(const string& st, gcry_md_algos algo) {
  size_t hash_len = gcry_md_get_algo_dlen(algo);
  shadigest_t *buf = (shadigest_t*) malloc(hash_len);
  gcry_md_hash_buffer(algo, buf, st.c_str(), st.length());
  
  shadigest_vect_t ret;
  for (unsigned int i=0; i<hash_len; i++)
    ret.push_back(buf[i]);
  
  free(buf);
  
  return ret;
}
Exemple #8
0
int
soft_sign (const uint8_t *to_sign, size_t len,
      jwa_t alg, void *cookie,
      uint8_t **out, size_t *out_len)
{


    int rc = -1;
    uint8_t *hash;
    gcry_sexp_t sig, digest;

    const unsigned int DLEN = gcry_md_get_algo_dlen (GCRY_MD_SHA256);
    hash = malloc (DLEN);
    assert (NULL != hash);

    gcry_md_hash_buffer (GCRY_MD_SHA256, hash, to_sign, len);

    rc = gcry_sexp_build (&digest, NULL,
                          "(data (flags raw)\n"
                          " (value %b))",
                          DLEN, hash);

    if (rc)
        goto OUT;

    if (rc = gcry_pk_sign (&sig, digest, signing_key))
        goto DIG;

    lca_print_sexp (sig);

    struct lca_octet_buffer signature = lca_sig2buf (&sig);

    if (NULL != signature.ptr)
    {
        *out = signature.ptr;
        *out_len = signature.len;
        rc = 0;
    }

    gcry_free (sig);


DIG:
    gcry_free (digest);
OUT:
    free (hash);
    assert (0 == rc);
    return rc;
}
Exemple #9
0
/* Calculate a raw hash of our DSA public key.  Return it in the passed
 * fingerprint buffer.  Return NULL on error, or a pointer to the given
 * buffer on success. */
unsigned char *otrl_privkey_fingerprint_raw(OtrlUserState us,
	unsigned char hash[20], const char *accountname, const char *protocol)
{
    OtrlPrivKey *p = otrl_privkey_find(us, accountname, protocol);

    if (p) {
	/* Calculate the hash */
	gcry_md_hash_buffer(GCRY_MD_SHA1, hash, p->pubkey_data,
		p->pubkey_datalen);
    } else {
	return NULL;
    }

    return hash;
}
Exemple #10
0
static SLVAL
sl_gcrypt_algorithm_hex_digest(sl_vm_t* vm, SLVAL self, SLVAL strv)
{
    size_t i;
    sl_string_t* str = sl_get_string(vm, strv);
    gcrypt_algorithm_t* algo = get_algo_check(vm, self);
    size_t digest_len = gcry_md_get_algo_dlen(algo->algo);
    char* digest = alloca(digest_len);
    char* hex_digest = alloca(digest_len * 2);
    gcry_md_hash_buffer(algo->algo, digest, str->buff, str->buff_len);
    for(i = 0; i < digest_len; i++) {
        sprintf(hex_digest + 2 * i, "%02x", (uint8_t)digest[i]);
    }
    return sl_make_string(vm, (uint8_t*)hex_digest, digest_len * 2);
}
Exemple #11
0
string cipher::encrypt(string const &plain,time_t timeout)
{
	size_t block_size=(plain.size() + 15) / 16 * 16;

	vector<unsigned char> data(sizeof(aes_hdr)+sizeof(info)+block_size,0);
	copy(plain.begin(),plain.end(),data.begin() + sizeof(aes_hdr)+sizeof(info));
	aes_hdr &aes_header=*(aes_hdr*)(&data.front());
	info &header=*(info *)(&data.front()+sizeof(aes_hdr));
	header.timeout=timeout;
	header.size=plain.size();
	memset(&aes_header,0,16);

	gcry_md_hash_buffer(GCRY_MD_MD5,&aes_header.md5,&header,block_size+sizeof(info));
	gcry_cipher_encrypt(hd_out,&data.front(),data.size(),NULL,0);

	return base64_enc(data);
}
guchar*
gkm_certificate_hash (GkmCertificate *self, int hash_algo, gsize *n_hash)
{
	guchar *hash;

	g_return_val_if_fail (GKM_IS_CERTIFICATE (self), NULL);
	g_return_val_if_fail (self->pv->data, NULL);
	g_return_val_if_fail (n_hash, NULL);

	*n_hash = gcry_md_get_algo_dlen (hash_algo);
	g_return_val_if_fail (*n_hash > 0, NULL);

	hash = g_malloc0 (*n_hash);
	gcry_md_hash_buffer (hash_algo, hash, self->pv->data, self->pv->n_data);

	return hash;
}
Exemple #13
0
static int get_hash_via_username_and_inode(char *hash, char *passwd, size_t *passwd_len)
{
	char		tmp[MAX_LEN], tobehashed[MAX_LEN];
	char		mumps_ex[GTM_PATH_MAX], *user_ptr, *dist_ptr;
	size_t		ilen;
	struct stat	stat_info;

	memset(tobehashed, 0, MAX_LEN);
	memset(mumps_ex, 0, GTM_PATH_MAX);
	/* We need $USER and $gtm_dist to be defined to do the proper masking */
	if (NULL == (user_ptr = (char *)getenv("USER")))
	{
		printf("Environment variable USER not defined.\n");
		return 1;
	}
	if (NULL == (dist_ptr = (char *)getenv(GTM_DIST)))
	{
		printf("Enivronment variable gtm_dist not defined.\n");
		return 1;
	}
	snprintf(mumps_ex, GTM_PATH_MAX, "%s/%s", dist_ptr, "mumps");
	if (0 != stat(mumps_ex, &stat_info))
	{
		printf("Cannot stat %s\n", mumps_ex);
		return 1;
	}
	prompt_passwd(passwd);
	*passwd_len = strlen(passwd);
	strncpy(tobehashed, user_ptr, MIN(*passwd_len, MAX_LEN));
	snprintf(tmp, MAX_LEN, "%ld", stat_info.st_ino);
	ilen = strlen(tmp);
	/* a potential simplification is to just concatenate the userid and inode */
	if (ilen < *passwd_len)
	      strncpy(tobehashed + (*passwd_len - ilen), tmp, ilen);
	else
	      strncpy(tobehashed, tmp, *passwd_len);

#	ifdef USE_OPENSSL
	EVP_Digest(tobehashed, *passwd_len, (unsigned char *)hash, NULL, EVP_sha512(), NULL);
#	elif defined USE_GCRYPT
	gcry_md_hash_buffer(GCRY_MD_SHA512, hash, tobehashed, *passwd_len );
#	endif

	return 0;

}
Exemple #14
0
/* Calculate a human-readable hash of our DSA public key.  Return it in
 * the passed fingerprint buffer.  Return NULL on error, or a pointer to
 * the given buffer on success. */
char *otrl_privkey_fingerprint(OtrlUserState us, char fingerprint[45],
	const char *accountname, const char *protocol)
{
    unsigned char hash[20];
    OtrlPrivKey *p = otrl_privkey_find(us, accountname, protocol);

    if (p) {
	/* Calculate the hash */
	gcry_md_hash_buffer(GCRY_MD_SHA1, hash, p->pubkey_data,
		p->pubkey_datalen);

	/* Now convert it to a human-readable format */
	otrl_privkey_hash_to_human(fingerprint, hash);
    } else {
	return NULL;
    }

    return fingerprint;
}
Exemple #15
0
/* Compute the SHA-1 checksum of the rawdata in BLOB and put it into
   DIGEST. */
static int
hash_blob_rawdata (KEYBOXBLOB blob, unsigned char *digest)
{
  const unsigned char *buffer;
  size_t n, length;
  int type;
  ulong rawdata_off, rawdata_len;

  buffer = _keybox_get_blob_image (blob, &length);

  if (length < 32)
    return -1;
  n = get32 (buffer);
  if (n < length)
    length = n;  /* Blob larger than length in header - ignore the rest. */

  type = buffer[4];
  switch (type)
    {
    case KEYBOX_BLOBTYPE_PGP:
    case KEYBOX_BLOBTYPE_X509:
      break;

    case KEYBOX_BLOBTYPE_EMPTY:
    case KEYBOX_BLOBTYPE_HEADER:
    default:
      memset (digest, 0, 20);
      return 0;
    }

  if (length < 40)
    return -1;

  rawdata_off = get32 (buffer + 8);
  rawdata_len = get32 (buffer + 12);

  if (rawdata_off > length || rawdata_len > length
      || rawdata_off+rawdata_off > length)
    return -1; /* Out of bounds.  */

  gcry_md_hash_buffer (GCRY_MD_SHA1, digest, buffer+rawdata_off, rawdata_len);
  return 0;
}
Exemple #16
0
static uint32_t gen_cksum(char *ptr, int len)
{
	int i;
	uint32_t md[4];

	/* Convert L1 table to big endian */
	for(i = 0; i < len / sizeof(uint64_t); i++) {
		cpu_to_be64s(&((uint64_t*) ptr)[i]);
	}

	/* Generate checksum */
	gcry_md_hash_buffer(GCRY_MD_MD5, md, ptr, len);

	/* Convert L1 table back to native endianess */
	for(i = 0; i < len / sizeof(uint64_t); i++) {
		be64_to_cpus(&((uint64_t*) ptr)[i]);
	}

	return md[0];
}
Exemple #17
0
z_int_t z_digest_sum_buffer(const void *buffer, z_int_t length, void *sum) /* z_proto, z_func z_digest_sum_buffer */
{
#if defined(HAVE_GCRYPT_H)

  if (!buffer || !sum) return gcry_md_get_algo_dlen(GCRY_MD_CRC32);

  gcry_md_hash_buffer(GCRY_MD_CRC32, sum, buffer, length);

#elif defined (Z_PACK_CRC32)

  if (!buffer || !sum) return sizeof(z_crc32_t);

  *((z_crc32_t *) sum) = z_crc32_buffer(buffer, length);
  
#endif

/*  printf("z: %.8X\n", *((z_crc32_t *) sum));*/

  return 0;
}
static CK_RV
attribute_set_check_value (GkmGenericKey *self, CK_ATTRIBUTE *attr)
{
	guchar buffer[20];

	g_assert (GKM_IS_GENERIC_KEY (self));
	g_assert (attr);

	/* Just asking for the length */
	if (!attr->pValue) {
		attr->ulValueLen = 3;
		return CKR_OK;
	}

	/* Just the a sha1 of the value */
	gcry_md_hash_buffer (GCRY_MD_SHA1, buffer, self->value, self->n_value);

	/* Use the first three bytes */
	return gkm_attribute_set_data (attr, buffer, 3);
}
Exemple #19
0
gchar * __pkey_manage_aes_encrypt (const gchar *in, const gchar *password)
{
    gchar * result = NULL;

    gint i;
    guint in_length = strlen (in);
    guchar * random_data = NULL;
    guchar * sha256 = NULL;
    gchar * sha256_hex = NULL;

    gchar * cyphered = NULL;

    random_data = g_new0 (guchar, in_length);

    // Fill random_data with random data
    gcry_create_nonce (random_data, in_length);

    // XOR random_data with in => random_data
    for (i=0; i<in_length; i++) {
        random_data[i] = random_data[i] ^ in[i];
    }

    // SHA-2 256 random_data
    sha256 = g_new0 (guchar, gcry_md_get_algo_dlen(GCRY_MD_SHA256));
    gcry_md_hash_buffer (GCRY_MD_SHA256, sha256, random_data, in_length);

    sha256_hex = __pkey_manage_to_hex (sha256, 32);

    cyphered = __pkey_manage_aes_encrypt_aux (in, password, &sha256[0], &sha256[16]);

    result = g_strdup_printf ("gCP%s%s", sha256_hex, cyphered);

    g_free (sha256_hex);
    g_free (cyphered);

    g_free (sha256);
    g_free (random_data);

    return result;

}
Exemple #20
0
/**
 * Proceed to a hash on a kbuffer, putting the result in the
 * hash kbuffer.
 */
void kmocrypt_hash(kbuffer * input, kbuffer * hash, int algo) {
    int digest_len;
    uint32_t input_size;
    
    /* Simple hashing, result is put directly in the buffer, no
       copy needed, no payment until 2099. */

    assert(gcry_md_test_algo(algo) == 0);

    digest_len = gcry_md_get_algo_dlen(algo);

    /* Get the length and addresse of unread data from input, and read it to
     * the end */
    input_size = input->len - input->pos;

    /* Hash the buffer. */
    gcry_md_hash_buffer(algo,
                        kbuffer_append_nbytes(hash, digest_len),
                        kbuffer_read_nbytes(input, input_size),
                        (size_t)input_size);
}
Exemple #21
0
void *
eet_identity_compute_sha1(const void  *data_base,
                          unsigned int data_length,
                          int         *sha1_length)
{
   void *result;

#ifdef HAVE_SIGNATURE
# ifdef HAVE_GNUTLS
   result = malloc(gcry_md_get_algo_dlen(GCRY_MD_SHA1));
   if (!result)
     return NULL;

   gcry_md_hash_buffer(GCRY_MD_SHA1, result, data_base, data_length);
   if (sha1_length)
     *sha1_length = gcry_md_get_algo_dlen(GCRY_MD_SHA1);

# else /* ifdef HAVE_GNUTLS */
#  ifdef HAVE_OPENSSL
   result = malloc(SHA_DIGEST_LENGTH);
   if (!result)
     return NULL;

   SHA1(data_base, data_length, result);
   if (sha1_length)
     *sha1_length = SHA_DIGEST_LENGTH;

#  else /* ifdef HAVE_OPENSSL */
   result = NULL;
#  endif /* ifdef HAVE_OPENSSL */
# endif /* ifdef HAVE_GNUTLS */
#else /* ifdef HAVE_SIGNATURE */
   data_base = NULL;
   data_length = 0;
   sha1_length = NULL;
   result = NULL;
#endif /* ifdef HAVE_SIGNATURE */

   return result;
}
void FileSystemSensorModule::getFileSHA1Sum(const std::string &fileName, std::string &sha1Sum){
	this->clearFSCache();

	  std::ifstream fileHandle;
	  fileHandle.open(std::string().insert(0, this->fileSystemPath).append("/").append(fileName).c_str(), std::ifstream::in);

	  long begin,end;
	  begin = fileHandle.tellg();
	  fileHandle.seekg (0, std::ios::end);
	  end = fileHandle.tellg();
	  fileHandle.seekg (0, std::ios::beg);

	  char * fileContent = (char *) malloc(end-begin);

	  int count = 0;
	  while (fileHandle.good())
	    fileContent[count++] = fileHandle.get();

	  fileHandle.close();

	  int hash_len = gcry_md_get_algo_dlen( GCRY_MD_SHA1 );

	  unsigned char hash[ hash_len ];

	  char *out = (char *) malloc( sizeof(char) * ((hash_len*2)+1) );
	  char *p = out;

	  gcry_md_hash_buffer( GCRY_MD_SHA1, hash, fileContent, count - 1 );

	  for ( int i = 0; i < hash_len; i++, p += 2 )
	    snprintf ( p, 3, "%02x", hash[i] );

	  sha1Sum.append(out, sizeof(char) * ((hash_len*2)));

	  free(fileContent);
	  free( out );



}
Exemple #23
0
static int evp_fdigest(lua_State *L)
{
  const char *type_name = luaL_checkstring(L, 1);
  const char *s = luaL_checkstring(L, 2);
  DIGEST_TYPE type = DIGEST_BY_NAME(type_name);
  size_t written = 0;
#if CRYPTO_OPENSSL
  HANDLER_EVP *c = NULL;
  unsigned char digest[EVP_MAX_MD_SIZE];
#elif CRYPTO_GCRYPT
  unsigned char digest[gcry_md_get_algo_dlen(type)];
#endif
  
  if (IS_DIGEST_INVALID(type)) {
    luaL_argerror(L, 1, "invalid digest type");
    return 0;
  }
  
#if CRYPTO_OPENSSL
  c = EVP_MD_CTX_create();
  EVP_DigestInit_ex(c, type, NULL);
  EVP_DigestUpdate(c, s, lua_strlen(L, 2));
  EVP_DigestFinal_ex(c, digest, &written);
#elif CRYPTO_GCRYPT
  gcry_md_hash_buffer(type,digest,s,lua_strlen(L, 2));
  written = gcry_md_get_algo_dlen(type);
#endif
  
  if (lua_toboolean(L, 3))
    lua_pushlstring(L, (char *)digest, written);
  else
  {
    char *hex = bin2hex(digest, written);
    lua_pushlstring(L, hex, written*2);
    free(hex);
  }
  
  return 1;
}
Exemple #24
0
int
rasqal_digest_buffer(rasqal_digest_type type, const unsigned char *output,
                     const unsigned char * const input, size_t len)
{
  enum gcry_md_algos algo;
  unsigned int output_len;
  
  if(type > RASQAL_DIGEST_LAST)
    return -1;
  
  algo = rasqal_digest_to_gcry_md_algos[type];
  if(algo == GCRY_MD_NONE)
    return -1;
  
  output_len = gcry_md_get_algo_dlen(algo);
  if(!input)
    return output_len;
  
  gcry_md_hash_buffer(algo, (void*)output, (const void*)input, len);
  
  return output_len;
}
Exemple #25
0
static libspectrum_error
get_hash( gcry_sexp_t *hash, const libspectrum_byte *data, size_t data_length )
{
  gcry_error_t error;
  unsigned char *digest; size_t digest_length;
  gcry_mpi_t hash_mpi;
  
  digest_length = gcry_md_get_algo_dlen( HASH_ALGORITHM );
  digest = libspectrum_malloc( digest_length );

  gcry_md_hash_buffer( HASH_ALGORITHM, digest, data, data_length );

  error = gcry_mpi_scan( &hash_mpi, GCRYMPI_FMT_USG, digest, digest_length,
			 NULL );
  if( error ) {
    libspectrum_print_error( LIBSPECTRUM_ERROR_LOGIC,
			     "get_hash: error creating hash MPI: %s",
			     gcry_strerror( error )
    );
    libspectrum_free( digest );
    return LIBSPECTRUM_ERROR_LOGIC;
  }

  libspectrum_free( digest );

  error = gcry_sexp_build( hash, NULL, hash_format, hash_mpi );
  if( error ) {
    libspectrum_print_error( LIBSPECTRUM_ERROR_LOGIC,
			     "get_hash: error creating hash sexp: %s",
			     gcry_strerror( error )
    );
    gcry_mpi_release( hash_mpi );
    return LIBSPECTRUM_ERROR_LOGIC;
  }

  gcry_mpi_release( hash_mpi );

  return LIBSPECTRUM_ERROR_NONE;
}
Exemple #26
0
/*
 * crypt_crc32() -
 *   return: error code
 *   thread_p(in):
 *   src(in): original message
 *   src_len(in): length of original message
 *   dest(out): crc32 result
 * Note:
 */
int
crypt_crc32 (THREAD_ENTRY * thread_p, const char *src, int src_len, int *dest)
{
  int hash_length;
  char *hash_result;
  int error_status = NO_ERROR;

  assert (src != NULL);

  if (thread_p == NULL)
    {
      thread_p = thread_get_thread_entry_info ();
    }

  if (init_gcrypt () != NO_ERROR)
    {
      return ER_ENCRYPTION_LIB_FAILED;
    }

  hash_length = gcry_md_get_algo_dlen (GCRY_MD_CRC32);
  hash_result = (char *) db_private_alloc (thread_p, hash_length);
  if (hash_result == NULL)
    {
      error_status = ER_OUT_OF_VIRTUAL_MEMORY;
      goto exit_and_free;
    }

  gcry_md_hash_buffer (GCRY_MD_CRC32, hash_result, src, src_len);

  *dest = htonl (*(UINT32 *) hash_result);

exit_and_free:
  if (hash_result != NULL)
    {
      db_private_free_and_init (thread_p, hash_result);
    }
  return error_status;
}
Exemple #27
0
static int get_hash_via_env_var(char *hash)
{
	int 		fd;
	char 		*ob_key;
	struct stat 	stat_info;
	char 		*p;

	if (NULL == (ob_key = (char *) getenv("gtm_obfuscation_key")))
		return 1;

	fd = open(ob_key, O_RDONLY);
	if (fd == -1)
		return 1;

	if (fstat(fd, &stat_info) == -1)
		return 1;

	if (!S_ISREG(stat_info.st_mode))
		return 1;

	p = mmap(0, stat_info.st_size, PROT_READ, MAP_SHARED, fd, 0);
	if (MAP_FAILED == p)
		return 1;

	if (-1 == close(fd))
		return 1;

#	ifdef USE_OPENSSL
	EVP_Digest(p, stat_info.st_size, (unsigned char *)hash, NULL, EVP_sha512(), NULL);
#	elif defined USE_GCRYPT
	gcry_md_hash_buffer(GCRY_MD_SHA512, hash, p, stat_info.st_size );
#	endif

	/* Since we have what we want no need to check the status of the munmap */
	munmap(p, stat_info.st_size);

	return 0;
}
Exemple #28
0
void sha1(unsigned char *digest, int len, unsigned char *hash) {
  gcry_md_hash_buffer(GCRY_MD_SHA1, hash, digest, len);
}
static int
generate_key_or_iv(unsigned int id, tvbuff_t *salt_tvb, unsigned int iter,
		       const char *pw, unsigned int req_keylen, char * keybuf)
{
  int rc;
  unsigned int i, j;
  gcry_md_hd_t md;
  gcry_mpi_t num_b1 = NULL;
  size_t pwlen;
  char hash[20], buf_b[64], buf_i[128], *p;
  char *salt_p;
  int salt_size;
  size_t cur_keylen;
  size_t n;
  gcry_error_t	err;

  cur_keylen = 0;

  salt_size = tvb_captured_length(salt_tvb);
  salt_p = (char *)tvb_memdup(wmem_packet_scope(), salt_tvb, 0, salt_size);

  if (pw == NULL)
    pwlen = 0;
  else
    pwlen = strlen(pw);

  if (pwlen > 63 / 2)
    {
      return FALSE;
    }

  /* Store salt and password in BUF_I */
  p = buf_i;
  for (i = 0; i < 64; i++)
    *p++ = salt_p[i % salt_size];
  if (pw)
    {
      for (i = j = 0; i < 64; i += 2)
	{
	  *p++ = 0;
	  *p++ = pw[j];
	  if (++j > pwlen)	/* Note, that we include the trailing zero */
	    j = 0;
	}
    }
  else
    memset (p, 0, 64);

  for (;;) {
      err = gcry_md_open(&md, GCRY_MD_SHA1, 0);
      if (gcry_err_code(err))
        {
          return FALSE;
        }
      for (i = 0; i < 64; i++)
        {
          unsigned char lid = id & 0xFF;
          gcry_md_write (md, &lid, 1);
	}

      gcry_md_write(md, buf_i, pw ? 128 : 64);

      gcry_md_final (md);
      memcpy (hash, gcry_md_read (md, 0), 20);

      gcry_md_close (md);

      for (i = 1; i < iter; i++)
        gcry_md_hash_buffer (GCRY_MD_SHA1, hash, hash, 20);

      for (i = 0; i < 20 && cur_keylen < req_keylen; i++)
        keybuf[cur_keylen++] = hash[i];

      if (cur_keylen == req_keylen)
      {
        gcry_mpi_release (num_b1);
        return TRUE;		/* ready */
      }

      /* need more bytes. */
      for (i = 0; i < 64; i++)
        buf_b[i] = hash[i % 20];

      n = 64;

      rc = gcry_mpi_scan (&num_b1, GCRYMPI_FMT_USG, buf_b, n, &n);

      if (rc != 0)
        {
          return FALSE;
        }

      gcry_mpi_add_ui (num_b1, num_b1, 1);

      for (i = 0; i < 128; i += 64)
        {
          gcry_mpi_t num_ij;

          n = 64;
          rc = gcry_mpi_scan (&num_ij, GCRYMPI_FMT_USG, buf_i + i, n, &n);

          if (rc != 0)
            {
              return FALSE;
            }

          gcry_mpi_add (num_ij, num_ij, num_b1);
          gcry_mpi_clear_highbit (num_ij, 64 * 8);

          n = 64;

          rc = gcry_mpi_print (GCRYMPI_FMT_USG, buf_i + i, n, &n, num_ij);
          if (rc != 0)
            {
              return FALSE;
            }

          gcry_mpi_release (num_ij);
        }
  }
}
Exemple #30
0
/* This function recognizes the signature of the KSP itself. Note that this
 * function prepares the validation of the signature of the KSP with its
 * corresponding public key but does not actually do the validation. The
 * validation should be done with kmocrypt_signature_validate2() once the public
 * key has been obtained from the KOS.
 * This function sets the KMO error string. It returns -1 on failure.
 */
static int recognize_ksp_signature(struct kmocrypt_signature2 *self, kbuffer *buffer, uint32_t total_len) {
    int error = 0;
    uint32_t sig_len;
    size_t scanned_sig_len;
    int digest_len = gcry_md_get_algo_dlen(self->hash_algo);
    uint8_t digest[MAX_DIGEST_LEN];
    char hashname[MAX_HASH_ALGO_NAME_LEN];
    char signame[MAX_SIG_ALGO_NAME_LEN];
    
    /* Verify that we're using the correct signature algorithm. */
    if (self->sig_algo != GCRY_AC_RSA) {
    	kmo_seterror("Signature algorithm is not GCRY_AC_RSA");
	return -1;
    }
    
    /* Get the hash algorithm name. */
    strncpy(hashname, gcry_md_algo_name(self->hash_algo), MAX_HASH_ALGO_NAME_LEN);
    strntolower(hashname, MAX_HASH_ALGO_NAME_LEN);
    
    /* Get the signature algorithm name. */
    strncpy(signame, gcry_pk_algo_name(self->sig_algo), MAX_SIG_ALGO_NAME_LEN);
    strntolower(signame, MAX_SIG_ALGO_NAME_LEN);
    
    /* Hash the content of the KSP up to KSP signature part. */
    gcry_md_hash_buffer(self->hash_algo, digest, buffer->data, buffer->pos);
    
    /* Build the gcrypt hash of the KSP required to verify the signature. */
    error = gcry_sexp_build(&self->sig_hash, NULL, "(4:data(5:flags5:pkcs1)(4:hash %s %b))", 
                            hashname, digest_len, digest);
    if (error) {
        kmo_seterror("cannot build signature hash: %s", gcry_strerror(error));
	return -1;
    }
    
    /* Get the length of the signature. */
    if (total_len < 4) {
    	kmo_seterror("KSP signature section is too short");
	return -1;
    }
    
    sig_len = kbuffer_read32(buffer);
    
    if (total_len != 4 + sig_len) {
    	kmo_seterror("KSP signature section is malformed");
	return -1;
    }
    
    /* Get the signature MPI. */
    error = gcry_mpi_scan(&self->sig_mpi, GCRYMPI_FMT_PGP, kbuffer_current_pos(buffer), sig_len, &scanned_sig_len);
    if (error) {
    	kmo_seterror("invalid MPI in signature: %s", gcry_strerror(error));
	return -1;
    }
    
    if (scanned_sig_len != sig_len) {
    	kmo_seterror("invalid MPI in signature: unexpected size");
	return -1;
    }
    
    /* Skip the signature (just to be thorough, it's not strictly necessary). */
    buffer->pos += sig_len;
    
    /* Build the signature s-expression. */
    error = gcry_sexp_build(&self->sig_sexp, NULL, "(7:sig-val(%s(1:s %m)))", signame, self->sig_mpi);
    if (error) {
    	kmo_seterror("cannot build signature from MPI: %s", gcry_strerror(error));
	return -1;
    }
    
    return 0;
}