/*******************************************************************************
* Function Name  : decrypt_pdu_cbc
* Description    : Decrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input cipher data address
*                  - int: length
* Output         : output_pointer: output plain data address
* Return         : None
*******************************************************************************/
void decrypt_pdu_cbc(u32 *exp_key, unsigned char *cipher,int len, unsigned char *plain)
{
  n_blocks = len / 16;
  n_remain = len % 16;
  uint8_t tempbuff[64];
  
  /*Decryption starts here..................*/
  memcpy( RevBuff, cipher, len );
  for ( index=0; index<n_blocks; index++ )
  {
    for(uint8_t i=0; i<16; i++)
    {
      buff[i] = RevBuff[(index*16)+i];
    }
    AES_decrypt(buff,(u32*)aes_out,exp_key);
    memcpy( tempbuff, aes_out, 16 );    
    for(uint8_t i =0; i<16; i++)
    {
      for(uint8_t ctr =0; ctr<4;ctr++)
      {
        temp[ctr+i*4] =   tempbuff[(3-ctr)+(i*4)];
      }
    }
    
    bitwise_xor(temp,&AES_InitnalizationVector_Rx[0], &plain[index*16]);
    memcpy( AES_InitnalizationVector_Rx, buff, 16 );
  }/*decription of n_blocks completed*/
}
Beispiel #2
0
void build_light_cache(hash512* cache, int num_items, const hash256& seed) noexcept
{
    hash512 item = keccak512(seed.bytes, sizeof(seed));
    cache[0] = item;
    for (int i = 1; i < num_items; ++i)
    {
        item = keccak512(item);
        cache[i] = item;
    }

    for (int q = 0; q < light_cache_rounds; ++q)
    {
        for (int i = 0; i < num_items; ++i)
        {
            const uint32_t index_limit = static_cast<uint32_t>(num_items);

            // Fist index: 4 first bytes of the item as little-endian integer.
            uint32_t t = fix_endianness(cache[i].half_words[0]);
            uint32_t v = t % index_limit;

            // Second index.
            uint32_t w = static_cast<uint32_t>(num_items + (i - 1)) % index_limit;

            // Pipelining functions returning structs gives small performance boost.
            cache[i] = keccak512(bitwise_xor(cache[v], cache[w]));
        }
    }
}
/*******************************************************************************
* Function Name  : decrypt_pdu_cbc
* Description    : Decrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input pCipher data address
*                  - int: length
* Output         : output_pointer: output plain data address
* Return         : None
*******************************************************************************/
void decrypt_pdu_cbc(u32 *aExp_key, unsigned char *pCipher,int len, unsigned char *pPlain)
{
    n_blocks = len / 16;
    n_remain = len % 16;
    uint8_t atempbuff[16]= {0};

    /*Decryption starts here..................*/
    memcpy( aRevBuff, pCipher, len );
    for ( g_index=0; g_index<n_blocks; g_index++ )
    {
        for(uint8_t count=0; count<16; count++)
        {
            aBuff[count] = aRevBuff[(g_index*16)+count];
        }
        AES_decrypt(aBuff,(u32*)aes_out,aExp_key);
        memcpy( atempbuff, aes_out, 16 );
        for(uint8_t count =0; count<4; count++)
        {
            for(uint8_t aCtr =0; aCtr<4; aCtr++)
            {
                aTemp[aCtr+count*4] =   atempbuff[(3-aCtr)+(count*4)];
            }
        }

        bitwise_xor(aTemp,&aAES_InitnalizationVector_Rx[0], &pPlain[g_index*16]);
        memcpy( aAES_InitnalizationVector_Rx, aBuff, 16 );
    }/*decription of n_blocks completed*/
}
Beispiel #4
0
 expression bitwise_xor_assign(
   const std::shared_ptr< llvm::LLVMContext > &context,
   const std::shared_ptr< ir_builder_t > &ir_builder,
   const expression &left,
   const expression &right
 ) {
   return assign( context, ir_builder, left, bitwise_xor( context, ir_builder, left, right ) );
 }
