Exemplo n.º 1
0
void encryptionOracle(std::ostream & outputStream, std::istream & inputStream)
{
    std::uniform_int_distribution<unsigned short> prefixAndSuffixLength(5, 10);

    std::istringstream prefix(
        generateRandomBytes(prefixAndSuffixLength(getRandomNumbers())));

    cat_streambuf prefixThenInput(prefix, inputStream);
    std::istream prefixAndInput(&prefixThenInput);

    std::istringstream suffix(
        generateRandomBytes(prefixAndSuffixLength(getRandomNumbers())));

    cat_streambuf prefixThenInputThenSuffix(prefixAndInput, suffix);
    std::istream prefixAndInputAndSuffix(&prefixThenInputThenSuffix);

    std::uniform_int_distribution<unsigned short> decideEncryptionMethod(0, 1);
    if (decideEncryptionMethod(getRandomNumbers())) {
        lastEncryptionMode = EncryptionMode::ECB;
        aes_ecb_encrypt(outputStream,
                        prefixAndInputAndSuffix,
                        generateRandomBytes(CryptoPP::AES::BLOCKSIZE));
    } else {
        lastEncryptionMode = EncryptionMode::CBC;
        aes_cbc_encrypt(outputStream,
                        prefixAndInputAndSuffix,
                        generateRandomBytes(CryptoPP::AES::BLOCKSIZE),
                        generateRandomBytes(CryptoPP::AES::BLOCKSIZE).c_str());
    }
}
Exemplo n.º 2
0
void gcm_init(gcm* g,int nk,char *key,int niv,char *iv)
{ /* iv size niv is usually 12 bytes (96 bits). AES key size nk can be 16,24 or 32 bytes */
	int i;
	MR_BYTE H[16];
	for (i=0;i<16;i++) {H[i]=0; g->stateX[i]=0;}

	aes_init(&(g->a),MR_ECB,nk,key,iv);
	aes_ecb_encrypt(&(g->a),H);     /* E(K,0) */
	precompute(g,H);
	
	g->lenA[0]=g->lenC[0]=g->lenA[1]=g->lenC[1]=0;
	if (niv==12)
	{
		for (i=0;i<12;i++) g->a.f[i]=iv[i];
		unpack((MR_WORD)1,(MR_BYTE *)&(g->a.f[12]));  /* initialise IV */
		for (i=0;i<16;i++) g->Y_0[i]=g->a.f[i];
	}
	else
	{
		g->status=GCM_ACCEPTING_CIPHER;
		gcm_add_cipher(g,0,iv,niv,NULL); /* GHASH(H,0,IV) */
		gcm_wrap(g);
		for (i=0;i<16;i++) {g->a.f[i]=g->stateX[i];g->Y_0[i]=g->a.f[i];g->stateX[i]=0;}
		g->lenA[0]=g->lenC[0]=g->lenA[1]=g->lenC[1]=0;
	}
	g->status=GCM_ACCEPTING_HEADER;
}
Exemplo n.º 3
0
void gcm_finish(gcm *g,char *tag)
{ /* Finish off and extract tag (MAC) */
	int i,j;
	MR_WORD F[4];
	MR_BYTE L[16];

/* convert lengths from bytes to bits */
	F[0]=(g->lenA[0]<<3)|(g->lenA[1]&0xE0000000)>>29;
	F[1]=g->lenA[1]<<3;
	F[2]=(g->lenC[0]<<3)|(g->lenC[1]&0xE0000000)>>29;
	F[3]=g->lenC[1]<<3;
	for (i=j=0;i<NB;i++,j+=4) unpack(F[i],(MR_BYTE *)&L[j]);

	for (i=0;i<16;i++) g->stateX[i]^=L[i];
	gf2mul(g);

	g->counter=1;
	unpack(g->counter,(MR_BYTE *)&(g->a.f[12]));  /* reset counter */
	for (i=0;i<16;i++) L[i]=g->a.f[i];
	aes_ecb_encrypt(&(g->a),L);        /* E(K,Y0) */

	for (i=0;i<16;i++) L[i]^=g->stateX[i];
	g->status=GCM_FINISHED;
	for (i=0;i<16;i++) tag[i]=L[i];
	aes_end(&(g->a));
}
Exemplo n.º 4
0
/**
   Initialize a Pelican state
   @param pelmac    The Pelican state to initialize
   @param cipher    The index of the desired cipher, must be AES
   @param key       The secret key
   @param keylen    The length of the secret key (octets)
   @return CRYPT_OK if successful
*/
int pelican_init(pelican_state *pelmac, int cipher, const unsigned char *key, unsigned long keylen)
{
    int index;
    int err;

    LTC_ARGCHK(pelmac != NULL);
    LTC_ARGCHK(key    != NULL);

   index = find_cipher("aes");
   if (cipher != index || index < 0) {
      return CRYPT_INVALID_CIPHER;
   }

#ifdef LTC_FAST
    if (16 % sizeof(LTC_FAST_TYPE)) {
        return CRYPT_INVALID_ARG;
    }
#endif

    if ((err = aes_setup(key, keylen, 0, &pelmac->K)) != CRYPT_OK) {
       return err;
    }

    zeromem(pelmac->state, 16);
    aes_ecb_encrypt(pelmac->state, pelmac->state, &pelmac->K);
    pelmac->buflen = 0;

    return CRYPT_OK;
}
static int
rj_encrypt(PX_Cipher *c, const uint8 *data, unsigned dlen, uint8 *res)
{
	struct int_ctx *cx = (struct int_ctx *) c->ptr;

	if (!cx->is_init)
	{
		if (rj_real_init(cx, 1))
			return PXE_CIPHER_INIT;
	}

	if (dlen == 0)
		return 0;

	if (dlen & 15)
		return PXE_NOTBLOCKSIZE;

	memcpy(res, data, dlen);

	if (cx->mode == MODE_CBC)
	{
		aes_cbc_encrypt(&cx->ctx.rj, cx->iv, res, dlen);
		memcpy(cx->iv, res + dlen - 16, 16);
	}
	else
		aes_ecb_encrypt(&cx->ctx.rj, res, dlen);

	return 0;
}
Exemplo n.º 6
0
Arquivo: mrgcm.c Projeto: lqtech/mx208
BOOL gcm_add_cipher(gcm *g,int mode,char *plain,int len,char *cipher)
{ /* Add plaintext to extract ciphertext, or visa versa, depending on mode. len is length of plaintext/ciphertext. Note this file combines GHASH() functionality with encryption/decryption */
	int i,j=0;
	MR_WORD counter;
	MR_BYTE B[16];
	if (g->status==GCM_ACCEPTING_HEADER) g->status=GCM_ACCEPTING_CIPHER;
	if (g->status!=GCM_ACCEPTING_CIPHER) return FALSE;

	while (j<len)
	{
		if (cipher!=NULL)
		{
			counter=pack((MR_BYTE *)&(g->a.f[12]));
			counter++;
			unpack(counter,(MR_BYTE *)&(g->a.f[12]));  /* increment counter */
			for (i=0;i<16;i++) B[i]=g->a.f[i];
			aes_ecb_encrypt(&(g->a),B);        /* encrypt it  */
		}
		for (i=0;i<16 && j<len;i++)
		{
			if (cipher==NULL)
				g->stateX[i]^=plain[j++];
			else
			{
				if (mode==GCM_ENCRYPTING) cipher[j]=plain[j]^B[i];
				if (mode==GCM_DECRYPTING) plain[j]=cipher[j]^B[i];
				g->stateX[i]^=cipher[j++];
			}
			g->lenC[1]++; if (g->lenC[1]==0) g->lenC[0]++;
		}
		gf2mul(g);
	}
	if (len%16!=0) g->status=GCM_NOT_ACCEPTING_MORE;
	return TRUE;
}
Exemplo n.º 7
0
BOOL gcm_add_cipher(gcm *g,int mode,char *plain,int len,char *cipher)
{ /* Add plaintext to extract ciphertext, or visa versa, depending on mode. len is length of plaintext/ciphertext */
	int i,j=0;
	MR_BYTE B[16];
	if (g->status==GCM_ACCEPTING_HEADER) g->status=GCM_ACCEPTING_CIPHER;
	if (g->status!=GCM_ACCEPTING_CIPHER) return FALSE;

	while (j<len)
	{
		g->counter++;
		unpack(g->counter,(MR_BYTE *)&(g->a.f[12]));  /* get counter */
		for (i=0;i<16;i++) B[i]=g->a.f[i];
		aes_ecb_encrypt(&(g->a),B);        /* encrypt it  */
		for (i=0;i<16 && j<len;i++)
		{
			if (mode==GCM_ENCRYPTING) cipher[j]=plain[j]^B[i];
			if (mode==GCM_DECRYPTING) plain[j]=cipher[j]^B[i];
			g->stateX[i]^=cipher[j++];
			g->lenC[1]++; if (g->lenC[1]==0) g->lenC[0]++;
		}
		gf2mul(g);
	}
	if (len%16!=0) g->status=GCM_NOT_ACCEPTING_MORE;
	return TRUE;
}
Exemplo n.º 8
0
static void
AES_ecb_encrypt(const uint8 *src, uint8 *dst, AES_KEY *ctx, int enc)
{
	memcpy(dst, src, 16);
	if (enc)
		aes_ecb_encrypt(ctx, dst, 16);
	else
		aes_ecb_decrypt(ctx, dst, 16);
}
Exemplo n.º 9
0
static void run_tomcrypt_aes128(uint8_t *output,
                                const uint8_t *input, unsigned size)
{
    symmetric_key aes;
    unsigned i;

    aes_setup(hardcoded_key, 16, 0, &aes);
    size -= 15;
    for (i = 0; i < size; i += 16)
        aes_ecb_encrypt(input + i, output + i, &aes);
}
Exemplo n.º 10
0
int main(int argc, char *argv[]) {
  const char indata[] = "MyBloodyValentinMyBloodyValentin";
  unsigned char data[32768];
  char hex[256], base64[256];
  int len;

  unsigned char iv[] = { 'Y', 'E', 'L', 'L', 'O', 'W', ' ', 'S', 'U', 'B', 'M', 'A', 'R', 'I', 'N', 'E' };
  unsigned char key[] = { 'Y', 'E', 'L', 'L', 'O', 'W', ' ', 'S', 'U', 'B', 'M', 'A', 'R', 'I', 'N', 'E' };

  len = strlen(indata);
  printf("// testing aes-128-ecb\n");

  printf("Plaintext:\n");
  hexdump(indata, len);
  
  memcpy(data, indata, len);

  aes_ecb_encrypt(data, len, key, sizeof(key));
  printf("Ciphertext:\n");
  hexdump(data, 16);

  base64[base64encode(data, len, base64)] = '\0';
  printf("base64: %s\n", base64);

  aes_ecb_decrypt(data, len, key, sizeof(key));
  data[len] = '\0';

  printf("Decrypted plaintext: %s\n", data);
  hexdump(data, len);

  printf("// testing aes-128-cbc\n");

  printf("Plaintext:\n");
  hexdump(indata, len);
  
  memcpy(data, indata, len);

  aes_cbc_encrypt(data, len, key, sizeof(key), iv);
  printf("Ciphertext:\n");
  hexdump(data, 16);

  base64[base64encode(data, len, base64)] = '\0';
  printf("base64: %s\n", base64);

  aes_cbc_decrypt(data, len, key, sizeof(key), iv);
  data[len] = '\0';

  printf("Decrypted plaintext: %s\n", data);
  hexdump(data, len);



  return 0;
}
Exemplo n.º 11
0
/*****************************************************************
 * This function calculates the hash for the application. 
 * When this function returns successfully, the hash
 * is written to hashOutput.
 *
 * Returns false if the operation failed. In this case
 * the value of hashOutput should be ignored. 
 *****************************************************************/
