Exemplo n.º 1
0
OSStatus
    AES_CTR_Init( 
        AES_CTR_Context *   inContext, 
        const uint8_t       inKey[ kAES_CTR_Size ], 
        const uint8_t       inNonce[ kAES_CTR_Size ] )
{
#if( AES_UTILS_USE_COMMON_CRYPTO )
    OSStatus        err;
    
    inContext->cryptor = NULL;
    err = CCCryptorCreate( kCCEncrypt, kCCAlgorithmAES128, kCCOptionECBMode, inKey, kAES_CTR_Size, NULL, 
        &inContext->cryptor );
    check_noerr( err );
    if( err ) return( err );
#elif( AES_UTILS_USE_GLADMAN_AES )
    aes_init();
    aes_encrypt_key128( inKey, &inContext->ctx );
#elif( AES_UTILS_USE_USSL )
    aes_setkey_enc( &inContext->ctx, (unsigned char *) inKey, kAES_CTR_Size * 8 );
#else
    AES_set_encrypt_key( inKey, kAES_CTR_Size * 8, &inContext->key );
#endif
    memcpy( inContext->ctr, inNonce, kAES_CTR_Size );
    inContext->used = 0;
    inContext->legacy = false;
    return( kNoErr );
}
Exemplo n.º 2
0
static void AES_Operation(CCOperation operation, void* key, size_t keySize,
						  FILE *fpInput, FILE *fpOutput)
{
	CCCryptorRef cryptorRef;
	CCCryptorStatus rc;
	rc = CCCryptorCreate(operation, kCCAlgorithmAES128, 0, key, keySize, NULL, &cryptorRef);
	assert(rc == kCCSuccess);
	
	char rawData[128/8];
	size_t bytesRead;
	while((bytesRead = fread(rawData, 1, sizeof(rawData), fpInput)) > 0)
	{
		char convertedData[128/8];
		size_t dataOutMoved;
		
		if(bytesRead < sizeof(rawData))
			bzero(&rawData[bytesRead], sizeof(rawData) - bytesRead);
		
		rc = CCCryptorUpdate(cryptorRef, rawData, sizeof(rawData), convertedData, sizeof(convertedData), &dataOutMoved);
		assert(rc == kCCSuccess);
		//assert(dataOutMoved == sizeof(convertedData));
		if(dataOutMoved != sizeof(convertedData))
			printf("Data out moved (%d) != converted (%d)\n", dataOutMoved, convertedData);
		
		if(dataOutMoved > 0)
			fwrite(convertedData, dataOutMoved, 1, fpOutput);
	}
	
	CCCryptorRelease(cryptorRef);
}
Exemplo n.º 3
0
OSStatus
    AES_CBCFrame_Init( 
        AES_CBCFrame_Context *  inContext, 
        const uint8_t           inKey[ kAES_CBCFrame_Size ], 
        const uint8_t           inIV[ kAES_CBCFrame_Size ], 
        Boolean                 inEncrypt )
{
#if( AES_UTILS_USE_COMMON_CRYPTO )
    OSStatus        err;
    
    inContext->cryptor = NULL;
    err = CCCryptorCreate( inEncrypt ? kCCEncrypt : kCCDecrypt, kCCAlgorithmAES128, 0, inKey, kAES_CTR_Size, 
        NULL, &inContext->cryptor );
    check_noerr( err );
    if( err ) return( err );
#elif( AES_UTILS_USE_GLADMAN_AES )
    aes_init();
    if( inEncrypt ) aes_encrypt_key128( inKey, &inContext->ctx.encrypt );
    else            aes_decrypt_key128( inKey, &inContext->ctx.decrypt );
    inContext->encrypt = inEncrypt;
#elif( AES_UTILS_USE_USSL )
    if( inEncrypt ) aes_setkey_enc( &inContext->ctx, (unsigned char *) inKey, kAES_CBCFrame_Size * 8 );
    else            aes_setkey_dec( &inContext->ctx, (unsigned char *) inKey, kAES_CBCFrame_Size * 8 );
    inContext->encrypt = inEncrypt;
#else
    if( inEncrypt ) AES_set_encrypt_key( inKey, kAES_CBCFrame_Size * 8, &inContext->key );
    else            AES_set_decrypt_key( inKey, kAES_CBCFrame_Size * 8, &inContext->key );
    inContext->mode = inEncrypt ? AES_ENCRYPT : AES_DECRYPT;
#endif
    memcpy( inContext->iv, inIV, kAES_CBCFrame_Size );
    return( kNoErr );
}
Exemplo n.º 4
0
selene_error_t *sln_cryptor_osx_cc_create(selene_t *s, int encrypt,
                                          sln_cipher_e type, const char *key,
                                          const char *iv,
                                          sln_cryptor_t **p_enc) {
  CCCryptorStatus rv;
  CCCryptorRef cryptor;
  size_t keylen;
  CCAlgorithm alg;
  CCOperation op;

  if (encrypt) {
    op = kCCEncrypt;
  } else {
    op = kCCDecrypt;
  }
  switch (type) {
    case SLN_CIPHER_AES_128_CBC:
      alg = kCCAlgorithmAES128;
      keylen = kCCKeySizeAES128;
      break;
    case SLN_CIPHER_AES_256_CBC:
      /* TODO: it is not clear from the docs why this is named AES-128, but if
       * you
       * pass in a key size that is for AES-256, it works (?????) as if it was
       * in AES-256 mode (!!!!!)
       */
      alg = kCCAlgorithmAES128;
      keylen = kCCKeySizeAES256;
      break;
    case SLN_CIPHER_RC4:
      alg = kCCAlgorithmRC4;
      keylen = SLN_CIPHER_RC4_128_KEY_LENGTH;
      break;
    default:
      return selene_error_createf(SELENE_ENOTIMPL,
                                  "Unsupported cipher type: %d", type);
  }

  rv = CCCryptorCreate(op, alg, 0, key, keylen, iv, &cryptor);

  if (rv != kCCSuccess) {
    return selene_error_createf(
        SELENE_EIO, "CCCryptorCreate failed CCCryptorStatus=%d", rv);
  } else {
    sln_cryptor_t *enc = sln_alloc(s, sizeof(sln_cryptor_t));
    enc->s = s;
    enc->baton = cryptor;
    enc->type = type;
    *p_enc = enc;
  }

  return SELENE_SUCCESS;
}
Exemplo n.º 5
0
crypt_aes_p crypt_aes_create(void* key, void* iv, size_t size) {
    
    assert(size == 16);
    
    struct crypt_aes_t *d = (struct crypt_aes_t*)malloc(sizeof(struct crypt_aes_t));
    memcpy(d->key, key, 16);
    memcpy(d->iv, iv, 16);
    
    OSStatus err = CCCryptorCreate(kCCDecrypt, kCCAlgorithmAES128, kCCOptionPKCS7Padding, key, 16, iv, &d->cryptor);
    
    if (err != noErr)
        return NULL;
    
    return d;
    
}
Exemplo n.º 6
0
static void transformAES_CBC(CCOperation operation, const CryptoAlgorithmAesCbcParams& parameters, const CryptoKeyAES& key, const CryptoOperationData& data, std::unique_ptr<PromiseWrapper> promise)
{
    static_assert(sizeof(parameters.iv) == kCCBlockSizeAES128, "Initialization vector size must be the same as algorithm block size");

    size_t keyLengthInBytes = key.key().size();
    if (keyLengthInBytes != 16 && keyLengthInBytes != 24 && keyLengthInBytes != 32) {
        promise->reject(nullptr);
        return;
    }

    CCCryptorRef cryptor;
#if PLATFORM(IOS) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090
    CCAlgorithm aesAlgorithm = kCCAlgorithmAES;
#else
    CCAlgorithm aesAlgorithm = kCCAlgorithmAES128;
#endif
    CCCryptorStatus status = CCCryptorCreate(operation, aesAlgorithm, kCCOptionPKCS7Padding, key.key().data(), keyLengthInBytes, parameters.iv.data(), &cryptor);
    if (status) {
        promise->reject(nullptr);
        return;
    }

    Vector<uint8_t> result(CCCryptorGetOutputLength(cryptor, data.second, true));

    size_t bytesWritten;
    status = CCCryptorUpdate(cryptor, data.first, data.second, result.data(), result.size(), &bytesWritten);
    if (status) {
        promise->reject(nullptr);
        return;
    }

    uint8_t* p = result.data() + bytesWritten;
    status = CCCryptorFinal(cryptor, p, result.end() - p, &bytesWritten);
    p += bytesWritten;
    if (status) {
        promise->reject(nullptr);
        return;
    }

    ASSERT(p <= result.end());
    result.shrink(p - result.begin());

    CCCryptorRelease(cryptor);

    promise->fulfill(result);
}
Exemplo n.º 7
0
int32_t mz_crypt_aes_set_decrypt_key(void *handle, const void *key, int32_t key_length)
{
    mz_crypt_aes *aes = (mz_crypt_aes *)handle;
    
    
    if (aes == NULL || key == NULL || key_length == 0)
        return MZ_PARAM_ERROR;
    
    mz_crypt_aes_reset(handle);
    
    aes->error = CCCryptorCreate(kCCDecrypt, kCCAlgorithmAES, 0, key, key_length, NULL, &aes->crypt);
        
    if (aes->error != kCCSuccess)
        return MZ_HASH_ERROR;

    return MZ_OK;
}
Exemplo n.º 8
0
static int
init_cc_key(int encp, CCAlgorithm alg, CCOptions opts, const void *key,
	    size_t keylen, const void *iv, CCCryptorRef *ref)
{
    CCOperation op = encp ? kCCEncrypt : kCCDecrypt;
    CCCryptorStatus ret;

    if (*ref) {
	if (key == NULL && iv) {
	    CCCryptorReset(*ref, iv);
	    return 1;
	}
	CCCryptorRelease(*ref);
    }

    if (key) {
        ret = CCCryptorCreate(op, alg, opts, key, keylen, iv, ref);
        if (ret)
	    return 0;
    }

    return 1;
}
Exemplo n.º 9
0
OSStatus    AES_ECB_Init( AES_ECB_Context *inContext, uint32_t inMode, const uint8_t inKey[ kAES_ECB_Size ] )
{
#if( AES_UTILS_USE_COMMON_CRYPTO )
    OSStatus        err;
    
    inContext->cryptor = NULL;
    err = CCCryptorCreate( inMode, kCCAlgorithmAES128, kCCOptionECBMode, inKey, kAES_ECB_Size, NULL, &inContext->cryptor );
    check_noerr( err );
    if( err ) return( err );
#elif( AES_UTILS_USE_GLADMAN_AES )
    aes_init();
    if( inMode == kAES_ECB_Mode_Encrypt )   aes_encrypt_key128( inKey, &inContext->ctx.encrypt );
    else                                    aes_decrypt_key128( inKey, &inContext->ctx.decrypt );
    inContext->encrypt = inMode;
#elif( AES_UTILS_USE_USSL )
    if( inMode == kAES_ECB_Mode_Encrypt )   aes_setkey_enc( &inContext->ctx, (unsigned char *) inKey, kAES_ECB_Size * 8 );
    else                                    aes_setkey_dec( &inContext->ctx, (unsigned char *) inKey, kAES_ECB_Size * 8 );
    inContext->mode = inMode;
#else
    AES_set_encrypt_key( inKey, kAES_ECB_Size * 8, &inContext->key );
    inContext->cryptFunc = ( inMode == kAES_ECB_Mode_Encrypt ) ? AES_encrypt : AES_decrypt;
#endif
    return( kNoErr );
}
Exemplo n.º 10
0
/* 
 * Test harness for CCCryptor with lots of options. 
 */
