Exemplo n.º 1
0
/*
 *  J A R _ d i g e s t _ f i l e
 *
 *  Calculates the MD5 and SHA1 digests for a file
 *  present on disk, and returns these in JAR_Digest struct.
 *
 */
int 
JAR_digest_file (char *filename, JAR_Digest *dig)
{
    JAR_FILE fp;
    PK11Context *md5 = 0;
    PK11Context *sha1 = 0;
    unsigned char *buf = (unsigned char *) PORT_ZAlloc (FILECHUNQ);
    int num;
    unsigned int md5_length, sha1_length;

    if (buf == NULL) {
	/* out of memory */
	return JAR_ERR_MEMORY;
    }

    if ((fp = JAR_FOPEN (filename, "rb")) == 0) {
	/* perror (filename); FIX XXX XXX XXX XXX XXX XXX */
	PORT_Free (buf);
	return JAR_ERR_FNF;
    }

    md5 = PK11_CreateDigestContext (SEC_OID_MD5);
    sha1 = PK11_CreateDigestContext (SEC_OID_SHA1);

    if (md5 == NULL || sha1 == NULL) {
	/* can't generate digest contexts */
	PORT_Free (buf);
	JAR_FCLOSE (fp);
	return JAR_ERR_GENERAL;
    }

    PK11_DigestBegin (md5);
    PK11_DigestBegin (sha1);

    while (1) {
	if ((num = JAR_FREAD (fp, buf, FILECHUNQ)) == 0)
	    break;

	PK11_DigestOp (md5, buf, num);
	PK11_DigestOp (sha1, buf, num);
    }

    PK11_DigestFinal (md5, dig->md5, &md5_length, MD5_LENGTH);
    PK11_DigestFinal (sha1, dig->sha1, &sha1_length, SHA1_LENGTH);

    PK11_DestroyContext (md5, PR_TRUE);
    PK11_DestroyContext (sha1, PR_TRUE);

    PORT_Free (buf);
    JAR_FCLOSE (fp);

    return 0;
}
Exemplo n.º 2
0
char *oauth_body_hash_data(size_t length, const char *data) {
  PK11SlotInfo  *slot = NULL;
  PK11Context   *context = NULL;
  unsigned char  digest[20]; // Is there a way to tell how large the output is?
  unsigned int   len;
  SECStatus      s;
  char          *rv=NULL;

  oauth_init_nss();

  slot = PK11_GetInternalKeySlot();
  if (!slot) goto looser;
  context = PK11_CreateDigestContext(SEC_OID_SHA1);
  if (!context) goto looser;

  s = PK11_DigestBegin(context);
  if (s != SECSuccess) goto looser;
  s = PK11_DigestOp(context, (unsigned char*) data, length);
  if (s != SECSuccess) goto looser;
  s = PK11_DigestFinal(context, digest, &len, sizeof digest);
  if (s != SECSuccess) goto looser;

  unsigned char *dgst = xmalloc(len*sizeof(char)); // oauth_body_hash_encode frees the digest..
  memcpy(dgst, digest, len);
  rv=oauth_body_hash_encode(len, dgst);

looser:
  if (context) PK11_DestroyContext(context, PR_TRUE);
  if (slot) PK11_FreeSlot(slot);
  return rv;
}
Exemplo n.º 3
0
Arquivo: nss.c Projeto: flashfoxter/sx
int sxi_hmac_sha1_init_ex(sxi_hmac_sha1_ctx *ctx,
                     const void *key, int key_len)
{
    if (!ctx)
        return 0;
    /* NOTE: params must be provided, but may be empty */
    SECItem noParams;
    noParams.type = siBuffer;
    noParams.data = 0;
    noParams.len = 0;

    if (ctx->context)
      PK11_DestroyContext(ctx->context, PR_TRUE);
    if (ctx->key)
        PK11_FreeSymKey(ctx->key);
    if (ctx->keysec)
        SECITEM_FreeItem(ctx->keysec, PR_TRUE);
    ctx->keysec = SECITEM_AllocItem(NULL, NULL, key_len);
    if (ctx->keysec) {
        memcpy(ctx->keysec->data, key, key_len);
        ctx->key = PK11_ImportSymKey(ctx->slot, CKM_SHA_1_HMAC, PK11_OriginDerive, CKA_SIGN,
                                     ctx->keysec, &noParams);
        if(ctx->key) {
            ctx->context = PK11_CreateContextBySymKey(CKM_SHA_1_HMAC, CKA_SIGN, ctx->key, &noParams);
            if (ctx->context && PK11_DigestBegin(ctx->context) == SECSuccess)
                return 1;
        }
    }
    return 0;
}
Exemplo n.º 4
0
static int nss_hash_init(void **pctx, SECOidTag hash_alg)
{
  PK11Context *ctx;

  /* we have to initialize NSS if not initialized alraedy */
#ifdef HAVE_NSS_INITCONTEXT
  if(!NSS_IsInitialized() && !nss_context) {
    static NSSInitParameters params;
    params.length = sizeof params;
    nss_context = NSS_InitContext("", "", "", "", &params, NSS_INIT_READONLY
        | NSS_INIT_NOCERTDB   | NSS_INIT_NOMODDB       | NSS_INIT_FORCEOPEN
        | NSS_INIT_NOROOTINIT | NSS_INIT_OPTIMIZESPACE | NSS_INIT_PK11RELOAD);
  }
#endif

  ctx = PK11_CreateDigestContext(hash_alg);
  if(!ctx)
    return /* failure */ 0;

  if(PK11_DigestBegin(ctx) != SECSuccess) {
    PK11_DestroyContext(ctx, PR_TRUE);
    return /* failure */ 0;
  }

  *pctx = ctx;
  return /* success */ 1;
}
Exemplo n.º 5
0
// Let derIssuer be the DER encoding of the issuer of aCert.
// Let derPublicKey be the DER encoding of the public key of aIssuerCert.
// Let serialNumber be the bytes of the serial number of aCert.
// The value calculated is SHA384(derIssuer || derPublicKey || serialNumber).
// Because the DER encodings include the length of the data encoded,
// there do not exist A(derIssuerA, derPublicKeyA, serialNumberA) and
// B(derIssuerB, derPublicKeyB, serialNumberB) such that the concatenation of
// each triplet results in the same string of bytes but where each part in A is
// not equal to its counterpart in B. This is important because as a result it
// is computationally infeasible to find collisions that would subvert this
// cache (given that SHA384 is a cryptographically-secure hash function).
static SECStatus
CertIDHash(SHA384Buffer& buf, const CertID& certID)
{
  ScopedPK11Context context(PK11_CreateDigestContext(SEC_OID_SHA384));
  if (!context) {
    return SECFailure;
  }
  SECStatus rv = PK11_DigestBegin(context.get());
  if (rv != SECSuccess) {
    return rv;
  }
  rv = PK11_DigestOp(context.get(), certID.issuer.data, certID.issuer.len);
  if (rv != SECSuccess) {
    return rv;
  }
  rv = PK11_DigestOp(context.get(), certID.issuerSubjectPublicKeyInfo.data,
                     certID.issuerSubjectPublicKeyInfo.len);
  if (rv != SECSuccess) {
    return rv;
  }
  rv = PK11_DigestOp(context.get(), certID.serialNumber.data,
                     certID.serialNumber.len);
  if (rv != SECSuccess) {
    return rv;
  }
  uint32_t outLen = 0;
  rv = PK11_DigestFinal(context.get(), buf, &outLen, SHA384_LENGTH);
  if (outLen != SHA384_LENGTH) {
    return SECFailure;
  }
  return rv;
}
Exemplo n.º 6
0
void hmac_final(u_char *output, struct hmac_ctx *ctx)
{
	unsigned int outlen = 0;
	SECStatus status = PK11_DigestFinal(ctx->ctx_nss, output, &outlen,
					    ctx->hmac_digest_len);

	PR_ASSERT(status == SECSuccess);
	PR_ASSERT(outlen == ctx->hmac_digest_len);
	PK11_DestroyContext(ctx->ctx_nss, PR_TRUE);
	ctx->ctx_nss = NULL;

	ctx->ctx_nss = PK11_CreateDigestContext(nss_hash_oid(ctx->h));
	PR_ASSERT(ctx->ctx_nss != NULL);

	status = PK11_DigestBegin(ctx->ctx_nss);
	PR_ASSERT(status == SECSuccess);

	status = PK11_DigestKey(ctx->ctx_nss, ctx->okey);
	PR_ASSERT(status == SECSuccess);

	status = PK11_DigestOp(ctx->ctx_nss, output, outlen);
	PR_ASSERT(status == SECSuccess);

	status = PK11_DigestFinal(ctx->ctx_nss, output, &outlen,
				  ctx->hmac_digest_len);
	PR_ASSERT(status == SECSuccess);
	PR_ASSERT(outlen == ctx->hmac_digest_len);
	PK11_DestroyContext(ctx->ctx_nss, PR_TRUE);

	if (ctx->ikey != NULL)
		PK11_FreeSymKey(ctx->ikey);
	if (ctx->okey != NULL)
		PK11_FreeSymKey(ctx->okey);
	/* DBG(DBG_CRYPT, DBG_log("NSS: hmac final end")); */
}
Exemplo n.º 7
0
/* MAC is generated per PKCS 12 section 6.  It is expected that key, msg
 * and mac_dest are pre allocated, non-NULL arrays.  msg_len is passed in
 * because it is not known how long the message actually is.  String
 * manipulation routines will not necessarily work because msg may have
 * imbedded NULLs
 */
