Example #1
0
/* Generate HMAC-SHA1 intermediate Hash */
static
void sa_hmac_sha1_get_pad(const u8 *key, u16 key_sz, u32 *ipad, u32 *opad)
{
	u32 ws[SHA_WORKSPACE_WORDS];
	u8 k_ipad[SHA_MESSAGE_BYTES];
	u8 k_opad[SHA_MESSAGE_BYTES];
	int i;

	for (i = 0; i < key_sz; i++) {
		k_ipad[i] = key[i] ^ 0x36;
		k_opad[i] = key[i] ^ 0x5c;
	}
	/* Instead of XOR with 0 */
	for (; i < SHA_MESSAGE_BYTES; i++) {
		k_ipad[i] = 0x36;
		k_opad[i] = 0x5c;
	}

	/* SHA-1 on k_ipad */
	sha_init(ipad);
	sha_transform(ipad, k_ipad, ws);

	for (i = 0; i < SHA_DIGEST_WORDS; i++)
		ipad[i] = cpu_to_be32(ipad[i]);

	/* SHA-1 on k_opad */
	sha_init(opad);
	sha_transform(opad, k_opad, ws);

	for (i = 0; i < SHA_DIGEST_WORDS; i++)
		opad[i] = cpu_to_be32(opad[i]);
}
Example #2
0
int NET_CookieHash(netadr_t *from){

    uint32_t digest[5];
    uint32_t workspace[80];
    char data[64];
    int i;

    if(from->type == NA_IP){

        for(i = 0; i < 4; i++)
            data[i] = from->ip[i];

        *((unsigned short*)&data[4]) = from->port;

        Com_Memcpy(&data[6], net_cookieSecret, sizeof(net_cookieSecret));

    }else if(from->type == NA_IP6){
        for(i = 0; i < 16; i++)
            data[i] = from->ip[i];

        *((unsigned short*)&data[16]) = from->port;

        Com_Memcpy(&data[18], net_cookieSecret, sizeof(net_cookieSecret) - 46);

    }else
        return 0;

    sha_init(digest);

    sha_transform(digest, data, workspace);

    return digest[0];
}
Example #3
0
void test_run() {
  sha_init(&sha_info);
  for(int n = 0; n < 4; ++n) {
    sha_update(&sha_info, data + 4 * n, 256);
  }
  sha_final(&sha_info);
}
Example #4
0
/*
 * Create a DiscID based on the TOC data found in the DiscId object.
 * The DiscID is placed in the provided string buffer.
 */