bool calculateHash(uint8_t *startAddr, int length, uint8_t *hashOutput)
{
  // Helper variables
  int cryptError, i, j;

  // This variable will always point to the current block
  // to be decrypted
  uint8_t *curBlock;

  // Calculate the number of AES blocks
  int aesBlocks = length / AES_BLOCKSIZE; 

  // Input buffer used to hold the input block to the 
  // encryption routine
  uint8_t inputBlock[AES_BLOCKSIZE];

  // Initialize key
  symmetric_key skey;
  cryptError = aes_setup(hashKey, HASH_KEY_SIZE, 0, &skey);

  if ( cryptError != CRYPT_OK ) {
    fprintf(stderr, "Error initializing crypto library\n");
    return false;
  }

  // hashOutput will always contain the last encrypted block
  // Initialize with the init vector for the first iteration
  memcpy(hashOutput, hashInitVector, AES_BLOCKSIZE);

  // Loop over all blocks 
  for ( i=0; i<aesBlocks; i++ ) {
    
    // Get address of the current AES block
    curBlock = startAddr + i * AES_BLOCKSIZE;

    // XOR current block with previous cipher
    for ( j=0; j<AES_BLOCKSIZE; j++ ) {
      inputBlock[j] = curBlock[j] ^ hashOutput[j];
    }

    // Encrypt a block. Result is stored in hashOutput
    cryptError = aes_ecb_encrypt(inputBlock, hashOutput, &skey);

    if ( cryptError != CRYPT_OK ) {
      fprintf(stderr, "Error during hash calculation\n");
      return false;
    }
  }

  // Success
  return true;
}
Exemplo n.º 12
0
/*****************************************************************
 * Encrypt the entire firmware image (including header) with AES
 * in CBC mode. The image is encrypted in place, 
 * when this function returns the buffer array will contain the 
 * encrypted image. 
 *****************************************************************/