/*******************************************************************************
* Function Name  : decrypt_pdu
* Description    : Decrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input cipher data address
*                  - int: length
* Output         : output_pointer: output plain data address
* Return         : None
*******************************************************************************/
u32 decrypt_pdu(u32 *exp_key, unsigned char *cipher,int len, unsigned char *plain )
{
  int out_len = 0;
  
  /*Getting the value of Nonce by capturing first word from incoming data*/
  n_blocks = len / 16;
  n_remain = len % 16;
  
  
  /*Decryption starts here..................*/
  for ( index=0; index< n_blocks; index++ ) {
    AES_encrypt(AES_InitnalizationVector_Rx,(u32*)aes_out,(u32*)exp_key); 
    bitwise_xor((unsigned char*)(aes_out), &cipher[index*16], &plain[index*16]);
    add_counter((u32*)AES_InitnalizationVector_Rx);
    out_len += 16;
  }
  
  
  for ( index=0; index<16; index++ ) {
    remain[index] = 0;
  }
  
  /*Storing remaining words in remain buffer*/
  for ( index=0; index<n_remain; index++ ) {
    remain[index] = cipher[n_blocks*16+index];
  }
  
  /*Decryption of the last block starts here*/
  AES_encrypt(AES_InitnalizationVector_Rx,(u32*)aes_out,(u32*)exp_key);  
  
  /*Notice that AES_encrypt is called for decryption instead of AES_decrypt*/
  bitwise_xor((unsigned char*)(aes_out),&remain[0], &temp[0]);
  
  /*putting remaining result into plain buffer*/
  for ( index=0; index<n_remain; index++ ) {
    plain[n_blocks*16+index] = temp[index];
  }
  out_len += n_remain;
  return nonce;
}
/*******************************************************************************
* Function Name  : encrypt_pdu
* Description    : Encrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input plain data address
*                  - int: length
* Output         : output_pointer: output cipher data address
* Return         : None
*******************************************************************************/
u32 encrypt_pdu(u32 *exp_key, unsigned char *plain, int len, unsigned char *cipher)
{
  int out_len = 0;
  out_len += 4;
  n_blocks = len / 16;
  n_remain = len % 16;
  
  
  
  /*Encryption starts here..................*/
  for ( index=0; index< n_blocks; index++ ) {
    AES_encrypt(AES_InitnalizationVector_Tx,(u32*)aes_out,exp_key); 
    bitwise_xor((unsigned char*)(aes_out), &plain[index*16], &cipher[index*16]);
    add_counter((uint32_t*)AES_InitnalizationVector_Tx);
    out_len += 16;
  }/*n_blocks have been encrypted, each with different counter value*/
  
  
  for ( index=0; index<16; index++ ) {
    remain[index] = 0;
  }
  
  /*Storing remaining words in remain buffer*/
  for ( index=0; index<n_remain; index++ ) {
    remain[index] = plain[n_blocks*16+index];
  }
  
  /*Encryption of the last block starts here*/
  AES_encrypt(/*(u32*)*/AES_InitnalizationVector_Tx,(u32*)aes_out,(u32*)exp_key); 
  bitwise_xor((unsigned char*)(aes_out),&remain[0], &temp[0]);
  
  /*putting remaining result into cipher buffer*/
  for ( index=0; index<n_remain; index++ ) {
    cipher[n_blocks*16+index] = temp[index];
  }
  
  out_len += n_remain;
  return nonce;
}
/*******************************************************************************
* Function Name  : encrypt_pdu
* Description    : Encrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input plain data address
*                  - int: length
* Output         : output_pointer: output pCipher data address
* Return         : None
*******************************************************************************/
u32 encrypt_pdu(u32 *aExp_key, unsigned char *pPlain, int len, unsigned char *pCipher)
{
    int out_len = 0;
    out_len += 4;
    n_blocks = len / 16;
    n_remain = len % 16;



    /*Encryption starts here..................*/
    for ( g_index=0; g_index< n_blocks; g_index++ ) {
        AES_encrypt(aAES_InitnalizationVector_Tx,(u32*)aes_out,aExp_key);
        bitwise_xor((unsigned char*)(aes_out), &pPlain[g_index*16], &pCipher[g_index*16]);
        add_counter((uint32_t*)aAES_InitnalizationVector_Tx);
        out_len += 16;
    }/*n_blocks have been encrypted, each with different counter value*/


    for ( g_index=0; g_index<16; g_index++ ) {
        aRemain[g_index] = 0;
    }

    /*Storing remaining words in aRemain buffer*/
    for ( g_index=0; g_index<n_remain; g_index++ ) {
        aRemain[g_index] = pPlain[n_blocks*16+g_index];
    }

    /*Encryption of the last block starts here*/
    AES_encrypt(/*(u32*)*/aAES_InitnalizationVector_Tx,(u32*)aes_out,(u32*)aExp_key);
    bitwise_xor((unsigned char*)(aes_out),&aRemain[0], &aTemp[0]);

    /*putting remaining result into pCipher buffer*/
    for ( g_index=0; g_index<n_remain; g_index++ ) {
        pCipher[n_blocks*16+g_index] = aTemp[g_index];
    }

    out_len += n_remain;
    return nonce;
}
Beispiel #8
0
void BenchMarkLatex::copySampleWithGt(CStr sampleDir, CStr imgNameNE, CStr mName, CStr dstDir)
{
	if (imgNameNE == "yokohm060409_dyjsn266")
		int a = 0;

	Mat gt = CmFile::LoadMask(sampleDir + "Imgs/" + imgNameNE + ".png"), largerGt;
	Mat img = imread(sampleDir + "Imgs/" + imgNameNE + ".jpg"); // C:\WkDir\Saliency\SED2\Saliency\00000155_DRFI.png
	Mat sal = imread(sampleDir + "Saliency/" + imgNameNE + "_" + mName + ".png", CV_LOAD_IMAGE_GRAYSCALE);
	SetBorder2Zero(gt, 5, 5);
	dilate(gt, largerGt, Mat(), Point(-1, -1), 5);
	bitwise_xor(gt, largerGt, largerGt);
	img.setTo(Scalar(0, 0, 255), largerGt);
	imwrite(dstDir + imgNameNE + ".jpg", img);
	imwrite(dstDir + imgNameNE + ".png", sal);
}
Beispiel #9
0
    Point calculateShift(InputArray _img0, InputArray _img1)
    {
        Mat img0 = _img0.getMat();
        Mat img1 = _img1.getMat();
        CV_Assert(img0.channels() == 1 && img0.type() == img1.type());
        CV_Assert(img0.size() == img0.size());

        int maxlevel = static_cast<int>(log((double)max(img0.rows, img0.cols)) / log(2.0)) - 1;
        maxlevel = min(maxlevel, max_bits - 1);

        std::vector<Mat> pyr0;
        std::vector<Mat> pyr1;
        buildPyr(img0, pyr0, maxlevel);
        buildPyr(img1, pyr1, maxlevel);

        Point shift(0, 0);
        for(int level = maxlevel; level >= 0; level--) {

            shift *= 2;
            Mat tb1, tb2, eb1, eb2;
            computeBitmaps(pyr0[level], tb1, eb1);
            computeBitmaps(pyr1[level], tb2, eb2);

            int min_err = (int)pyr0[level].total();
            Point new_shift(shift);
            for(int i = -1; i <= 1; i++) {
                for(int j = -1; j <= 1; j++) {
                    Point test_shift = shift + Point(i, j);
                    Mat shifted_tb2, shifted_eb2, diff;
                    shiftMat(tb2, shifted_tb2, test_shift);
                    shiftMat(eb2, shifted_eb2, test_shift);
                    bitwise_xor(tb1, shifted_tb2, diff);
                    bitwise_and(diff, eb1, diff);
                    bitwise_and(diff, shifted_eb2, diff);
                    int err = countNonZero(diff);
                    if(err < min_err) {
                        new_shift = test_shift;
                        min_err = err;
                    }
                }
            }
            shift = new_shift;
        }
        return shift;
    }