static void create_disc_id(mb_disc_private *d, char buf[]) {
	SHA_INFO	sha;
	unsigned char	digest[20], *base64;
	unsigned long	size;
	char		tmp[17]; /* for 8 hex digits (16 to avoid trouble) */
	int		i;

	assert( d != NULL );

	sha_init(&sha);

	sprintf(tmp, "%02X", d->first_track_num);
	sha_update(&sha, (unsigned char *) tmp, strlen(tmp));

	sprintf(tmp, "%02X", d->last_track_num);
	sha_update(&sha, (unsigned char *) tmp, strlen(tmp));

	for (i = 0; i < 100; i++) {
		sprintf(tmp, "%08X", d->track_offsets[i]);
		sha_update(&sha, (unsigned char *) tmp, strlen(tmp));
	}

	sha_final(digest, &sha);

	base64 = rfc822_binary(digest, sizeof(digest), &size);

	memcpy(buf, base64, size);
	buf[size] = '\0';

	free(base64);
}
Example #5
0
VOID NextBitLoc( ULONG *resx, ULONG *resy, UWORD width, UWORD height )
{
    ULONG  x, y, hash;
    SHA_INFO sha = {0};

    y = counter / width;
    x = counter % width;

    // First iteration

    sha_init(&sha);
    sha_update( &sha, key, SHA_DIGESTSIZE );
    sha_update( &sha, (UBYTE *)&x, sizeof(x) );
    sha_final( &sha );
    D(sha_print( &sha ));
    hash = (sha.digest[0] & 0x7fffffff); // Lose the sign

    y = (y+hash) % height;

    // Second iteration

    sha_init(&sha);
    sha_update( &sha, key, SHA_DIGESTSIZE );
    sha_update( &sha, (UBYTE *)&y, sizeof(y) );
    sha_final( &sha );
    D(sha_print( &sha ));
    hash = (sha.digest[0] & 0x7fffffff); // Lose the sign

    x = (x+hash) % width;

    // Third iteration

    sha_init(&sha);
    sha_update( &sha, key, SHA_DIGESTSIZE );
    sha_update( &sha, (UBYTE *)&x, sizeof(x) );
    sha_final( &sha );
    D(sha_print( &sha ));
    hash = (sha.digest[0] & 0x7fffffff); // Lose the sign

    y = (y+hash) % height;

    *resx = x;
    *resy = y;

    ++counter;
}
Example #6
0
char *shahash(const char *str) 
{
	char read_buffer[65];
	//int read_buffer[64];
	int c=1, i;
       
	INT64 length=0;

	int strsz;
	static char final[40];
	int *hashval;

	hashval = (int *)malloc(20);

	sha_init(hashval);

	strsz = strlen(str);

	if(strsz == 0) 
	{
	     memset(read_buffer, 0, 65);
	     read_buffer[0] = 0x80;
	     sha_hash((int *)read_buffer, hashval);
	}

	while (strsz>0) 
	{
		memset(read_buffer, 0, 65);
		strncpy((char*)read_buffer, str, 64);
		c = strlen((char *)read_buffer);
		length+=c;
		strsz-=c;
		if (strsz<=0) 
		{
			length<<=3;	
			read_buffer[c]=(char)0x80;
			for (i=c+1; i<64; i++) 
				read_buffer[i]=0;
			if (c>55) 
			{
				/* we need to do an entire new block */
				sha_hash((int *)read_buffer, hashval);
				for (i=0; i<14; i++) 
					((int*)read_buffer)[i]=0;
			}      
#ifndef WORDS_BIGENDIAN
			for (i=0; i<8; i++) 
			{
				read_buffer[56+i]=(char)(length>>(56-(i*8))) & 0xff;
			}
#else	
			memcpy(read_buffer+56, &length, 8);
#endif
		}
		
		sha_hash((int *)read_buffer, hashval);
		str+=64;
	}
Example #7
0
PERROR MakeKeyMaterial( FRAME *frame, UBYTE *passphrase, struct PPTBase *PPTBase )
{
    ROWPTR cp, tmprow;
    WORD row;
    struct ExecBase *SysBase = PPTBase->lb_Sys;
    SHA_INFO sha = {0};
    PERROR res = PERR_OK;

    sha_init( &sha );

    InitProgress(frame,"Building key...", 0, frame->pix->height );

    /*
     *  First, use the passphrase for the key.
     */

    if( strlen(passphrase) > 0 ) sha_update( &sha, passphrase, strlen(passphrase) );

    if( tmprow = AllocVec( frame->pix->bytes_per_row, 0L ) ) {
        for( row = 0; row < frame->pix->height; row++ ) {
            WORD col;

            cp = GetPixelRow( frame, row );

            if( Progress( frame, row ) ) {
                res = PERR_BREAK;
                break;
            }

            for( col = 0; col < frame->pix->bytes_per_row; col++ ) {
                /* Use only significant bytes */
                tmprow[col] = cp[col] & 0xFE;
            }

            sha_update( &sha, tmprow, frame->pix->bytes_per_row );
        }

        // Use the passphrase again (why?)

        if( strlen(passphrase) > 0 ) sha_update( &sha, passphrase, strlen(passphrase) );

        FinishProgress( frame );
        sha_final( &sha );

        memcpy( key, &sha.digest[0], SHA_DIGESTSIZE );

        D(sha_print( &sha ) );

        FreeVec( tmprow );
    } else {
        SetErrorCode( frame, PERR_OUTOFMEMORY );
        res = PERR_OUTOFMEMORY;
    }

    return res;
}
int ctr_nand_crypto_interface_initialize(ctr_nand_crypto_interface *crypto_io, uint8_t keySlot, ctr_nand_crypto_type crypto_type, ctr_io_interface *lower_io)
{
	crypto_io->base = nand_crypto_base;

	//Get the nonces for CTRNAND and TWL decryption
	uint32_t mode;
	uint32_t NandCid[4];
	alignas(4) uint8_t shasum[32];

	sdmmc_get_cid(true, NandCid);
	uint32_t ctr[4];

	switch (crypto_type)
	{
		case NAND_CTR:
			check_and_do_n3ds_init();
			sha_init(SHA256_MODE);
			sha_update((uint8_t*)NandCid, 16);
			sha_get(shasum);
			memcpy(ctr, shasum, 16);
			mode = AES_CNT_CTRNAND_MODE;
			break;

		case NAND_TWL:
			check_and_do_twl_init();
			sha_init(SHA1_MODE);
			sha_update((uint8_t*)NandCid, 16);
			sha_get(shasum);
			for(uint32_t i = 0; i < 16u; i++) // little endian and reversed order
			{
				((uint8_t*)ctr)[i] = shasum[15-i];
			}
			mode = AES_CNT_TWLNAND_MODE;
			break;

		default:
			return 1; //Unknown type
	}

	ctr_crypto_interface_initialize(&crypto_io->crypto_io, keySlot, mode, CTR_CRYPTO_ENCRYPTED, CRYPTO_CTR, (uint8_t*)ctr, lower_io);
	return 0;
}
Example #9
0
CK_RV
digest_mgr_init( STDLL_TokData_t   *tokdata,
		 SESSION           *sess,
                 DIGEST_CONTEXT    *ctx,
                 CK_MECHANISM      *mech )
{
   CK_RV rc = CKR_OK;
   CK_BYTE  * ptr = NULL;

   if (!sess || !ctx){
      TRACE_ERROR("Invalid function arguments.\n");
      return CKR_FUNCTION_FAILED;
   }
   if (ctx->active != FALSE){
      TRACE_ERROR("%s\n", ock_err(ERR_OPERATION_ACTIVE));
      return CKR_OPERATION_ACTIVE;
   }
   // is the mechanism supported?  is the parameter present if required?
   //
   switch (mech->mechanism) {
      case CKM_SHA_1:
      case CKM_SHA256:
      case CKM_SHA384:
      case CKM_SHA512:
         {
            if (mech->ulParameterLen != 0){
               TRACE_ERROR("%s\n", ock_err(ERR_MECHANISM_PARAM_INVALID));
               return CKR_MECHANISM_PARAM_INVALID;
            }

            ctx->context = NULL;
            rc = sha_init(tokdata, sess, ctx, mech);
            if (rc != CKR_OK) {
               digest_mgr_cleanup(ctx);  // to de-initialize context above
	       TRACE_ERROR("Failed to init sha context.\n");
               return rc;
            }
         }
         break;

      case CKM_MD2:
         {
            if (mech->ulParameterLen != 0){
               TRACE_ERROR("%s\n", ock_err(ERR_MECHANISM_PARAM_INVALID));
               return CKR_MECHANISM_PARAM_INVALID;
            }
            ctx->context_len = sizeof(MD2_CONTEXT);
            ctx->context     = (CK_BYTE *)malloc(sizeof(MD2_CONTEXT));
            if (!ctx->context){
               digest_mgr_cleanup(ctx);  // to de-initialize context above
               TRACE_ERROR("%s\n", ock_err(ERR_HOST_MEMORY));
               return CKR_HOST_MEMORY;
            }
            memset( ctx->context, 0x0, sizeof(MD2_CONTEXT) );
         }
         break;

      case CKM_MD5:
         {
            if (mech->ulParameterLen != 0){
               TRACE_ERROR("%s\n", ock_err(ERR_MECHANISM_PARAM_INVALID));
               return CKR_MECHANISM_PARAM_INVALID;
            }
            ctx->context_len = sizeof(MD5_CONTEXT);
            ctx->context     = (CK_BYTE *)malloc(sizeof(MD5_CONTEXT));
            if (!ctx->context){
               digest_mgr_cleanup(ctx);  // to de-initialize context above
               TRACE_ERROR("%s\n", ock_err(ERR_HOST_MEMORY));
               return CKR_HOST_MEMORY;
            }
            ckm_md5_init( tokdata, (MD5_CONTEXT *)ctx->context );
         }
         break;

      default:
         TRACE_ERROR("%s\n", ock_err(ERR_MECHANISM_INVALID));
         return CKR_MECHANISM_INVALID;
   }

   if (mech->ulParameterLen > 0) {
      ptr = (CK_BYTE *)malloc(mech->ulParameterLen);
      if (!ptr){
         digest_mgr_cleanup(ctx);  // to de-initialize context above
         TRACE_ERROR("%s\n", ock_err(ERR_HOST_MEMORY));
         return CKR_HOST_MEMORY;
      }
      memcpy( ptr, mech->pParameter, mech->ulParameterLen );
   }
   ctx->mech.ulParameterLen = mech->ulParameterLen;
   ctx->mech.mechanism      = mech->mechanism;
   ctx->mech.pParameter     = ptr;
   ctx->multi               = FALSE;
   ctx->active              = TRUE;

   return CKR_OK;
}
Example #10
0
char *par_mktmpdir ( char **argv ) {
    int i;
    const char *tmpdir = NULL;
    const char *key = NULL , *val = NULL;

    /* NOTE: all arrays below are NULL terminated */
    const char *temp_dirs[] = { 
        P_tmpdir, 
#ifdef WIN32
        "C:\\TEMP", 
#endif
        ".", NULL };
    const char *temp_keys[] = { "PAR_TMPDIR", "TMPDIR", "TEMPDIR", 
                                 "TEMP", "TMP", NULL };
    const char *user_keys[] = { "USER", "USERNAME", NULL };

    const char *subdirbuf_prefix = "par-";
    const char *subdirbuf_suffix = "";

    char *progname = NULL, *username = NULL;
    char *stmpdir = NULL, *top_tmpdir = NULL;
    int f, j, k, stmp_len = 0;
    char sha1[41];
    SHA_INFO sha_info;
    unsigned char buf[32768];
    unsigned char sha_data[20];

    if ( (val = par_getenv(PAR_TEMP)) && strlen(val) ) {
        par_setup_libpath(val);
        return strdup(val);
    }

#ifdef WIN32
    {
        DWORD buflen = MAXPATHLEN;
        username = malloc(MAXPATHLEN);
        GetUserName((LPTSTR)username, &buflen);
        // FIXME this is uncondifionally overwritten below - WTF?
    }
#endif

    /* Determine username */
    username = get_username_from_getpwuid();
    if ( !username ) { /* fall back to env vars */
        for ( i = 0 ; username == NULL && (key = user_keys[i]); i++) {
            if ( (val = par_getenv(key)) && strlen(val) ) 
                username = strdup(val);
        }
    }
    if ( username == NULL )
        username = "******";
   
    /* sanitize username: encode all bytes as 2 hex digits */
    {
        char *hexname = malloc(2 * strlen(username) + 1);
        char *u, *h;
        for ( u = username, h = hexname ; *u != '\0' ; u++, h += 2)
            sprintf(h, "%02x", *(unsigned char*)u);
        username = hexname;
    }

    /* Try temp environment variables */
    for ( i = 0 ; tmpdir == NULL && (key = temp_keys[i]); i++ ) {
        if ( (val = par_getenv(key)) && strlen(val) && isWritableDir(val) ) {
            tmpdir = strdup(val);
            break;
        }
    }

#ifdef WIN32
    /* Try the windows temp directory */
    if ( tmpdir == NULL && (val = par_getenv("WinDir")) && strlen(val) ) {
        char* buf = malloc(strlen(val) + 5 + 1);
        sprintf(buf, "%s\\temp", val);
        if (isWritableDir(buf)) {
            tmpdir = buf;
        } else {
            free(buf);
        }
    }
#endif

    /* Try default locations */
    for ( i = 0 ; tmpdir == NULL && (val = temp_dirs[i]) && strlen(val) ; i++ ) {
        if ( isWritableDir(val) ) {
            tmpdir = strdup(val);
        }
    }

    /* "$TEMP/par-$USER" */
    stmp_len = 
        strlen(tmpdir) +
        strlen(subdirbuf_prefix) +
        strlen(username) +
        strlen(subdirbuf_suffix) + 1024;

    /* stmpdir is what we are going to return; 
       top_tmpdir is the top $TEMP/par-$USER, needed to build stmpdir.  
       NOTE: We need 2 buffers because snprintf() can't write to a buffer
       it is also reading from. */
    top_tmpdir = malloc( stmp_len );
    sprintf(top_tmpdir, "%s%s%s%s", tmpdir, dir_sep, subdirbuf_prefix, username);
#ifdef WIN32
    _mkdir(top_tmpdir);         /* FIXME bail if error (other than EEXIST) */
#else
    {
        if (mkdir(top_tmpdir, 0700) == -1 && errno != EEXIST) {
            fprintf(stderr, "%s: creation of private subdirectory %s failed (errno=%i)\n", 
                    argv[0], top_tmpdir, errno);
            return NULL;
        }

        if (!isSafeDir(top_tmpdir)) {
            fprintf(stderr, "%s: private subdirectory %s is unsafe (please remove it and retry your operation)\n",
                    argv[0], top_tmpdir);
            return NULL;
        }
    }
#endif

    stmpdir = malloc( stmp_len );

    /* Doesn't really work - XXX */
    val = par_getenv( "PATH" );
    if (val != NULL)
        progname = par_findprog(argv[0], strdup(val));
    if (progname == NULL)
        progname = argv[0];

    /* If invoked as "/usr/bin/parl foo.par myscript.pl" then progname should
     * be ".../parl", and we don't want to base our checksum on that, but
     * rather on "foo.par".
     */
    {
#ifdef WIN32
#define STREQ(a,b) (strcasecmp(a,b) == 0)
#else
#define STREQ(a,b) (strcmp(a,b) == 0)
#endif
	int prog_len = strlen(progname);
	int parl_len = strlen(PARL_EXE);

	if (prog_len >= parl_len
	    && STREQ(progname + prog_len - parl_len, PARL_EXE)
	    && (prog_len == parl_len || progname[prog_len - parl_len - 1] == dir_sep[0])
	    && argv[1]
	    && strlen(argv[1]) >= 4
	    && STREQ(argv[1] + strlen(argv[1]) - 4, ".par"))
		progname = argv[1];
#undef STREQ
    }

    if ( !par_env_clean() && (f = open( progname, O_RDONLY | OPEN_O_BINARY ))) {
        lseek(f, -18, 2);
        read(f, buf, 6);
        if(buf[0] == 0 && buf[1] == 'C' && buf[2] == 'A' && buf[3] == 'C' && buf[4] == 'H' && buf[5] == 'E') {
            /* pre-computed cache_name in this file */
            /* "$TEMP/par-$USER/cache-$cache_name" */
            lseek(f, -58, 2);
            read(f, buf, 41);
            sprintf(
                stmpdir,
                "%s%scache-%s%s",
                top_tmpdir, dir_sep, buf, subdirbuf_suffix
            );
        }
        else {
            /* "$TEMP/par-$USER/cache-$SHA1" */
	    lseek(f, 0, 0);
            sha_init( &sha_info );
            while( ( j = read( f, buf, sizeof( buf ) ) ) > 0 )
            {
                sha_update( &sha_info, buf, j );
            }
            close( f );
            sha_final( sha_data, &sha_info );
            for( k = 0; k < 20; k++ )
            {
                sprintf( sha1+k*2, "%02x", sha_data[k] );
            }
            sha1[40] = '\0';
            sprintf(
                stmpdir,
                "%s%scache-%s%s",
                top_tmpdir, dir_sep, sha1, subdirbuf_suffix
            );
        }
    }
    else {
        int i = 0;

        /* "$TEMP/par-$USER/temp-$PID" */

        par_setenv("PAR_CLEAN", "1");
        sprintf(
            stmpdir,
            "%s%stemp-%u%s",
            top_tmpdir, dir_sep, getpid(), subdirbuf_suffix
        );

        /* Ensure we pick an unused directory each time.  If the directory
           already exists when we try to create it, bump a counter and try
           "$TEMP/par-$USER/temp-$PID-$i". This will guard against cases where
           a prior invocation crashed leaving garbage in a temp directory that
           might interfere. */

        while (my_mkdir(stmpdir, 0700) == -1 && errno == EEXIST) {
            sprintf(
                stmpdir,
                "%s%stemp-%u-%u%s",
                top_tmpdir, dir_sep, getpid(), ++i, subdirbuf_suffix
                );
        }
    }

    free(top_tmpdir);

    /* set dynamic loading path */
    par_setenv(PAR_TEMP, stmpdir);

    par_setup_libpath( stmpdir );

    return stmpdir;
}
Example #11
0
nyx_error_t security_init_hash(nyx_device_handle_t d, const char *hash_algo)
{
	return sha_init(hash_algo);
}
Example #12
0
/*
 * hash the password
 */
void do_sha_hash(int *hashval, int *pw)
{
	sha_init(hashval);
	sha_hash(pw, hashval);
}