SECItem *
sec_pkcs12_generate_mac(SECItem *key, 
			SECItem *msg,
			PRBool old_method)
{
    SECStatus res = SECFailure;
    SECItem *mac = NULL;
    PK11Context *pk11cx = NULL;    
    SECItem ignore = {0};

    if((key == NULL) || (msg == NULL)) {
	return NULL;
    }

    if(old_method == PR_TRUE) {
	return sec_pkcs12_generate_old_mac(key, msg);
    }

    /* allocate return item */
    mac = SECITEM_AllocItem(NULL, NULL, SHA1_LENGTH);
    if (mac == NULL) {
	return NULL;
    }

    pk11cx = PK11_CreateContextByRawKey(NULL, CKM_SHA_1_HMAC, PK11_OriginDerive,
                                        CKA_SIGN, key, &ignore, NULL);
    if (pk11cx == NULL) {
	goto loser;
    }

    res = PK11_DigestBegin(pk11cx);
    if (res == SECFailure) {
	goto loser;
    }

    res = PK11_DigestOp(pk11cx, msg->data, msg->len);
    if (res == SECFailure) {
	goto loser;
    }

    res = PK11_DigestFinal(pk11cx, mac->data, &mac->len, SHA1_LENGTH);
    if (res == SECFailure) {
	goto loser;
    }

    PK11_DestroyContext(pk11cx, PR_TRUE);
    pk11cx = NULL;

loser:

    if(res != SECSuccess) {
	SECITEM_ZfreeItem(mac, PR_TRUE);
	mac = NULL;
	if (pk11cx) {
	    PK11_DestroyContext(pk11cx, PR_TRUE);
	}
    }

    return mac;
}
Exemplo n.º 8
0
static void cpg_deliver_fn (
        cpg_handle_t handle,
        const struct cpg_name *group_name,
        uint32_t nodeid,
        uint32_t pid,
        void *m,
        size_t msg_len)
{
	const struct my_msg *msg2 = m;
	unsigned char sha1_compare[20];
	unsigned int i;
	unsigned int sha1_len;

	printf ("msg '%s'\n", msg2->buffer);
	PK11_DigestBegin(sha1_context);
	PK11_DigestOp(sha1_context, msg2->buffer, msg2->msg_size);
	PK11_DigestFinal(sha1_context, sha1_compare, &sha1_len, sizeof(sha1_compare));
printf ("SIZE %d HASH: ", msg2->msg_size);
for (i = 0; i < 20; i++) {
printf ("%x", sha1_compare[i]);
}
printf ("\n");
	if (memcmp (sha1_compare, msg2->sha1, 20) != 0) {
		printf ("incorrect hash\n");
		exit (1);
	}
	deliveries++;
}
Exemplo n.º 9
0
// Let derIssuer be the DER encoding of the issuer of aCert.
// Let derPublicKey be the DER encoding of the public key of aIssuerCert.
// Let serialNumber be the bytes of the serial number of aCert.
// The value calculated is SHA384(derIssuer || derPublicKey || serialNumber).
// Because the DER encodings include the length of the data encoded,
// there do not exist A(derIssuerA, derPublicKeyA, serialNumberA) and
// B(derIssuerB, derPublicKeyB, serialNumberB) such that the concatenation of
// each triplet results in the same string of bytes but where each part in A is
// not equal to its counterpart in B. This is important because as a result it
// is computationally infeasible to find collisions that would subvert this
// cache (given that SHA384 is a cryptographically-secure hash function).
static SECStatus
CertIDHash(SHA384Buffer& buf, const CERTCertificate* aCert,
       const CERTCertificate* aIssuerCert)
{
  ScopedPK11Context context(PK11_CreateDigestContext(SEC_OID_SHA384));
  if (!context) {
    return SECFailure;
  }
  SECStatus rv = PK11_DigestBegin(context.get());
  if (rv != SECSuccess) {
    return rv;
  }
  rv = PK11_DigestOp(context.get(), aCert->derIssuer.data,
                     aCert->derIssuer.len);
  if (rv != SECSuccess) {
    return rv;
  }
  rv = PK11_DigestOp(context.get(), aIssuerCert->derPublicKey.data,
                     aIssuerCert->derPublicKey.len);
  if (rv != SECSuccess) {
    return rv;
  }
  rv = PK11_DigestOp(context.get(), aCert->serialNumber.data,
                     aCert->serialNumber.len);
  if (rv != SECSuccess) {
    return rv;
  }
  uint32_t outLen = 0;
  rv = PK11_DigestFinal(context.get(), buf, &outLen, SHA384_LENGTH);
  if (outLen != SHA384_LENGTH) {
    return SECFailure;
  }
  return rv;
}
Exemplo n.º 10
0
/* void init (in unsigned long aAlgorithm, in nsIKeyObject aKeyObject); */
NS_IMETHODIMP
nsCryptoHMAC::Init(uint32_t aAlgorithm, nsIKeyObject *aKeyObject)
{
  nsNSSShutDownPreventionLock locker;
  if (isAlreadyShutDown()) {
    return NS_ERROR_NOT_AVAILABLE;
  }

  if (mHMACContext)
  {
    PK11_DestroyContext(mHMACContext, true);
    mHMACContext = nullptr;
  }

  CK_MECHANISM_TYPE HMACMechType;
  switch (aAlgorithm)
  {
  case nsCryptoHMAC::MD2:
    HMACMechType = CKM_MD2_HMAC; break;
  case nsCryptoHMAC::MD5:
    HMACMechType = CKM_MD5_HMAC; break;
  case nsCryptoHMAC::SHA1:
    HMACMechType = CKM_SHA_1_HMAC; break;
  case nsCryptoHMAC::SHA256:
    HMACMechType = CKM_SHA256_HMAC; break;
  case nsCryptoHMAC::SHA384:
    HMACMechType = CKM_SHA384_HMAC; break;
  case nsCryptoHMAC::SHA512:
    HMACMechType = CKM_SHA512_HMAC; break;
  default:
    return NS_ERROR_INVALID_ARG;
  }

  NS_ENSURE_ARG_POINTER(aKeyObject);

  nsresult rv;

  int16_t keyType;
  rv = aKeyObject->GetType(&keyType);
  NS_ENSURE_SUCCESS(rv, rv);

  NS_ENSURE_TRUE(keyType == nsIKeyObject::SYM_KEY, NS_ERROR_INVALID_ARG);

  PK11SymKey* key;
  // GetKeyObj doesn't addref the key
  rv = aKeyObject->GetKeyObj((void**)&key);
  NS_ENSURE_SUCCESS(rv, rv);

  SECItem rawData;
  rawData.data = 0;
  rawData.len = 0;
  mHMACContext = PK11_CreateContextBySymKey(
      HMACMechType, CKA_SIGN, key, &rawData);
  NS_ENSURE_TRUE(mHMACContext, NS_ERROR_FAILURE);

  SECStatus ss = PK11_DigestBegin(mHMACContext);
  NS_ENSURE_TRUE(ss == SECSuccess, NS_ERROR_FAILURE);

  return NS_OK;
}
Exemplo n.º 11
0
Arquivo: nss.c Projeto: flashfoxter/sx
int sxi_sha1_init(sxi_md_ctx *ctx)
{
    if (!ctx)
        return 0;
    if (PK11_DigestBegin(ctx->context) != SECSuccess)
	return 0;
    return 1;
}
Exemplo n.º 12
0
PK11SymKey * PK11_Derive_osw(PK11SymKey *base, CK_MECHANISM_TYPE mechanism
				    , SECItem *param, CK_MECHANISM_TYPE target
				    , CK_ATTRIBUTE_TYPE  operation, int keysize)
{
	SECOidTag oid;
	PK11Context *ctx;
	unsigned char dkey[HMAC_BUFSIZE];
	SECItem dkey_param;
	SECStatus status;
	unsigned int len=0;
	CK_EXTRACT_PARAMS bs;
        chunk_t dkey_chunk;

	if( ((mechanism == CKM_SHA256_KEY_DERIVATION) ||
	     (mechanism == CKM_SHA384_KEY_DERIVATION)||
	      (mechanism == CKM_SHA512_KEY_DERIVATION)) && (param == NULL) && (keysize ==0)) {

	switch (mechanism) {
	case CKM_SHA256_KEY_DERIVATION: oid = SEC_OID_SHA256; break;
        case CKM_SHA384_KEY_DERIVATION: oid = SEC_OID_SHA384; break;
        case CKM_SHA512_KEY_DERIVATION: oid = SEC_OID_SHA512; break;
	default: DBG(DBG_CRYPT, DBG_log("PK11_Derive_osw: Invalid NSS mechanism ")); break; /*should not reach here*/
	}

	ctx = PK11_CreateDigestContext(oid);
	PR_ASSERT(ctx!=NULL);
	status=PK11_DigestBegin(ctx);
        PR_ASSERT(status == SECSuccess);
	status=PK11_DigestKey(ctx, base);
        PR_ASSERT(status == SECSuccess);
	PK11_DigestFinal(ctx, dkey, &len, sizeof dkey);
	PK11_DestroyContext(ctx, PR_TRUE);

	dkey_chunk.ptr = dkey;
	dkey_chunk.len = len;

        PK11SymKey *tkey1 = pk11_derive_wrapper_osw(base, CKM_CONCATENATE_DATA_AND_BASE, dkey_chunk, CKM_EXTRACT_KEY_FROM_KEY, CKA_DERIVE, 0);
        PR_ASSERT(tkey1!=NULL);

        bs=0;
        dkey_param.data = (unsigned char*)&bs;
        dkey_param.len = sizeof (bs);
        PK11SymKey *tkey2 = PK11_Derive(tkey1, CKM_EXTRACT_KEY_FROM_KEY, &dkey_param, target, operation, len);
        PR_ASSERT(tkey2!=NULL);

	if(tkey1!=NULL) {
        PK11_FreeSymKey(tkey1);
	}

	return tkey2;

	}
	else {
	return PK11_Derive(base, mechanism, param, target, operation, keysize);
	}

}
Exemplo n.º 13
0
CryptoMd5
crypto_md5_init(void)
{
	CryptoMd5 md5 = xmalloc(sizeof(*md5));
	md5->context = PK11_CreateDigestContext(SEC_OID_MD5);
	SECStatus s = PK11_DigestBegin(md5->context);
	check(s, "Error initializing md5");
	return md5;
}
Exemplo n.º 14
0
CryptoSha1
crypto_sha1_init(void)
{
	CryptoSha1 sha1 = xmalloc(sizeof(*sha1));
	sha1->context = PK11_CreateDigestContext(SEC_OID_SHA1);
	SECStatus s = PK11_DigestBegin(sha1->context);
	check(s, "Error initializing sha1");
	return sha1;
}
Exemplo n.º 15
0
/* MD5 initialization. Begins an MD5 operation, writing a new context.
 */