Beispiel #10
0
// load format(imgW, i) and add information to the back of imgs and lens
void CmIllustr::LoadImgs(CStr &imgW, vecM &imgs, vecD &lens, int W, int H)
{
	bool toRow = W > H;
	double crnt = -space;
	if (imgs.size()){ // There exist a predefined image for sketch
		lens.push_back(toRow ? H*imgs[0].cols*1./imgs[0].rows : W*imgs[0].rows*1./imgs[0].cols);
		crnt += lens[0] + space;
	}

	for (int i = 0; i < 500; i++){
		string imgN = format(_S(imgW), i), inDir, maskN;
		vecS names;
		int subN = CmFile::GetNames(imgN, names, inDir);
		if (subN == 0)
			continue;
		Mat img = imread(inDir + names[0]);
		if (img.data == NULL){
			printf("Can't load image file %-70s\n", _S(names[0]));
			continue;
		}
		if (subN > 1){
			Mat mask1u = imread(inDir + names[1], CV_LOAD_IMAGE_GRAYSCALE), big1u;
			dilate(mask1u, big1u, Mat(), Point(-1, -1), 5);
			bitwise_xor(mask1u, big1u, mask1u);
			img.setTo(Scalar(0, 0, 255), mask1u);
		}

		lens.push_back(toRow ? H*img.cols*1./img.rows : W*img.rows*1./img.cols);
		imgs.push_back(img);
		crnt += lens[lens.size() - 1] + space;
		if (crnt >= max(H, W))
			break;
	}
	int num = imgs.size();
	if (num && abs(crnt - max(H,W)) > abs(crnt - lens[num - 1] - space - max(H,W)))
		imgs.resize(num - 1), lens.resize(num - 1);

	printf("%s: %d\n", _S(imgW), num);
	if (crnt < max(H, W))	{
		printf(_S(imgW + ": not enough images\n"));
		exit(0);
	}
}
Beispiel #11
0
 const value operator^(::zval const& rhs) const {
     return bitwise_xor(rhs);
 }