CCCryptorStatus doCCCrypt(
	bool forEncrypt,
	CCAlgorithm encrAlg,			
	bool doCbc,
	bool doPadding,
	const void *keyBytes, size_t keyLen,
	const void *iv,
	bool randUpdates,
	bool inPlace,								/* !doPadding only */
	size_t ctxSize,								/* if nonzero, we allocate ctx */
	bool askOutSize,
	const uint8_t *inText, size_t inTextLen,
	uint8_t **outText, size_t *outTextLen)		/* both returned, WE malloc */
{
	CCCryptorRef	cryptor = NULL;
	CCCryptorStatus crtn;
	CCOperation		op = forEncrypt ? kCCEncrypt : kCCDecrypt;
	CCOptions		options = 0;
	uint8_t			*outBuf = NULL;			/* mallocd output buffer */
	uint8_t			*outp;					/* running ptr into outBuf */
	const uint8		*inp;					/* running ptr into inText */
	size_t			outLen;					/* bytes remaining in outBuf */
	size_t			toMove;					/* bytes remaining in inText */
	size_t			thisMoveOut;			/* output from CCCryptUpdate()/CCCryptFinal() */
	size_t			outBytes;				/* total bytes actually produced in outBuf */
	char			ctx[CC_MAX_CTX_SIZE];	/* for CCCryptorCreateFromData() */
	uint8_t			*textMarker = NULL;		/* 8 bytes of marker here after expected end of 
											 * output */
	char			*ctxMarker = NULL;		/* ditto for caller-provided context */
	unsigned		dex;
	size_t			askedOutSize;			/* from the lib */
	size_t			thisOutLen;				/* dataOutAvailable we use */
	
	if(ctxSize > CC_MAX_CTX_SIZE) {
		printf("***HEY! Adjust CC_MAX_CTX_SIZE!\n");
		exit(1);
	}
	if(!doCbc) {
		options |= kCCOptionECBMode;
	}
	if(doPadding) {
		options |= kCCOptionPKCS7Padding;
	}
	
	/* just hack this one */
	outLen = inTextLen;
	if(forEncrypt) {
		outLen += MAX_BLOCK_SIZE;
	}
	
	outBuf = (uint8_t *)malloc(outLen + MARKER_LENGTH);
	memset(outBuf, 0xEE, outLen + MARKER_LENGTH);
	
	/* library should not touch this memory */
	textMarker = outBuf + outLen;
	memset(textMarker, MARKER_BYTE, MARKER_LENGTH);
	
	/* subsequent errors to errOut: */

	if(inPlace) {
		memmove(outBuf, inText, inTextLen);
		inp = outBuf;
	}
	else {
		inp = inText;
	}

	if(!randUpdates) {
		/* one shot */
		if(askOutSize) {
			crtn = CCCrypt(op, encrAlg, options,
				keyBytes, keyLen, iv,
				inp, inTextLen,
				outBuf, 0, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				printf("***Did not get kCCBufferTooSmall as expected\n");
				printf("   alg %d inTextLen %lu cbc %d padding %d keyLen %lu\n",
					(int)encrAlg, (unsigned long)inTextLen, (int)doCbc, (int)doPadding,
					(unsigned long)keyLen);
				printCCError("CCCrypt", crtn);
				crtn = -1;
				goto errOut;
			}
			outLen = askedOutSize;
		}
		crtn = CCCrypt(op, encrAlg, options,
			keyBytes, keyLen, iv,
			inp, inTextLen,
			outBuf, outLen, &outLen);
		if(crtn) {
			printCCError("CCCrypt", crtn);
			goto errOut;
		}
		*outText = outBuf;
		*outTextLen = outLen;
		goto errOut;
	}
	
	/* random multi updates */
	if(ctxSize) {
		size_t ctxSizeCreated;
		
		if(askOutSize) {
			crtn = CCCryptorCreateFromData(op, encrAlg, options,
				keyBytes, keyLen, iv,
				ctx, 0 /* ctxSize */,
				&cryptor, &askedOutSize);
			if(crtn != kCCBufferTooSmall) {
				printf("***Did not get kCCBufferTooSmall as expected\n");
				printCCError("CCCryptorCreateFromData", crtn);
				crtn = -1;
				goto errOut;
			}
			ctxSize = askedOutSize;
		}
		crtn = CCCryptorCreateFromData(op, encrAlg, options,
			keyBytes, keyLen, iv,
			ctx, ctxSize, &cryptor, &ctxSizeCreated);
		if(crtn) {
			printCCError("CCCryptorCreateFromData", crtn);
			return crtn;
		}
		ctxMarker = ctx + ctxSizeCreated;
		memset(ctxMarker, MARKER_BYTE, MARKER_LENGTH);
	}
	else {
		crtn = CCCryptorCreate(op, encrAlg, options,
			keyBytes, keyLen, iv,
			&cryptor);
		if(crtn) {
			printCCError("CCCryptorCreate", crtn);
			return crtn;
		}
	}
	
	toMove = inTextLen;		/* total to go */
	outp = outBuf;
	outBytes = 0;			/* bytes actually produced in outBuf */
	
	while(toMove) {
		uint32 thisMoveIn;			/* input to CCryptUpdate() */
		
		thisMoveIn = genRand(1, toMove);
		logSize(("###ptext segment len %lu\n", (unsigned long)thisMoveIn)); 
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, thisMoveIn, false);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorUpdate(cryptor, inp, thisMoveIn,
			outp, thisOutLen, &thisMoveOut);
		if(crtn) {
			printCCError("CCCryptorUpdate", crtn);
			goto errOut;
		}
		inp			+= thisMoveIn;
		toMove		-= thisMoveIn;
		outp		+= thisMoveOut;
		outLen   	-= thisMoveOut;
		outBytes	+= thisMoveOut;
	}
	
	if(doPadding) {
		/* Final is not needed if padding is disabled */
		if(askOutSize) {
			thisOutLen = CCCryptorGetOutputLength(cryptor, 0, true);
		}
		else {
			thisOutLen = outLen;
		}
		crtn = CCCryptorFinal(cryptor, outp, thisOutLen, &thisMoveOut);
	}
	else {
		thisMoveOut = 0;
		crtn = kCCSuccess;
	}
	
	if(crtn) {
		printCCError("CCCryptorFinal", crtn);
		goto errOut;
	}
	
	outBytes += thisMoveOut;
	*outText = outBuf;
	*outTextLen = outBytes;
	crtn = kCCSuccess;

	for(dex=0; dex<MARKER_LENGTH; dex++) {
		if(textMarker[dex] != MARKER_BYTE) {
			printf("***lib scribbled on our textMarker memory (op=%s)!\n",
				forEncrypt ? "encrypt" : "decrypt");
			crtn = (CCCryptorStatus)-1;
		}
	}
	if(ctxSize) {
		for(dex=0; dex<MARKER_LENGTH; dex++) {
			if(ctxMarker[dex] != MARKER_BYTE) {
				printf("***lib scribbled on our ctxMarker memory (op=%s)!\n",
					forEncrypt ? "encrypt" : "decrypt");
				crtn = (CCCryptorStatus)-1;
			}
		}
	}
	