void lsMD5Init(lsMD5_CTX *context)
{
	SECStatus status;

	context->ctx_nss = PK11_CreateDigestContext(SEC_OID_MD5);
	passert(context->ctx_nss != NULL);
	status = PK11_DigestBegin(context->ctx_nss);
	passert(status == SECSuccess);
}
Exemplo n.º 16
0
/* void reset (); */
NS_IMETHODIMP nsCryptoHMAC::Reset()
{
  nsNSSShutDownPreventionLock locker;

  SECStatus ss = PK11_DigestBegin(mHMACContext);
  NS_ENSURE_TRUE(ss == SECSuccess, NS_ERROR_FAILURE);

  return NS_OK;
}
Exemplo n.º 17
0
void sha256_init(sha256_context *ctx)
{
	DBG(DBG_CRYPT, DBG_log("NSS: sha256 init start"));
	SECStatus status;
	ctx->ctx_nss = NULL;
	ctx->ctx_nss = PK11_CreateDigestContext(SEC_OID_SHA256);
	PR_ASSERT(ctx->ctx_nss != NULL);
	status = PK11_DigestBegin(ctx->ctx_nss);
	PR_ASSERT(status == SECSuccess);
	DBG(DBG_CRYPT, DBG_log("NSS: sha256 init end"));
}
Exemplo n.º 18
0
/* Initialize the SHS values */
void shsInit(SHS_INFO *shsInfo)
{
    if (k5_nss_init()) {
        shsInfo->nss_ctxt = NULL;
        return;
    }
    shsInfo->nss_ctxt = PK11_CreateDigestContext(SEC_OID_SHA1);
    if (shsInfo->nss_ctxt == NULL)
        return;
    PK11_DigestBegin((PK11Context *)shsInfo->nss_ctxt);
}
Exemplo n.º 19
0
gboolean
crypto_md5_hash (const char *salt,
                 const gsize salt_len,
                 const char *password,
                 gsize password_len,
                 char *buffer,
                 gsize buflen,
                 GError **error)
{
	PK11Context *ctx;
	int nkey = buflen;
	unsigned int digest_len;
	int count = 0;
	char digest[MD5_HASH_LEN];
	char *p = buffer;

	if (salt)
		g_return_val_if_fail (salt_len >= 8, FALSE);

	g_return_val_if_fail (password != NULL, FALSE);
	g_return_val_if_fail (password_len > 0, FALSE);
	g_return_val_if_fail (buffer != NULL, FALSE);
	g_return_val_if_fail (buflen > 0, FALSE);

	ctx = PK11_CreateDigestContext (SEC_OID_MD5);
	if (!ctx) {
		g_set_error (error, NM_CRYPTO_ERROR,
		             NM_CRYPTO_ERR_MD5_INIT_FAILED,
		             _("Failed to initialize the MD5 context: %d."),
		             PORT_GetError ());
		return FALSE;
	}

	while (nkey > 0) {
		int i = 0;

		PK11_DigestBegin (ctx);
		if (count++)
			PK11_DigestOp (ctx, (const unsigned char *) digest, digest_len);
		PK11_DigestOp (ctx, (const unsigned char *) password, password_len);
		if (salt)
			PK11_DigestOp (ctx, (const unsigned char *) salt, 8); /* Only use 8 bytes of salt */
		PK11_DigestFinal (ctx, (unsigned char *) digest, &digest_len, sizeof (digest));

		while (nkey && (i < digest_len)) {
			*(p++) = digest[i++];
			nkey--;
		}
	}

	memset (digest, 0, sizeof (digest));
	PK11_DestroyContext (ctx, PR_TRUE);
	return TRUE;
}
Exemplo n.º 20
0
static void delivery_callback (
	cpg_handle_t handle,
	const struct cpg_name *groupName,
	uint32_t nodeid,
	uint32_t pid,
	void *msg,
	size_t msg_len)
{
	log_entry_t *log_pt;
	msg_t *msg_pt = (msg_t*)msg;
	msg_status_t status = MSG_OK;
	char status_buf[20];
	unsigned char sha1_compare[20];
	unsigned int sha1_len;

	if (record_messages_g == 0) {
		return;
	}

	if (nodeid != msg_pt->nodeid) {
		status = MSG_NODEID_ERR;
	}
	if (pid != msg_pt->pid) {
		status = MSG_PID_ERR;
	}
	if (msg_len != msg_pt->size) {
		status = MSG_SIZE_ERR;
	}
	PK11_DigestBegin(sha1_context);
	PK11_DigestOp(sha1_context, msg_pt->payload, (msg_pt->size - sizeof (msg_t)));
        PK11_DigestFinal(sha1_context, sha1_compare, &sha1_len, sizeof(sha1_compare));
	if (memcmp (sha1_compare, msg_pt->sha1, 20) != 0) {
		qb_log (LOG_ERR, "msg seq:%d; incorrect hash",
			msg_pt->seq);
		status = MSG_SHA1_ERR;
	}

	log_pt = malloc (sizeof(log_entry_t));
	qb_list_init (&log_pt->list);

	snprintf (log_pt->log, LOG_STR_SIZE, "%u:%d:%d:%s;",
		msg_pt->nodeid, msg_pt->seq, my_seq,
		err_status_string (status_buf, 20, status));
	qb_list_add_tail (&log_pt->list, &msg_log_head);
	total_stored_msgs++;
	total_msgs_revd++;
	my_seq++;

	if ((total_msgs_revd % 1000) == 0) {
		qb_log (LOG_INFO, "rx %d", total_msgs_revd);
	}
}
Exemplo n.º 21
0
Arquivo: nss.c Projeto: flashfoxter/sx
void sxi_sha256(const unsigned char *d, size_t n,unsigned char *md)
{
    unsigned len;
    PK11Context *context = PK11_CreateDigestContext(SEC_OID_SHA256);
    if (!context || PK11_DigestBegin(context) != SECSuccess ||
        PK11_DigestOp(context, d, n) != SECSuccess ||
        PK11_DigestFinal(context, md, &len, SHA256_DIGEST_LENGTH) != SECSuccess)
    {
        /* TODO: log */
    }
    if (context)
        PK11_DestroyContext(context, PR_TRUE);
}
Exemplo n.º 22
0
/*
 *  J A R _ c a l c u l a t e _ d i g e s t
 *
 *  Quick calculation of a digest for
 *  the specified block of memory. Will calculate
 *  for all supported algorithms, now MD5.
 *
 *  This version supports huge pointers for WIN16.
 *
 */