bool encrypt(void)
{
  // Helper variables
  int cryptError, i, j;

  // Compute number of AES blocks to encrypt
  int aesBlocks = encryptedSize / AES_BLOCKSIZE;

  // The pointer to the current block to be encrypted
  uint8_t *curBlock;

  // Pointer to the last encrypted block
  // Initialize with the init vector
  uint8_t *prevBlock = initVector;

  // Initialize key
  symmetric_key skey;
  cryptError = aes_setup(encryptionKey, AES_KEY_SIZE, 0, &skey);

  if ( cryptError != CRYPT_OK ) {
    fprintf(stderr, "Error initializing crypto library\n");
    return false;
  }

  // Loop over the entire image
  for ( i=0; i<aesBlocks; i++ ) {
    
    // Get address of the current AES block
    curBlock = buffer + i * AES_BLOCKSIZE;

    // XOR current block with the last encrypted block
    for ( j=0; j<AES_BLOCKSIZE; j++ ) {
      curBlock[j] = curBlock[j] ^ prevBlock[j];
    }

    // Encrypt block in place
    cryptError = aes_ecb_encrypt(curBlock, curBlock, &skey);

    // Store address of current block for next iteration
    prevBlock = curBlock;

    if ( cryptError != CRYPT_OK ) {
      fprintf(stderr, "Error during encryption\n");
      return false;
    }
  }

  return true;
}
Exemplo n.º 13
0
void gcm_init(gcm* g,int nk,char *key,char *iv)
{ /* assumes iv is 96 bits/12 bytes. AES key can be 16,24 or 32 bytes */
	int i;
	MR_BYTE H[16];
	for (i=0;i<16;i++) {H[i]=0; g->stateX[i]=0;}

	aes_init(&(g->a),MR_ECB,nk,key,iv);
	aes_ecb_encrypt(&(g->a),H);     /* E(K,0) */
	precompute(g,H);
	g->counter=1;
	for (i=0;i<12;i++) g->a.f[i]=iv[i];
	unpack(g->counter,(MR_BYTE *)&(g->a.f[12]));  /* initialise IV */

	g->status=GCM_ACCEPTING_HEADER;
	g->lenA[0]=g->lenC[0]=g->lenA[1]=g->lenC[1]=0;
}
Exemplo n.º 14
0
void gcm_finish(gcm *g,char *tag)
{ /* Finish off GHASH and extract tag (MAC) */
	int i;

	gcm_wrap(g);

/* extract tag */
	if (tag!=NULL)
	{
		aes_ecb_encrypt(&(g->a),g->Y_0);        /* E(K,Y0) */
		for (i=0;i<16;i++) g->Y_0[i]^=g->stateX[i];
		for (i=0;i<16;i++) {tag[i]=g->Y_0[i];g->Y_0[i]=g->stateX[i]=0;}
	}
	g->status=GCM_FINISHED;
	aes_end(&(g->a));
}
Exemplo n.º 15
0
int main(int argc, char *argv[])
{
	unsigned char encrypted[padded_message_size];
	unsigned char decrypted[padded_message_size];

	memset(decrypted, 0, sizeof(decrypted));
	memcpy(decrypted, message, sizeof(message));

	aes_ecb_encrypt(decrypted, encrypted, padded_message_size, key_size * 8,
			key);
	memset(decrypted, 0, padded_message_size);

	aes_ecb_decrypt(encrypted, decrypted, padded_message_size, key_size * 8,
			key);
	printf("%s", decrypted);

	return 0;
}
Exemplo n.º 16
0
static void
yarrow_fast_reseed(struct yarrow256_ctx *ctx)
{
  quint8 digest[SHA256_DIGEST_SIZE];
  unsigned i;
  
#if YARROW_DEBUG
  fprintf(stderr, "yarrow_fast_reseed\n");
#endif
  
  /* We feed two block of output using the current key into the pool
   * before emptying it. */
  if (ctx->seeded)
    {
      quint8 blocks[AES_BLOCK_SIZE * 2];
      
      yarrow_generate_block(ctx, blocks);
      yarrow_generate_block(ctx, blocks + AES_BLOCK_SIZE);
      sha256_update(&ctx->pools[YARROW_FAST],blocks,sizeof(blocks));
    }
  
  sha256_finish(&ctx->pools[YARROW_FAST],digest);

  /* Iterate */
  yarrow_iterate(digest);

  aes_encrypt_key256(digest,&ctx->key);

  /* Derive new counter value */
  memset(ctx->counter, 0, sizeof(ctx->counter));
  //aes_encrypt(&ctx->key, sizeof(ctx->counter), ctx->counter, ctx->counter);
  aes_ecb_encrypt(ctx->counter,ctx->counter,sizeof(ctx->counter),&ctx->key);
  
  /* Reset estimates. */
  for (i = 0; i<ctx->nsources; i++)
    ctx->sources[i].estimate[YARROW_FAST] = 0;

  /* New seed file. */
  /* FIXME: Extract this into a function of its own. */
  for (i = 0; i < sizeof(ctx->seed_file); i+= AES_BLOCK_SIZE)
    yarrow_generate_block(ctx, ctx->seed_file + i);

  yarrow_gate(ctx);
}
Exemplo n.º 17
0
/**
  Terminate Pelican MAC
  @param pelmac      The Pelican MAC state
  @param out         [out] The TAG
  @return CRYPT_OK on sucess
*/
int pelican_done(pelican_state *pelmac, unsigned char *out)
{
   LTC_ARGCHK(pelmac  != NULL);
   LTC_ARGCHK(out     != NULL);

   /* check range */
   if (pelmac->buflen < 0 || pelmac->buflen > 16) {
      return CRYPT_INVALID_ARG;
   }

   if  (pelmac->buflen == 16) {
       four_rounds(pelmac);
       pelmac->buflen = 0;
   }
   pelmac->state[pelmac->buflen++] ^= 0x80;
   aes_ecb_encrypt(pelmac->state, out, &pelmac->K);
   aes_done(&pelmac->K);
   return CRYPT_OK;
}
Exemplo n.º 18
0
OSStatus    AES_ECB_Update( AES_ECB_Context *inContext, const void *inSrc, size_t inLen, void *inDst )
{
    OSStatus            err;
    const uint8_t *     src;
    uint8_t *           dst;
    size_t              n;
    
    // inSrc and inDst may be the same, but otherwise, the buffers must not overlap.
    
#if( DEBUG )
    if( inSrc != inDst ) check_ptr_overlap( inSrc, inLen, inDst, inLen );
    if( ( inLen % kAES_ECB_Size ) != 0 ) aes_log( "ECB doesn't support non-block-sized operations (%d bytes)", (int)inLen );
#endif
    
    src = (const uint8_t *) inSrc;
    dst = (uint8_t *) inDst;
    for( n = inLen / kAES_ECB_Size; n > 0; --n )
    {
        #if( AES_UTILS_USE_COMMON_CRYPTO )
            size_t      len;
            
            err = CCCryptorUpdate( inContext->cryptor, src, kAES_ECB_Size, dst, kAES_ECB_Size, &len );
            require_noerr( err, exit );
            check( len == kAES_ECB_Size );
        #elif( AES_UTILS_USE_GLADMAN_AES )
            if( inContext->encrypt )    aes_ecb_encrypt( src, dst, kAES_ECB_Size, &inContext->ctx.encrypt );
            else                        aes_ecb_decrypt( src, dst, kAES_ECB_Size, &inContext->ctx.decrypt );
        #elif( AES_UTILS_USE_USSL )
            aes_crypt_ecb( &inContext->ctx, inContext->mode, (unsigned char *) src, dst );
        #else
            inContext->cryptFunc( src, dst, &inContext->key );
        #endif
        src += kAES_ECB_Size;
        dst += kAES_ECB_Size;
    }
    err = kNoErr;
    
#if( AES_UTILS_USE_COMMON_CRYPTO )
exit:
#endif
    return( err );
}
Exemplo n.º 19
0
/* FIXME: Generalize so that it generates a few more blocks at a
 * time. */