errOut:
	if(crtn) {
		if(outBuf) {
			free(outBuf);
		}
	}
	if(cryptor) {
		CCCryptorRelease(cryptor);
	}
	return crtn;
}
Exemplo n.º 11
0
static wi_cipher_t * _wi_cipher_init_with_key(wi_cipher_t *cipher, wi_data_t *key, wi_data_t *iv) {
#ifdef WI_CIPHER_COMMONCRYPTO
	CCCryptorStatus		status;
#endif
	unsigned char		*key_buffer, *iv_buffer;
	
	key_buffer			= (unsigned char *) wi_data_bytes(key);
	iv_buffer			= iv ? (unsigned char *) wi_data_bytes(iv) : NULL;

	cipher->key			= wi_retain(key);
	cipher->iv			= wi_retain(iv);
	
#ifdef WI_CIPHER_OPENSSL
	if(EVP_EncryptInit(&cipher->encrypt_ctx, cipher->cipher, NULL, NULL) != 1) {
		wi_error_set_openssl_error();
		
		wi_release(cipher);
		
		return NULL;
	}
	
	if(EVP_DecryptInit(&cipher->decrypt_ctx, cipher->cipher, NULL, NULL) != 1) {
		wi_error_set_openssl_error();
		
		wi_release(cipher);
		
		return NULL;
	}
	
	_wi_cipher_configure_cipher(cipher);
	
	if(EVP_EncryptInit(&cipher->encrypt_ctx, cipher->cipher, key_buffer, iv_buffer) != 1) {
		wi_error_set_openssl_error();
		
		wi_release(cipher);
		
		return NULL;
	}
	
	if(EVP_DecryptInit(&cipher->decrypt_ctx, cipher->cipher, key_buffer, iv_buffer) != 1) {
		wi_error_set_openssl_error();
		
		wi_release(cipher);
		
		return NULL;
	}
#endif
	
#ifdef WI_CIPHER_COMMONCRYPTO
	status = CCCryptorCreate(kCCEncrypt,
							 cipher->algorithm,
							 kCCOptionPKCS7Padding,
							 key_buffer,
							 wi_data_length(cipher->key),
							 iv_buffer,
							 &cipher->encrypt_ref);
	
	if(status != kCCSuccess) {
		wi_error_set_commoncrypto_error(status);
		
		wi_release(cipher);
		
		return NULL;
	}
	
	status = CCCryptorCreate(kCCDecrypt,
							 cipher->algorithm,
							 kCCOptionPKCS7Padding,
							 key_buffer,
							 wi_data_length(cipher->key),
							 iv_buffer,
							 &cipher->decrypt_ref);
	
	if(status != kCCSuccess) {
		wi_error_set_commoncrypto_error(status);
		
		wi_release(cipher);
		
		return NULL;
	}
#endif

	return cipher;
}
Exemplo n.º 12
0
U8_EXPORT ssize_t u8_cryptic
(int do_encrypt,const char *cname,
 const unsigned char *key,int keylen,
 const unsigned char *iv,int ivlen,
 u8_block_reader reader,u8_block_writer writer,
 void *readstate,void *writestate,
 u8_context caller)
{
  if (strncasecmp(cname,"rsa",3)==0) {
    u8_seterr(_("RSA support NYI"),"u8_cryptic/CommonCrypto",u8_strdup(cname));
    return -1;}
  else {
    CCCryptorRef ctx;
    CCOptions options=0;
    ssize_t inlen, outlen, totalin=0, totalout=0, retval=0;
    unsigned char inbuf[1024], outbuf[1024];
    struct U8_CCCIPHER *cipher=get_cipher(cname);
    if (cipher) {
      size_t blocksize=cipher->cc_blocksize;
      ssize_t needivlen=cipher->cc_ivlen;
      if (!((keylen<=cipher->cc_keymax)&&(keylen>=cipher->cc_keymin)))
	return u8_reterr(u8_BadCryptoKey,
			 ((caller)?(caller):((u8_context)"u8_cryptic")),
			 u8_mkstring("%d!=[%d,%d](%s)",keylen,
				     cipher->cc_keymin,cipher->cc_keymax,
				     cname));
      if ((needivlen)&&(ivlen!=needivlen))
	return u8_reterr(u8_BadCryptoIV,
			 ((caller)?(caller):(COMMONCRYPTO_CRYPTIC)),
			 u8_mkstring("%d!=%d(%s)",ivlen,needivlen,cname));

      if (needivlen==0) iv=NULL;

      memset(&ctx,0,sizeof(ctx));

      CCCryptorStatus status=CCCryptorCreate
	(((do_encrypt)? (kCCEncrypt) : (kCCDecrypt)),
	 cipher->cc_algorithm,cipher->cc_opts,key,keylen,iv,&ctx);

      u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC,
	     " %s cipher=%s, keylen=%d/[%d,%d], ivlen=%d, blocksize=%d\n",
	     ((do_encrypt)?("encrypt"):("decrypt")),
	     cname,keylen,cipher->cc_keymin,cipher->cc_keymax,
	     ivlen,blocksize);

      while (1) {
	inlen = reader(inbuf,blocksize,readstate);
	if (inlen <= 0) {
	  u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC,
		 "Finished %s(%s) with %ld in, %ld out",
		 ((do_encrypt)?("encrypt"):("decrypt")),cname,
		 totalin,totalout);
	  break;}
	if ((status=CCCryptorUpdate(ctx,inbuf,inlen,outbuf,1024,&outlen))
	    !=kCCSuccess) {
	  CCCryptorRelease(ctx);
	  return u8_reterr(u8_InternalCryptoError,
			   ((caller)?(caller):((u8_context)"u8_cryptic")),
			   NULL);}
	else {
	  u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC,
		 "%s(%s) consumed %d/%ld bytes, emitted %d/%ld bytes"
		 " in=<%v>\n out=<%v>",
		 ((do_encrypt)?("encrypt"):("decrypt")),cname,
		 inlen,totalin,outlen,totalout+outlen,
		 inbuf,inlen,outbuf,outlen);
	  writer(outbuf,outlen,writestate);
	  totalout=totalout+outlen;}}

      if ((status=CCCryptorFinal(ctx,outbuf,1024,&outlen))!=kCCSuccess) {
	CCCryptorRelease(ctx);
	return u8_reterr(u8_InternalCryptoError,
			 ((caller)?(caller):((u8_context)"u8_cryptic")),
			 NULL);}
      else {
	writer(outbuf,outlen,writestate);
	u8_log(CRYPTO_LOGLEVEL,COMMONCRYPTO_CRYPTIC,
	       "%s(%s) done after consuming %ld/%ld bytes, emitting %ld/%ld bytes"
	       "\n final out=<%v>",
	       ((do_encrypt)?("encrypt"):("decrypt")),cname,
	       inlen,totalin,outlen,totalout+outlen,
	       outbuf,outlen);
	CCCryptorRelease(ctx);
	totalout=totalout+outlen;
	return totalout;}}
    else return u8_reterr("Unknown cipher",
			  ((caller)?(caller):((u8_context)"u8_cryptic")),
			  u8_strdup(cname));
  }
}
Exemplo n.º 13
0
int
decryptInit(int (*writerFunc)(void *, size_t), void *h)
{
  CCCryptorStatus status;
  int rv;

  writer = writerFunc;

  strm.zalloc = Z_NULL;
  strm.zfree = Z_NULL;
  strm.opaque = Z_NULL;
  strm.avail_in = 0;
  strm.next_in = Z_NULL;
  rv = inflateInit(&strm);
  if (rv != Z_OK) {
    printf("zlib init error\n");
    return(-1);
  }

  getPassword();

  memcpy(&header, h, sizeof(header));

  if (isZero(encKey, kCCKeySizeAES256) ||
      memcmp(header.keySalt, redsideSalts.keySalt, header.keySaltLen)) {

    redsideSalts.keySaltLen = header.keySaltLen;
    memcpy(redsideSalts.keySalt, header.keySalt, sizeof(header.keySalt));

    /* AES KEY DERIVATION */
    rv = CCKeyDerivationPBKDF(kCCPBKDF2,
                              password, strlen(password),
                              header.keySalt, header.keySaltLen,
                              kCCPRFHmacAlgSHA512,
                              kIterations,
                              encKey, kCCKeySizeAES256);
    if (rv < 0) {
      printf("Key derivation: error: %d\n", rv);
      exit(1);
    }
  }

  if (isZero(hmacKey, kCCKeySizeAES256) ||
      memcmp(header.hmacSalt, redsideSalts.hmacSalt, sizeof(header.hmacSalt))) {

    redsideSalts.hmacSaltLen = header.hmacSaltLen;
    memcpy(redsideSalts.hmacSalt, header.hmacSalt, header.hmacSaltLen);

    /* HMAC KEY DERIVATION */
    rv = CCKeyDerivationPBKDF(kCCPBKDF2,
                              password, strlen(password),
                              header.hmacSalt, header.hmacSaltLen,
                              kCCPRFHmacAlgSHA512,
                              kIterations,
                              hmacKey, kCCKeySizeAES256);
    if (rv < 0) {
      printf("HMAC Key derivation: error: %d\n", rv);
      exit(1);
    }
  }

  CCHmacInit(&hmacContext, kCCHmacAlgSHA512, hmacKey, kCCKeySizeAES256);
  CCHmacInit(&hmacContextPlain, kCCHmacAlgSHA512, hmacKey, kCCKeySizeAES256);

  status = CCCryptorCreate(kCCDecrypt,
                           kCCAlgorithmAES128,
                           kCCOptionPKCS7Padding,
                           encKey, kCCKeySizeAES256,
                           header.iv,
                           &cryptorRef);
  if (status != kCCSuccess) {
    printf("cryptor init error\n");
    return(-1);
  }

  return(0);
}
Exemplo n.º 14
0
int
encryptInit(int (*writerFunc)(void *, size_t),
            int (*seekerFunc)(size_t))
{
  CCCryptorStatus status;
  int rv;

  writer = writerFunc;
  seeker = seekerFunc;

  strm.zalloc = Z_NULL;
  strm.zfree = Z_NULL;
  strm.opaque = Z_NULL;
  rv = deflateInit(&strm, Z_DEFAULT_COMPRESSION);
  if (rv != Z_OK) {
    printf("zlib init error\n");
    return(-1);
  }

  getPassword();

  if (isZero(encKey, kCCKeySizeAES256) || isZero(hmacKey, kCCKeySizeAES256)) {

    header.keySaltLen = redsideSalts.keySaltLen;
    memcpy(header.keySalt, redsideSalts.keySalt, header.keySaltLen);

    /* AES KEY DERIVATION */
    rv = CCKeyDerivationPBKDF(kCCPBKDF2,
                              password, strlen(password),
                              header.keySalt, header.keySaltLen,
                              kCCPRFHmacAlgSHA512,
                              kIterations,
                              encKey, kCCKeySizeAES256);
    if (rv < 0) {
      printf("Key derivation: error: %d\n", rv);
      exit(1);
    }

    header.hmacSaltLen = redsideSalts.hmacSaltLen;
    memcpy(header.hmacSalt, redsideSalts.hmacSalt, header.hmacSaltLen);

    /* HMAC KEY DERIVATION */
    rv = CCKeyDerivationPBKDF(kCCPBKDF2,
                              password, strlen(password),
                              header.hmacSalt, header.hmacSaltLen,
                              kCCPRFHmacAlgSHA512,
                              kIterations,
                              hmacKey, kCCKeySizeAES256);
    if (rv < 0) {
      printf("HMAC Key derivation: error: %d\n", rv);
      exit(1);
    }
  }

  if (isZero(header.iv, sizeof(header.iv)))
    getSalt(header.iv, sizeof(header.iv));

  CCHmacInit(&hmacContext, kCCHmacAlgSHA512, hmacKey, kCCKeySizeAES256);
  CCHmacInit(&hmacContextPlain, kCCHmacAlgSHA512, hmacKey, kCCKeySizeAES256);

  status = CCCryptorCreate(kCCEncrypt,
                           kCCAlgorithmAES128,
                           kCCOptionPKCS7Padding,
                           encKey, kCCKeySizeAES256,
                           header.iv,
                           &cryptorRef);
  if (status != kCCSuccess) {
    printf("cryptor init error\n");
    return(-1);
  }

  seeker(sizeof(header));

  return(0);
}
int main(int argc, char **argv)
{
	unsigned loops = LOOPS_DEF;
	unsigned bufSize = BUFSIZE_DEF;
	unsigned algFirst = ALG_FIRST;
	unsigned algLast = ALG_LAST;
	bool ecbMode = false;
	extern char *optarg;
	int arg;
	while ((arg = getopt(argc, argv, "a:l:b:eh")) != -1) {
		switch (arg) {
			case 'a':
				switch(optarg[0]) {
					case 'a':
						algFirst = algLast = ALG_AES_128;
						break;
					case 'n':
						algFirst = algLast = ALG_AES_192;
						break;
					case 'A':
						algFirst = algLast = ALG_AES_256;
						break;
					case 'd':
						algFirst = algLast = ALG_DES;
						break;
					case '3':
						algFirst = algLast = ALG_3DES;
						break;
					case 'c':
						algFirst = algLast = ALG_CAST;
					case '4':
						algFirst = algLast = ALG_RC4;
				}
				break;
			case 'l':
				loops = atoi(optarg);
				break;
			case 'b':
				bufSize = atoi(optarg);
				break;
			case 'e':
				ecbMode = true;
				break;
			case 'h':
				usage(argv);
		}
	}
	if(optind != argc) {
		usage(argv);
	}

	/* 
	 * encrypt and decrypt on workBuf
	 * save original ptext in saveBuf, compare at end as sanity check 
	 *   for ECB only
	 */
	unsigned char *workBuf = (unsigned char *)malloc(bufSize);
	unsigned char *saveBuf = (unsigned char *)malloc(bufSize);
	if((workBuf == NULL) || (saveBuf == NULL)) {
		printf("***malloc failure\n");
		exit(1);
	}
	appGetRandomBytes(workBuf, bufSize);
	memmove(saveBuf, workBuf, bufSize);
	
	uint8_t keyBytes[MAX_KEY_SIZE];
	size_t keyLength;
	
	appGetRandomBytes(keyBytes, MAX_KEY_SIZE);
	
	CCCryptorRef cryptor;
	CCAlgorithm alg;
	CCOptions options = 0;
	OSStatus ortn;
	
	if(ecbMode) {
		options |= kCCOptionECBMode;
	}
	
	unsigned currAlg;
	for(currAlg=algFirst; currAlg<=algLast; currAlg++) {
		const char *algStr = NULL;
		
		switch(currAlg) {
			case ALG_DES:
				keyLength = kCCKeySizeDES;
				alg = kCCAlgorithmDES;
				algStr = "DES ";
				break;
			case ALG_3DES:
				keyLength = kCCKeySize3DES;
				alg = kCCAlgorithm3DES;
				algStr = "3DES";
				break;
			case ALG_AES_128:
				keyLength = kCCKeySizeAES128;
				alg = kCCAlgorithmAES128;
				algStr = "AES128";
				break;
			case ALG_AES_192:
				keyLength = kCCKeySizeAES192;
				alg = kCCAlgorithmAES128;
				algStr = "AES192";
				break;
			case ALG_AES_256:
				keyLength = kCCKeySizeAES256;
				alg = kCCAlgorithmAES128;
				algStr = "AES256";
				break;
			case ALG_CAST:
				keyLength = kCCKeySizeMaxCAST;
				alg = kCCAlgorithmCAST;
				algStr = "CAST";
				break;
			case ALG_RC4:
				keyLength = kCCKeySizeMaxRC4;
				alg = kCCAlgorithmRC4;
				algStr = "RC4";
				break;
		}
		
		printf("Algorithm: %s  keySize: %u  mode: %s  loops: %u  bufSize: %u\n",
			algStr, (unsigned)keyLength, ecbMode ? "ECB" : "CBC",
			(unsigned)loops, (unsigned)bufSize);
			
		CFAbsoluteTime start, end;
		unsigned loop;
		size_t thisMoved;
		
		/* encrypt: GO */
		start = CFAbsoluteTimeGetCurrent();
		
		ortn = CCCryptorCreate(kCCEncrypt, alg, options,
			keyBytes, keyLength, NULL, &cryptor);
		if(ortn) {
			printCCError("CCCryptorCreate", ortn);
			exit(1);
		}
		
		for(loop=0; loop<loops; loop++) {
			ortn = CCCryptorUpdate(cryptor, workBuf, bufSize,
				workBuf, bufSize, &thisMoved);
			if(ortn) {
				printCCError("CCCryptorUpdate", ortn);
				exit(1);
			}
		}
		/* no padding, CCCryptFinal not needed */
		end = CFAbsoluteTimeGetCurrent();
		
		printf("   encrypt %u * %u bytes took %gs: %g KBytes/s\n",
			(unsigned)loops, (unsigned)bufSize,
			end - start,
			(loops * bufSize) / (end - start) / 1024.0);
			
		/* dncrypt: GO */
		start = CFAbsoluteTimeGetCurrent();
		
		ortn = CCCryptorCreate(kCCDecrypt, alg, options,
			keyBytes, keyLength, NULL, &cryptor);
		if(ortn) {
			printCCError("CCCryptorCreate", ortn);
			exit(1);
		}
		
		for(loop=0; loop<loops; loop++) {
			ortn = CCCryptorUpdate(cryptor, workBuf, bufSize,
				workBuf, bufSize, &thisMoved);
			if(ortn) {
				printCCError("CCCryptorUpdate", ortn);
				exit(1);
			}
		}
		/* no padding, CCCryptFinal not needed */
		end = CFAbsoluteTimeGetCurrent();
		
		printf("   decrypt %u * %u bytes took %gs: %g KBytes/s\n",
			(unsigned)loops, (unsigned)bufSize,
			end - start,
			(loops * bufSize) / (end - start) / 1024.0);
			
		if(ecbMode) {
			if(memcmp(workBuf, saveBuf, bufSize)) {
				printf("***plaintext miscompare!\n");
			}
		}
	}
	return 0;
}