JAR_Digest * PR_CALLBACK 
JAR_calculate_digest(void *data, long length)
{
    PK11Context *md5  = 0;
    PK11Context *sha1 = 0;
    JAR_Digest *dig   = PORT_ZNew(JAR_Digest);
    long chunq;
    unsigned int md5_length, sha1_length;

    if (dig == NULL) {
	/* out of memory allocating digest */
	return NULL;
    }

    md5  = PK11_CreateDigestContext(SEC_OID_MD5);
    sha1 = PK11_CreateDigestContext(SEC_OID_SHA1);

    if (length >= 0) {
	PK11_DigestBegin (md5);
	PK11_DigestBegin (sha1);

	do {
	    chunq = length;

	    PK11_DigestOp(md5,  (unsigned char*)data, chunq);
	    PK11_DigestOp(sha1, (unsigned char*)data, chunq);
	    length -= chunq;
	    data = ((char *) data + chunq);
	}
	while (length > 0);

	PK11_DigestFinal (md5,	dig->md5,  &md5_length,  MD5_LENGTH);
	PK11_DigestFinal (sha1, dig->sha1, &sha1_length, SHA1_LENGTH);

	PK11_DestroyContext (md5,  PR_TRUE);
	PK11_DestroyContext (sha1, PR_TRUE);
    }
    return dig;
}
/*
 * @param(IN) salt  salt in binary format
 * @param(IN) saltSize   number of bytes for the salt
 * @param(IN) clearPasswd clearPasswd
 * @param(OUT) the hashed password with salt in ascii b64 format
 *
 * #sample keyfile line
 * j2ee;{SSHA}WRWaz20fzw3zN9x5Uzyyk5Wfvrbe4m40rYTPrA==;staff,eng
 */