Beispiel #12
0
void detect2(Mat img, vector<Mat>& regionsOfInterest,vector<Blob>& blobs){
/*	Mat blurred; 
	GaussianBlur(img, blurred, Size(), _SharpSigma, _SharpSigma);
	Mat lowContrastMask = abs(img - blurred) < _SharpThreshold;
	Mat sharpened = img*(1+_SharpAmount) + blurred*(-_SharpAmount);
	img.copyTo(sharpened, lowContrastMask);
	sharpened.copyTo(img);*/
	/*************INIZIALIZZAZIONI**********/
	Mat gray; 
	Mat out = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat masked = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat morph = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat bwmorph = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat cont = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat maskHSV = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat whiteMaskMasked = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat whiteMaskOrig = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat Bands[3];
	Mat noBackMask = Mat::zeros(Size(WIDTH,HEIGH), CV_8U);
	Mat kernelEr = getStructuringElement(MORPH_ELLIPSE,Size(5,5));
	Mat thMasked; Mat thOrig; Mat bwOrig; Mat bwNoBackMask;
	Mat kernelOp = getStructuringElement(MORPH_ELLIPSE,Size(13,13));
	vector<Mat> BGRbands;  split(img,BGRbands);
	vector< vector<Point> > contours;
	/***************************************/
	/*cvtColor(img,gray,CV_BGR2GRAY);
	gray = (gray!=0);
	imshow("gray",gray);*/
	/*Rimozione Ombre e Background*/
//	masked = applyMaskBandByBand(maskHSV,BGRbands); split(masked,BGRbands);
	
	/*Rimozione sfondo e sogliatura per videnziare esclusivamente ciò che è bianco*/
	noBackMask = backgroundRemoval(img);
	masked = applyMaskBandByBand(noBackMask,BGRbands);
/*
	whiteMaskOrig = computeWhiteMaskLight(img);
	whiteMaskOrig = whiteMaskOrig + computeWhiteMaskShadow(img);

	whiteMaskMasked = computeWhiteMaskLight(masked);
	whiteMaskMasked = whiteMaskMasked + computeWhiteMaskShadow(masked);
*/
	CBlobResult blobsRs;
	blobsRs = computeWhiteMaskOtsu(img, img, blobsRs, img.rows*img.cols, img.rows*img.cols, 0.8, 0.8, 30, 200, 0);
	
	//Mat newimg(img.size(),img.type());
    whiteMaskOrig.setTo(0);
    for(int i=0;i<blobsRs.GetNumBlobs();i++){
			 blobsRs.GetBlob(i)->FillBlob(whiteMaskOrig,CV_RGB(255,255,255),0,0,true);
    }

	threshold(masked,whiteMaskMasked,0,255,THRESH_BINARY);
	cvtColor(whiteMaskMasked,whiteMaskMasked,CV_BGR2GRAY);
		cout << whiteMaskMasked.type() << " " << whiteMaskOrig.type() << endl;
	bitwise_or(whiteMaskMasked,whiteMaskOrig,thOrig);
	masked = applyMaskBandByBand(thOrig,BGRbands);
#if DO_MORPH
	/*Operazioni morfologiche per poter riempire i buchi e rimuovere i bordi frastagliati*/
	dilate(masked,morph,kernelEr);
	erode(morph,morph,kernelEr);
	
	erode(morph,morph,kernelOp);
	dilate(morph,morph,kernelOp);
#else
	morph = masked;
#endif
	/*Ricerca componenti connesse e rimozione in base all'area*/
	cvtColor(morph,bwmorph,CV_BGR2GRAY);
	findContours(bwmorph, contours, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE);
	vector<double> areas = computeArea(contours);
	for(int j = areas.size()-1; j>=0; j--){
		if(areas.at(j)>MAX_AREA || areas.at(j)<MIN_AREA )
			contours.erase(contours.begin()+j);
	}

	/*Calcolo Bounding Rectangle a partire dall'immagine con componenti connesse di interesse*/
	 vector<Rect> boundRect( contours.size() );
	 vector<vector<Point> > contours_poly( contours.size() );
	 vector<Point2f>center( contours.size() ); 
	 vector<float>radius( contours.size() );
	 /*Costruzione immagine finale ed estrazione regioni di interesse*/
	for (int idx = 0; idx < contours.size(); idx++){
		Blob b; b.originalImage = &img;
		Scalar color(255);
		approxPolyDP( Mat(contours[idx]), contours_poly[idx], 3, true );
		boundRect[idx] = boundingRect( Mat(contours_poly[idx]) );
		
		minEnclosingCircle( (Mat)contours_poly[idx], center[idx], radius[idx] );
	//	Rect tmpRect(center[idx].x-boundRect[idx].width/2,center[idx].y-boundRect[idx].height/2,boundRect[idx].width,boundRect[idx].height);
		Rect tmpRect(center[idx].x-radius[idx],center[idx].y-radius[idx],radius[idx]*2,radius[idx]*2);
		//Rect tmpRect = boundRect[idx];
		Rect toPrint; 
		tmpRect += Size(tmpRect.width*RECT_AUGMENT ,tmpRect.height*RECT_AUGMENT);			  // Aumenta area di RECT_ARGUMENT
		tmpRect -= Point((tmpRect.width*RECT_AUGMENT)/2 , (tmpRect.height*RECT_AUGMENT)/2 ); // Ricentra il rettangolo
		
		drawContours(cont, contours, idx, color, CV_FILLED, 8);
		if(tmpRect.x>0 && tmpRect.y>0 && tmpRect.x+tmpRect.width < morph.cols && tmpRect.y+tmpRect.height < morph.rows){ //Se il nuovo rettangolo allargato
																														// NON esce fuori dall'immagine, accettalo
			regionsOfInterest.push_back(masked(tmpRect));
			b.cuttedWithBack = img(tmpRect);
			b.cuttedImages = masked(tmpRect);
			b.blobsImage = cont(tmpRect);
			b.rectangles = tmpRect;
			toPrint = tmpRect;
		}
		else{
			toPrint = boundRect[idx];
			regionsOfInterest.push_back(masked(boundRect[idx]));
			b.cuttedImages = masked(boundRect[idx]);
			b.cuttedWithBack = img(boundRect[idx]);
			b.rectangles = boundRect[idx];
			b.blobsImage = cont(boundRect[idx]);
		}
		Point centroid = computeCentroid(contours[idx]);
		b.centroid = centroid;
		b.area = contourArea(contours[idx]);
		b.distance = HEIGH - centroid.y;
		
		/*rectangle( cont, toPrint.tl(), toPrint.br(), color, 2, 8, 0 );
		circle( cont, center[idx], (int)radius[idx], color, 2, 8, 0 );*/
		blobs.push_back(b);
	}
	
	//out = out+cont;
	bitwise_xor(out,cont,out);
	
	/*imshow("img",img);
	imshow("out",out);
	waitKey(0);*/
}
/*******************************************************************************
* Function Name  : encrypt_pdu_cbc
* Description    : Encrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input plain data address
*                  - int: length
* Output         : output_pointer: output cipher data address
* Return         : None
*******************************************************************************/
void encrypt_pdu_cbc(u32 *exp_key, unsigned char *plain, int len, unsigned char *cipher)
{
  n_blocks = len / 16;
  n_remain = len % 16;
  uint8_t tempbuff[64];
  CipherBlocklen = 0x00;
  
  /*Encryption starts here..................*/
  for (index=0; index< n_blocks; index++ ) 
  {
    bitwise_xor((unsigned char*)AES_InitnalizationVector_Tx, &plain[index*16], &temp[0] );
    AES_encrypt(temp,aes_out,exp_key); 
    memcpy( tempbuff, aes_out, 16 );
    
    for(uint8_t i =0; i<16; i++)
    {
      for(uint8_t ctr =0; ctr<4;ctr++)
      {
        AES_InitnalizationVector_Tx[ctr+i*4] =   tempbuff[(3-ctr)+(i*4)];
      }
    }
    
    for(uint8_t i=0; i<16; i++)
    {
      cipher[(index*16)+i] = AES_InitnalizationVector_Tx[i];
    }
    CipherBlocklen +=16;
  }/*n_blocks have been encrypted*/ 
  if(n_remain!=0)
  {
    for ( index=0; index<16; index++ ) {
      remain[index] = 0;
    }
    
    /*Storing remaining words in remain buffer*/
    for ( index=0; index<n_remain; index++ ) 
    {
      remain[index] = plain[n_blocks*16+index];
    }
    if(n_remain < 16)
    {
      for ( index=n_remain; index<16; index++ ) 
      {
        remain[index] = 0x2F;
      }
    }
    
    /*Encryption of the last block starts here*/ 
    bitwise_xor((unsigned char*)AES_InitnalizationVector_Tx, &remain[0], &temp[0] );
    AES_encrypt(temp,(u32*)aes_out,(u32*)exp_key);
    /*putting remaining result into cipher buffer*/
    memcpy( tempbuff, aes_out, 16 );
    
    for(uint8_t i =0; i<16; i++)
    {
      for(uint8_t ctr =0; ctr<4;ctr++)
      {
        cipher[ctr+i*4] =   tempbuff[(3-ctr)+(i*4)];
      }
    }
    
    CipherBlocklen += 16;    
  }
}
Beispiel #14
0
/*-----------------------------------------------------------------------------
hdr: wlanhdr
llc: llc_snap
pframe: raw data payload
plen: length of raw data payload
mic: mic of AES
------------------------------------------------------------------------------*/
static void aes_tx(struct rtl8192cd_priv *priv, UINT8 *key, UINT8 keyid,
			union PN48 *pn48, UINT8 *hdr, UINT8 *llc,
			UINT8 *pframe, UINT32 plen, UINT8* txmic)
{
	static UINT8	message[MAX_MSG_SIZE];
	UINT32	qc_exists, a4_exists, i, j, payload_remainder,
			num_blocks,payload_length, payload_index;

	UINT8 pn_vector[6];
	UINT8 mic_iv[16];
    UINT8 mic_header1[16];
    UINT8 mic_header2[16];
    UINT8 ctr_preload[16];

    /* Intermediate Buffers */
    UINT8 chain_buffer[16];
    UINT8 aes_out[16];
    UINT8 padded_buffer[16];
    UINT8 mic[8];

	UINT32	offset = 0;
	UINT32	hdrlen  = get_hdrlen(priv, hdr);

	memset((void *)mic_iv, 0, 16);
	memset((void *)mic_header1, 0, 16);
	memset((void *)mic_header2, 0, 16);
	memset((void *)ctr_preload, 0, 16);
	memset((void *)chain_buffer, 0, 16);
	memset((void *)aes_out, 0, 16);
	memset((void *)padded_buffer, 0, 16);

	if (get_tofr_ds(hdr) != 0x03)
		a4_exists = 0;
	else
		a4_exists = 1;

	if (is_qos_data(hdr)) {
		qc_exists = 1;
		//hdrlen += 2;	// these 2 bytes has already added
	}
	else
		qc_exists = 0;

	// below is to collecting each frag(hdr, llc, pay, and mic into single message buf)

	// extiv (8 bytes long) should have been appended
	pn_vector[0]  = hdr[hdrlen]   = pn48->_byte_.TSC0;
	pn_vector[1]  = hdr[hdrlen+1] = pn48->_byte_.TSC1;
	hdr[hdrlen+2] =  0x00;
	hdr[hdrlen+3] = (0x20 | (keyid << 6));
	pn_vector[2]  = hdr[hdrlen+4] = pn48->_byte_.TSC2;
	pn_vector[3]  = hdr[hdrlen+5] = pn48->_byte_.TSC3;
	pn_vector[4]  = hdr[hdrlen+6] = pn48->_byte_.TSC4;
	pn_vector[5]  = hdr[hdrlen+7] = pn48->_byte_.TSC5;

	memcpy((void *)message, hdr, (hdrlen + 8)); //8 is for ext iv len
	offset = (hdrlen + 8);

	if (llc)
	{
		memcpy((void *)(message + offset), (void *)llc, 8);
		offset += 8;
	}
	memcpy((void *)(message + offset), (void *)pframe, plen);
	offset += plen;

	// now we have collecting all the bytes into single message buf

	payload_length = plen; // 8 is for llc

	if (llc)
		payload_length += 8;

	construct_mic_iv(
                        mic_iv,
                        qc_exists,
                        a4_exists,
                        message,
                        (payload_length),
                        pn_vector
                        );

    construct_mic_header1(
                            mic_header1,
                            hdrlen,
                            message
                            );
    construct_mic_header2(
                            mic_header2,
                            message,
                            a4_exists,
                            qc_exists
                            );


	payload_remainder = (payload_length) % 16;
    num_blocks = (payload_length) / 16;

    /* Find start of payload */
    payload_index = (hdrlen + 8);

    /* Calculate MIC */
    aes128k128d(key, mic_iv, aes_out);
    bitwise_xor(aes_out, mic_header1, chain_buffer);
    aes128k128d(key, chain_buffer, aes_out);
    bitwise_xor(aes_out, mic_header2, chain_buffer);
    aes128k128d(key, chain_buffer, aes_out);

	for (i = 0; i < num_blocks; i++)
    {
        bitwise_xor(aes_out, &message[payload_index], chain_buffer);

        payload_index += 16;
        aes128k128d(key, chain_buffer, aes_out);
    }

    /* Add on the final payload block if it needs padding */
    if (payload_remainder > 0)
    {
        for (j = 0; j < 16; j++) padded_buffer[j] = 0x00;
        for (j = 0; j < payload_remainder; j++)
        {
            padded_buffer[j] = message[payload_index++];
        }
        bitwise_xor(aes_out, padded_buffer, chain_buffer);
        aes128k128d(key, chain_buffer, aes_out);

    }

    for (j = 0 ; j < 8; j++) mic[j] = aes_out[j];

    /* Insert MIC into payload */
    for (j = 0; j < 8; j++)
    	message[payload_index+j] = mic[j];

	payload_index = hdrlen + 8;
	for (i=0; i< num_blocks; i++)
    {
        construct_ctr_preload(
                                ctr_preload,
                                a4_exists,
                                qc_exists,
                                message,
                                pn_vector,
                                i+1);
        aes128k128d(key, ctr_preload, aes_out);
        bitwise_xor(aes_out, &message[payload_index], chain_buffer);
        for (j=0; j<16;j++) message[payload_index++] = chain_buffer[j];
    }

    if (payload_remainder > 0)          /* If there is a short final block, then pad it,*/
    {                                   /* encrypt it and copy the unpadded part back   */
        construct_ctr_preload(
                                ctr_preload,
                                a4_exists,
                                qc_exists,
                                message,
                                pn_vector,
                                num_blocks+1);

        for (j = 0; j < 16; j++) padded_buffer[j] = 0x00;
        for (j = 0; j < payload_remainder; j++)
        {
            padded_buffer[j] = message[payload_index+j];
        }
        aes128k128d(key, ctr_preload, aes_out);
        bitwise_xor(aes_out, padded_buffer, chain_buffer);
        for (j=0; j<payload_remainder;j++) message[payload_index++] = chain_buffer[j];
    }

    /* Encrypt the MIC */
    construct_ctr_preload(
                        ctr_preload,
                        a4_exists,
                        qc_exists,
                        message,
                        pn_vector,
                        0);

    for (j = 0; j < 16; j++) padded_buffer[j] = 0x00;
    for (j = 0; j < 8; j++)
    {
        padded_buffer[j] = message[j+hdrlen+8+payload_length];
    }

    aes128k128d(key, ctr_preload, aes_out);
    bitwise_xor(aes_out, padded_buffer, chain_buffer);
    for (j=0; j<8;j++) message[payload_index++] = chain_buffer[j];

	// now, going to copy the final result back to the input buf...
	offset =0;

	//if (llc)
	{
		memcpy((void *)hdr, (void *)(&message[offset]), (hdrlen + 8 )); //8 is for ext iv
    	offset += (hdrlen + 8);
    }

    if (llc)
    {
    	memcpy((void *)llc, (void *)(&message[offset]),  8 ); //8 is for llc
    	offset +=  (8);
    }


    memcpy((void *)pframe, (void *)(&message[offset]), (plen)); //now is for plen
    offset += (plen);


    memcpy((void *)txmic, (void *)(&message[offset]), 8); //now is for mic
    offset += 8;

	rtl_cache_sync_wback(priv, (unsigned long)hdr, hdrlen + 8, PCI_DMA_TODEVICE);
	if (llc)
		rtl_cache_sync_wback(priv, (unsigned long)llc, 8, PCI_DMA_TODEVICE);
	rtl_cache_sync_wback(priv, (unsigned long)pframe, plen, PCI_DMA_TODEVICE);
	rtl_cache_sync_wback(priv, (unsigned long)txmic, 8, PCI_DMA_TODEVICE);

    _DEBUG_INFO("--txmic=%X %X %X %X %X %X %X %X\n",
    txmic[0], txmic[1], txmic[2], txmic[3],
    txmic[4], txmic[5], txmic[6], txmic[7]);

   	if (pn48->val48 == 0xffffffffffffULL)
		pn48->val48 = 0;
	else
		pn48->val48++;
}
Beispiel #15
0
static void aes_rx(UINT8 *ttkey, UINT8 qc_exists, UINT8 a4_exists,
				UINT8 *pframe, UINT32 hdrlen, UINT32 plen)
{
	UINT32	i, j, payload_remainder,
			num_blocks, payload_index;

	UINT8 pn_vector[6];
	UINT8 mic_iv[16];
    UINT8 mic_header1[16];
    UINT8 mic_header2[16];
    UINT8 ctr_preload[16];

    UINT8 chain_buffer[16];
    UINT8 aes_out[16];
    UINT8 padded_buffer[16];
    UINT8 mic[8];

	memset((void *)mic_iv, 0, 16);
	memset((void *)mic_header1, 0, 16);
	memset((void *)mic_header2, 0, 16);
	memset((void *)ctr_preload, 0, 16);
	memset((void *)chain_buffer, 0, 16);
	memset((void *)aes_out, 0, 16);
	memset((void *)mic, 0, 8);

	num_blocks = plen / 16; //(plen including llc, payload_length and mic )

	payload_remainder = plen % 16;

	pn_vector[0]  = pframe[hdrlen];
	pn_vector[1]  = pframe[hdrlen+1];
	pn_vector[2]  = pframe[hdrlen+4];
	pn_vector[3]  = pframe[hdrlen+5];
	pn_vector[4]  = pframe[hdrlen+6];
	pn_vector[5]  = pframe[hdrlen+7];

	// now, decrypt pframe with hdrlen offset and plen long

	payload_index = hdrlen + 8; // 8 is for extiv
	for (i=0; i< num_blocks; i++)
    {
        construct_ctr_preload(
                                ctr_preload,
                                a4_exists,
                                qc_exists,
                                pframe,
                                pn_vector,
                                i+1
                            );

        aes128k128d(ttkey, ctr_preload, aes_out);
        bitwise_xor(aes_out, &pframe[payload_index], chain_buffer);

        for (j=0; j<16;j++) pframe[payload_index++] = chain_buffer[j];
    }

    if (payload_remainder > 0)          /* If there is a short final block, then pad it,*/
    {                                   /* encrypt it and copy the unpadded part back   */
        construct_ctr_preload(
                                ctr_preload,
                                a4_exists,
                                qc_exists,
                                pframe,
                                pn_vector,
                                num_blocks+1
                            );

        for (j = 0; j < 16; j++) padded_buffer[j] = 0x00;
        for (j = 0; j < payload_remainder; j++)
        {
            padded_buffer[j] = pframe[payload_index+j];
        }
        aes128k128d(ttkey, ctr_preload, aes_out);
        bitwise_xor(aes_out, padded_buffer, chain_buffer);
        for (j=0; j<payload_remainder;j++) pframe[payload_index++] = chain_buffer[j];
    }
}
Beispiel #16
0
 const value bitwise_xor(::zval const& rhs) const {
     return bitwise_xor(rhs BOOST_PHP_TSRM_DIRECT_CC);
 }