static void
yarrow_generate_block(struct yarrow256_ctx *ctx,
		      quint8 *block)
{
  unsigned i;
  //aes_encrypt(&ctx->key, sizeof(ctx->counter), block, ctx->counter);
  aes_ecb_encrypt(ctx->counter,block,sizeof(ctx->counter),&ctx->key);

  /* Increment counter, treating it as a big-endian number. This is
   * machine independent, and follows appendix B of the NIST
   * specification of cipher modes of operation.
   *
   * We could keep a representation of thy counter as 4 32-bit values,
   * and write entire words (in big-endian byteorder) into the counter
   * block, whenever they change. */
  for (i = sizeof(ctx->counter); i--; )
    {
      if (++ctx->counter[i])
	break;
    }
}
Exemplo n.º 20
0
static int ecb_encrypt(struct blkcipher_desc *desc, struct scatterlist *dst,
		       struct scatterlist *src, unsigned int nbytes)
{
	struct crypto_aes_ctx *ctx = crypto_blkcipher_ctx(desc->tfm);
	int err, first, rounds = 6 + ctx->key_length / 4;
	struct blkcipher_walk walk;
	unsigned int blocks;

	desc->flags &= ~CRYPTO_TFM_REQ_MAY_SLEEP;
	blkcipher_walk_init(&walk, dst, src, nbytes);
	err = blkcipher_walk_virt(desc, &walk);