void sshaPasswd(const char* salt, const int saltSize,const char* clearPasswd,NSString& hashed)
{
    //PRBool workaround= PR_FALSE; //PR_TRUE;
    const int digestLen = SHA1_LENGTH;  //20
    unsigned char H[512];
    char* pwdAndSalt=NULL;
    
    hashed.clear();
    if (!clearPasswd) {
        return;
    }
    int tobeHashedLen = 0;
    pwdAndSalt = addSalt(clearPasswd, salt, saltSize,tobeHashedLen);

        //if (workaround==PR_TRUE) {
        //https_SHA1_Hash(H,pwdAndSalt); //refer lib/libadmin/password.cpp
        //} else {
        //const int keylen = PRIVATE_KEY_LEN;
        //unsigned char DigestPrivatekey[PRIVATE_KEY_LEN];
        //PK11_GenerateRandom(DigestPrivatekey, keylen);

        PK11Context * SHA1Ctx = PK11_CreateDigestContext(SEC_OID_SHA1);
        if (SHA1Ctx==NULL) {
            FREE(pwdAndSalt);
            return;            
        }
        PK11_DigestBegin(SHA1Ctx);
        //PK11_DigestOp(SHA1Ctx, (unsigned char*)pwdAndSalt, strlen(pwdAndSalt) );
        PK11_DigestOp(SHA1Ctx, (unsigned char*)pwdAndSalt, tobeHashedLen );
        PK11_DigestFinal(SHA1Ctx, (unsigned char *)H, (unsigned int*)&digestLen, sizeof(H));
        PK11_DestroyContext(SHA1Ctx, 1);
        PR_ASSERT(digestLen==20);
        //}

    char* base64Val=NULL;
    if (salt!=NULL && saltSize>0) {
        memcpy(H+20,salt,saltSize);   //append salt to hashed passwd
        base64Val = BTOA_DataToAscii(H,digestLen+saltSize);   //base64.h
    } else {
        base64Val = BTOA_DataToAscii(H,digestLen);   //base64.h
    }

    hashed.append(SSHA_TAG );
    hashed.append(base64Val);

    if (base64Val)
        PORT_Free(base64Val);
    base64Val = NULL;
    FREE(pwdAndSalt);
    return;
}
Exemplo n.º 24
0
static int nr_crypto_nss_hmac(UCHAR *key, int keyl, UCHAR *buf, int bufl,
                              UCHAR *result) {
  CK_MECHANISM_TYPE mech = CKM_SHA_1_HMAC;
  PK11SlotInfo *slot = 0;
  MOZ_ASSERT(keyl > 0);
  SECItem keyi = { siBuffer, key, static_cast<unsigned int>(keyl)};
  PK11SymKey *skey = 0;
  PK11Context *hmac_ctx = 0;
  SECStatus status;
  unsigned int hmac_len;
  SECItem param = { siBuffer, nullptr, 0 };
  int err = R_INTERNAL;

  slot = PK11_GetInternalKeySlot();
  if (!slot)
    goto abort;

  skey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap,
                          CKA_SIGN, &keyi, nullptr);
  if (!skey)
    goto abort;


  hmac_ctx = PK11_CreateContextBySymKey(mech, CKA_SIGN,
                                        skey, &param);
  if (!hmac_ctx)
    goto abort;

  status = PK11_DigestBegin(hmac_ctx);
  if (status != SECSuccess)
    goto abort;

  status = PK11_DigestOp(hmac_ctx, buf, bufl);
  if (status != SECSuccess)
    goto abort;

  status = PK11_DigestFinal(hmac_ctx, result, &hmac_len, 20);
  if (status != SECSuccess)
    goto abort;

  MOZ_ASSERT(hmac_len == 20);

  err = 0;

 abort:
  if(hmac_ctx) PK11_DestroyContext(hmac_ctx, PR_TRUE);
  if (skey) PK11_FreeSymKey(skey);
  if (slot) PK11_FreeSlot(slot);

  return err;
}
Exemplo n.º 25
0
/*
 * This code is mostly cargo-cult taken from here:
 *   http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn5.html
 *
 * It should implement HMAC with the given mechanism (SHA: 1, 256, 384, 512).
 */