/*******************************************************************************
* Function Name  : encrypt_pdu_cbc
* Description    : Encrypts the incoming stream
* Input          : - input_pointer: expended key address
*                  - input_pointer: input plain data address
*                  - int: length
* Output         : output_pointer: output pCipher data address
* Return         : None
*******************************************************************************/
void encrypt_pdu_cbc(u32 *aExp_key, unsigned char *pPlain, int len, unsigned char *pCipher)
{
    n_blocks = len / 16;
    n_remain = len % 16;
    uint8_t atempbuff[16]= {0};
    CipherBlocklen = 0x00;

    /*Encryption starts here..................*/
    for (g_index=0; g_index< n_blocks; g_index++ )
    {
        bitwise_xor((unsigned char*)aAES_InitnalizationVector_Tx, &pPlain[g_index*16], &aTemp[0] );
        AES_encrypt(aTemp,aes_out,aExp_key);
        memcpy( atempbuff, aes_out, 16 );

        for(uint8_t count =0; count<4; count++)
        {
            for(uint8_t aCtr =0; aCtr<4; aCtr++)
            {
                aAES_InitnalizationVector_Tx[aCtr+count*4] =   atempbuff[(3-aCtr)+(count*4)];
            }
        }

        for(uint8_t count=0; count<16; count++)
        {
            pCipher[(g_index*16)+count] = aAES_InitnalizationVector_Tx[count];
        }
        CipherBlocklen +=16;
    }/*n_blocks have been encrypted*/
    if(n_remain!=0)
    {
        for ( g_index=0; g_index<16; g_index++ ) {
            aRemain[g_index] = 0;
        }

        /*Storing remaining words in aRemain buffer*/
        for ( g_index=0; g_index<n_remain; g_index++ )
        {
            aRemain[g_index] = pPlain[n_blocks*16+g_index];
        }
        if(n_remain < 16)
        {
            for ( g_index=n_remain; g_index<16; g_index++ )
            {
                aRemain[g_index] = 0x2F;
            }
        }

        /*Encryption of the last block starts here*/
        bitwise_xor((unsigned char*)aAES_InitnalizationVector_Tx, &aRemain[0], &aTemp[0] );
        AES_encrypt(aTemp,(u32*)aes_out,(u32*)aExp_key);
        /*putting remaining result into pCipher buffer*/
        memcpy( atempbuff, aes_out, 16 );

        for(uint8_t count =0; count<4; count++)
        {
            for(uint8_t aCtr =0; aCtr<4; aCtr++)
            {
                pCipher[n_blocks*16+aCtr+count*4] =   atempbuff[(3-aCtr)+(count*4)];
            }
        }

        CipherBlocklen += 16;
    }
}