	kernel_neon_begin();
	for (first = 1; (blocks = (walk.nbytes / AES_BLOCK_SIZE)); first = 0) {
		aes_ecb_encrypt(walk.dst.virt.addr, walk.src.virt.addr,
				(u8 *)ctx->key_enc, rounds, blocks, first);
		err = blkcipher_walk_done(desc, &walk, walk.nbytes % AES_BLOCK_SIZE);
	}
	kernel_neon_end();
	return err;
}
Exemplo n.º 21
0
void aes_cbc_encrypt(std::ostream & outputStream,
                     std::istream & inputStream,
                     const std::string & key,
                     const char * initializationVector)
{
    pkcs7_pad_streambuf pkcs7Padder(inputStream, CryptoPP::AES::BLOCKSIZE);
    std::istream pkcs7PaddedInput(&pkcs7Padder);
    char prevResult[CryptoPP::AES::BLOCKSIZE];
    for (std::istringstream prevResultStream(
             std::string(initializationVector, CryptoPP::AES::BLOCKSIZE));
         pkcs7PaddedInput;
         prevResultStream.clear(),
         prevResultStream.str(std::string(prevResult, sizeof prevResult))) {
        xor_streambuf xorCombiner(pkcs7PaddedInput, prevResultStream);
        std::istream xorCombinedInput(&xorCombiner);
        boost::iostreams::stream<boost::iostreams::array_sink>
            thisOutputSaver(prevResult, sizeof prevResult);
        tee_streambuf teeOutput(thisOutputSaver, outputStream);
        aes_ecb_encrypt(std::ostream(&teeOutput).flush(),
                        xorCombinedInput,
                        key,
                        false);
    }
}
Exemplo n.º 22
0
Arquivo: tom_aes.c Projeto: ufwt/bacs
int main(){
	unsigned char 	key128[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f};
	unsigned char 	key192[24] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17};
	unsigned char 	key256[32] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f};

	unsigned char 	ct[16];
	unsigned char 	vt[16];
	unsigned char 	pt[16] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
	symmetric_key 	skey128;
	symmetric_key 	skey192;
	symmetric_key 	skey256;


	/* AES 128 */
	if (aes_setup(key128, 16, 10, &skey128) != CRYPT_OK){
		printf("ERROR: in %s, unable to setup AES 128 key\n", __func__);
		return 0;
	}

	if (aes_ecb_encrypt(pt, ct, &skey128) != CRYPT_OK){
		printf("ERROR: in %s, unable to encrypt AES 128\n", __func__);
	}

	printf("Plaintext:      ");
	fprintBuffer_raw(stdout, (char*)pt, 16);
	printf("\nKey 128:        ");
	fprintBuffer_raw(stdout, (char*)key128, 16);
	printf("\nCiphertext 128: ");
	fprintBuffer_raw(stdout, (char*)ct, 16);

	if (aes_ecb_decrypt(ct, vt, &skey128) != CRYPT_OK){
		printf("ERROR: in %s, unable to decrypt AES 128\n", __func__);
	}

	if (!memcmp(vt, pt, 16)){
		printf("\nRecovery 128:   OK\n");
	}
	else{
		printf("\nRecovery 128:   FAIL\n");
	}

	aes_done(&skey128);


	/* AES 192 */
	if (aes_setup(key192, 24, 12, &skey192) != CRYPT_OK){
		printf("ERROR: in %s, unable to setup AES 192 key\n", __func__);
		return 0;
	}

	if (aes_ecb_encrypt(pt, ct, &skey192) != CRYPT_OK){
		printf("ERROR: in %s, unable to encrypt AES 192\n", __func__);
	}

	printf("Key 192:        ");
	fprintBuffer_raw(stdout, (char*)key192, 24);
	printf("\nCiphertext 192: ");
	fprintBuffer_raw(stdout, (char*)ct, 16);

	if (aes_ecb_decrypt(ct, vt, &skey192) != CRYPT_OK){
		printf("ERROR: in %s, unable to decrypt AES 192\n", __func__);
	}

	if (!memcmp(vt, pt, 16)){
		printf("\nRecovery 192:   OK\n");
	}
	else{
		printf("\nRecovery 192:   FAIL\n");
	}

	aes_done(&skey192);


	/* AES 256 */
	if (aes_setup(key256, 32, 14, &skey256) != CRYPT_OK){
		printf("ERROR: in %s, unable to setup AES 256 key\n", __func__);
		return 0;
	}

	if (aes_ecb_encrypt(pt, ct, &skey256) != CRYPT_OK){
		printf("ERROR: in %s, unable to encrypt AES 256\n", __func__);
	}

	printf("Key 256:        ");
	fprintBuffer_raw(stdout, (char*)key256, 32);
	printf("\nCiphertext 256: ");
	fprintBuffer_raw(stdout, (char*)ct, 16);

	if (aes_ecb_decrypt(ct, vt, &skey256) != CRYPT_OK){
		printf("ERROR: in %s, unable to decrypt AES 256\n", __func__);
	}

	if (!memcmp(vt, pt, 16)){
		printf("\nRecovery 256:   OK\n");
	}
	else{
		printf("\nRecovery 256:   FAIL\n");
	}

	aes_done(&skey256);

	return 0;
}
Exemplo n.º 23
0
mr_unsign32 aes_decrypt(aes *a,char *buff)
{
    int j,bytes;
    char st[16];
    mr_unsign32 fell_off;

   /* Supported modes of operation */
    fell_off=0;
    switch (a->mode)
    {
    case MR_ECB:
        aes_ecb_decrypt(a,(MR_BYTE *)buff);
        return 0;
    case MR_CBC:
        for (j=0;j<4*NB;j++) 
        {
            st[j]=a->f[j];
            a->f[j]=buff[j];
        }
        aes_ecb_decrypt(a,(MR_BYTE *)buff);
        for (j=0;j<4*NB;j++)
        { 
            buff[j]^=st[j];
            st[j]=0;
        }
        return 0;
    case MR_CFB1:
    case MR_CFB2:
    case MR_CFB4:
        bytes=a->mode-MR_CFB1+1;
        for (j=0;j<bytes;j++) fell_off=(fell_off<<8)|a->f[j];
        for (j=0;j<4*NB;j++) st[j]=a->f[j];
        for (j=bytes;j<4*NB;j++) a->f[j-bytes]=a->f[j];
        aes_ecb_encrypt(a,(MR_BYTE *)st);
        for (j=0;j<bytes;j++)
        {
            a->f[16-bytes+j]=buff[j];
            buff[j]^=st[j];
        }
        return fell_off;
    case MR_OFB1:
    case MR_OFB2:
    case MR_OFB4:
    case MR_OFB8:
    case MR_OFB16:
        bytes=a->mode-MR_OFB1+1;
        aes_ecb_encrypt(a,(MR_BYTE *)(a->f));
        for (j=0;j<bytes;j++) buff[j]^=a->f[j];
        return 0;

    case MR_PCFB1:   /* error propagating CFB */
    case MR_PCFB2:
    case MR_PCFB4:
        
        bytes=a->mode-MR_PCFB1+1;
        for (j=0;j<bytes;j++) fell_off=(fell_off<<8)|a->f[j];
        for (j=0;j<4*NB;j++) st[j]=a->f[j];
        for (j=bytes;j<4*NB;j++) a->f[j-bytes]=a->f[j];
        aes_ecb_encrypt(a,(MR_BYTE *)st);
        for (j=0;j<bytes;j++)
        {
            a->f[16-bytes+j]=buff[j]^st[16-bytes+j];
            buff[j]^=st[j];
        }
        return fell_off;
    default:
        return 0;
    }
}
Exemplo n.º 24
0
void encrypt() 
{
    trigger_high();
    aes_ecb_encrypt(buf, key);
    trigger_low();
}
Exemplo n.º 25
0
OSStatus    AES_CTR_Update( AES_CTR_Context *inContext, const void *inSrc, size_t inLen, void *inDst )
{
    OSStatus            err;
    const uint8_t *     src;
    uint8_t *           dst;
    uint8_t *           buf;
    size_t              used;
    size_t              i;
    
    // inSrc and inDst may be the same, but otherwise, the buffers must not overlap.
    
#if( DEBUG )
    if( inSrc != inDst ) check_ptr_overlap( inSrc, inLen, inDst, inLen );
#endif
    
    src = (const uint8_t *) inSrc;
    dst = (uint8_t *) inDst;
    
    // If there's any buffered key material from a previous block then use that first.
    
    buf  = inContext->buf;
    used = inContext->used;
    while( ( inLen > 0 ) && ( used != 0 ) ) 
    {
        *dst++ = *src++ ^ buf[ used++ ];
        used %= kAES_CTR_Size;
        inLen -= 1;
    }
    inContext->used = used;
    
    // Process whole blocks.
    
    while( inLen >= kAES_CTR_Size )
    {
        #if( AES_UTILS_USE_COMMON_CRYPTO )
            err = CCCryptorUpdate( inContext->cryptor, inContext->ctr, kAES_CTR_Size, buf, kAES_CTR_Size, &i );
            require_noerr( err, exit );
            require_action( i == kAES_CTR_Size, exit, err = kSizeErr );
        #elif( AES_UTILS_USE_GLADMAN_AES )
            aes_ecb_encrypt( inContext->ctr, buf, kAES_CTR_Size, &inContext->ctx );
        #elif( AES_UTILS_USE_USSL )
            aes_crypt_ecb( &inContext->ctx, AES_ENCRYPT, inContext->ctr, buf );
        #else
            AES_encrypt( inContext->ctr, buf, &inContext->key );
        #endif
        AES_CTR_Increment( inContext->ctr );
        
        for( i = 0; i < kAES_CTR_Size; ++i )
        {
            dst[ i ] = src[ i ] ^ buf[ i ];
        }
        src   += kAES_CTR_Size;
        dst   += kAES_CTR_Size;
        inLen -= kAES_CTR_Size;
    }
    
    // Process any trailing sub-block bytes. Extra key material is buffered for next time.
    
    if( inLen > 0 )
    {
        #if( AES_UTILS_USE_COMMON_CRYPTO )
            err = CCCryptorUpdate( inContext->cryptor, inContext->ctr, kAES_CTR_Size, buf, kAES_CTR_Size, &i );
            require_noerr( err, exit );
            require_action( i == kAES_CTR_Size, exit, err = kSizeErr );
        #elif( AES_UTILS_USE_GLADMAN_AES )
            aes_ecb_encrypt( inContext->ctr, buf, kAES_CTR_Size, &inContext->ctx );
        #elif( AES_UTILS_USE_USSL )
            aes_crypt_ecb( &inContext->ctx, AES_ENCRYPT, inContext->ctr, buf );
        #else
            AES_encrypt( inContext->ctr, buf, &inContext->key );
        #endif
        AES_CTR_Increment( inContext->ctr );
        
        for( i = 0; i < inLen; ++i )
        {
            *dst++ = *src++ ^ buf[ used++ ];
        }
        
        // For legacy mode, always leave the used amount as 0 so we always increment the counter each time.
        
        if( !inContext->legacy )
        {
            inContext->used = used;
        }
    }
    err = kNoErr;
    
#if( AES_UTILS_USE_COMMON_CRYPTO )
exit:
#endif
    return( err );
}