static bool hmac(SECItem *key, CK_MECHANISM_TYPE mech, const SECItem *in,
                 struct digest_buffer *out)
{
    SECItem param = { siBuffer, NULL, 0 };
    PK11SlotInfo *slot = NULL;
    PK11SymKey *symkey = NULL;
    PK11Context *ctx = NULL;
    bool ret = false;
    SECStatus s;

    slot = PK11_GetBestSlot(mech, NULL);
    if (slot == NULL) {
        slot = PK11_GetInternalKeySlot();
        if (slot == NULL) {
            goto done;
        }
    }

    symkey = PK11_ImportSymKey(slot, mech, PK11_OriginUnwrap,
                               CKA_SIGN, key, NULL);
    if (symkey == NULL)
        goto done;

    ctx = PK11_CreateContextBySymKey(mech, CKA_SIGN, symkey, &param);
    if (ctx == NULL)
        goto done;

    s = PK11_DigestBegin(ctx);
    if (s != SECSuccess)
        goto done;

    s = PK11_DigestOp(ctx, in->data, in->len);
    if (s != SECSuccess)
        goto done;

    s = PK11_DigestFinal(ctx, out->buf, &out->len, sizeof(out->buf));
    if (s != SECSuccess)
        goto done;

    ret = true;

done:
    if (ctx != NULL)
        PK11_DestroyContext(ctx, PR_TRUE);
    if (symkey != NULL)
        PK11_FreeSymKey(symkey);
    if (slot != NULL)
        PK11_FreeSlot(slot);
    return ret;
}
Exemplo n.º 26
0
static int
DigestFile(FILE *outFile, FILE *inFile, SECOidData *hashOID)
{
    int nb;
    unsigned char ibuf[4096], digest[32];
    PK11Context *hashcx;
    unsigned int len;
    SECStatus rv;

    hashcx = PK11_CreateDigestContext(hashOID->offset);
    if (hashcx == NULL) {
	return -1;
    }
    PK11_DigestBegin(hashcx);


    for (;;) {
	if (feof(inFile)) break;
	nb = fread(ibuf, 1, sizeof(ibuf), inFile);
	if (nb != sizeof(ibuf)) {
	    if (nb == 0) {
		if (ferror(inFile)) {
		    PORT_SetError(SEC_ERROR_IO);
		    PK11_DestroyContext(hashcx,PR_TRUE);
		    return -1;
		}
		/* eof */
		break;
	    }
	}
	rv = PK11_DigestOp(hashcx, ibuf, nb);
	if (rv != SECSuccess) {
	   PK11_DestroyContext(hashcx, PR_TRUE);
	   return -1;
	}
    }

    rv = PK11_DigestFinal(hashcx, digest, &len, 32);
    PK11_DestroyContext(hashcx, PR_TRUE);

    if (rv != SECSuccess) return -1;

    nb = fwrite(digest, 1, len, outFile);
    if (nb != len) {
	PORT_SetError(SEC_ERROR_IO);
	return -1;
    }

    return 0;
}
Exemplo n.º 27
0
void
hmac_final(u_char *output, struct hmac_ctx *ctx)
{
#ifndef HAVE_LIBNSS
    const struct hash_desc *h = ctx->h;

    h->hash_final(output, &ctx->hash_ctx);

    h->hash_init(&ctx->hash_ctx);
    h->hash_update(&ctx->hash_ctx, ctx->buf2, HMAC_BUFSIZE);
    h->hash_update(&ctx->hash_ctx, output, h->hash_digest_len);
    h->hash_final(output, &ctx->hash_ctx);
#else
    unsigned int outlen = 0;
    SECStatus status = PK11_DigestFinal(ctx->ctx_nss, output, &outlen, ctx->hmac_digest_len);
    PR_ASSERT(status == SECSuccess);
    PR_ASSERT(outlen == ctx->hmac_digest_len);
    PK11_DestroyContext(ctx->ctx_nss, PR_TRUE);
    ctx->ctx_nss = NULL;

    ctx->ctx_nss = PK11_CreateDigestContext(nss_hash_oid(ctx->h));
    PR_ASSERT(ctx->ctx_nss!=NULL);

    status=PK11_DigestBegin(ctx->ctx_nss);
    PR_ASSERT(status==SECSuccess);

    status=PK11_DigestKey(ctx->ctx_nss, ctx->okey);
    PR_ASSERT(status==SECSuccess);

    status = PK11_DigestOp(ctx->ctx_nss, output, outlen);
    PR_ASSERT(status == SECSuccess);

    status = PK11_DigestFinal(ctx->ctx_nss, output, &outlen, ctx->hmac_digest_len);
    PR_ASSERT(status == SECSuccess);
    PR_ASSERT(outlen == ctx->hmac_digest_len);
    PK11_DestroyContext(ctx->ctx_nss, PR_TRUE);

    if(ctx->ikey !=NULL) {
    PK11_FreeSymKey(ctx->ikey);
    }
    if(ctx->okey != NULL) {
    PK11_FreeSymKey(ctx->okey);
    }
    /* DBG(DBG_CRYPT, DBG_log("NSS: hmac final end")); */
#endif
}
Exemplo n.º 28
0
    void clear()
    {
	SECStatus s;

	PK11_DestroyContext(m_context, PR_TRUE);

	m_context = PK11_CreateDigestContext(m_hashAlgo);
	if (! m_context) {
	    qDebug() << "CreateDigestContext failed";
	    return;
	}

	s = PK11_DigestBegin(m_context);
	if (s != SECSuccess) {
	    qDebug() << "DigestBegin failed";
	    return;
	}
    }
Exemplo n.º 29
0
// Let derIssuer be the DER encoding of the issuer of aCert.
// Let derPublicKey be the DER encoding of the public key of aIssuerCert.
// Let serialNumber be the bytes of the serial number of aCert.
// The value calculated is SHA384(derIssuer || derPublicKey || serialNumber).
// Because the DER encodings include the length of the data encoded,
// there do not exist A(derIssuerA, derPublicKeyA, serialNumberA) and
// B(derIssuerB, derPublicKeyB, serialNumberB) such that the concatenation of
// each triplet results in the same string of bytes but where each part in A is
// not equal to its counterpart in B. This is important because as a result it
// is computationally infeasible to find collisions that would subvert this
// cache (given that SHA384 is a cryptographically-secure hash function).
static SECStatus
CertIDHash(SHA384Buffer& buf, const CertID& certID, const char* aIsolationKey)
{
  ScopedPK11Context context(PK11_CreateDigestContext(SEC_OID_SHA384));
  if (!context) {
    return SECFailure;
  }
  SECStatus rv = PK11_DigestBegin(context.get());
  if (rv != SECSuccess) {
    return rv;
  }
  SECItem certIDIssuer = UnsafeMapInputToSECItem(certID.issuer);
  rv = PK11_DigestOp(context.get(), certIDIssuer.data, certIDIssuer.len);
  if (rv != SECSuccess) {
    return rv;
  }
  SECItem certIDIssuerSubjectPublicKeyInfo =
    UnsafeMapInputToSECItem(certID.issuerSubjectPublicKeyInfo);
  rv = PK11_DigestOp(context.get(), certIDIssuerSubjectPublicKeyInfo.data,
                     certIDIssuerSubjectPublicKeyInfo.len);
  if (rv != SECSuccess) {
    return rv;
  }
  SECItem certIDSerialNumber =
    UnsafeMapInputToSECItem(certID.serialNumber);
  rv = PK11_DigestOp(context.get(), certIDSerialNumber.data,
                     certIDSerialNumber.len);
  if (rv != SECSuccess) {
    return rv;
  }
  if (aIsolationKey) {
    rv = PK11_DigestOp(context.get(), (const unsigned char*) aIsolationKey,
                       strlen(aIsolationKey));
    if (rv != SECSuccess) {
      return rv;
    }
  }
  uint32_t outLen = 0;
  rv = PK11_DigestFinal(context.get(), buf, &outLen, SHA384_LENGTH);
  if (outLen != SHA384_LENGTH) {
    return SECFailure;
  }
  return rv;
}
Exemplo n.º 30
0
char *oauth_sign_hmac_sha1_raw (const char *m, const size_t ml, const char *k, const size_t kl) {
  PK11SlotInfo  *slot = NULL;
  PK11SymKey    *pkey = NULL;
  PK11Context   *context = NULL;
  unsigned char  digest[20]; // Is there a way to tell how large the output is?
  unsigned int   len;
  SECStatus      s;
  SECItem        keyItem, noParams;
  char          *rv=NULL;

  keyItem.type = siBuffer;
  keyItem.data = (unsigned char*) k;
  keyItem.len = kl;

  noParams.type = siBuffer;
  noParams.data = NULL;
  noParams.len = 0;

  oauth_init_nss();

  slot = PK11_GetInternalKeySlot();
  if (!slot) goto looser;
  pkey = PK11_ImportSymKey(slot, CKM_SHA_1_HMAC, PK11_OriginUnwrap, CKA_SIGN, &keyItem, NULL);
  if (!pkey)  goto looser;
  context = PK11_CreateContextBySymKey(CKM_SHA_1_HMAC, CKA_SIGN, pkey, &noParams);
  if (!context) goto looser;

  s = PK11_DigestBegin(context);
  if (s != SECSuccess) goto looser;
  s = PK11_DigestOp(context, (unsigned char*) m, ml);
  if (s != SECSuccess) goto looser;
  s = PK11_DigestFinal(context, digest, &len, sizeof digest);
  if (s != SECSuccess) goto looser;

  rv=oauth_encode_base64(len, digest);

looser:
  if (context) PK11_DestroyContext(context, PR_TRUE);
  if (pkey) PK11_FreeSymKey(pkey);
  if (slot) PK11_FreeSlot(slot);
  return rv;
}