int CommonCryptoSymOffset(int argc, char *const *argv) {
    int accum = 0;
    uint8_t iLikeBigBuffs[ILIKEEMDISBIG];
    uint8_t andICannotLie[ILIKEEMDISBIG];
    uint8_t iLikeEmRoundandBig[ILIKEEMDISBIG];
    int i;
    size_t moved;
    CCCryptorStatus retval;
    byteBuffer key = hexStringToBytes("010203040506070809000a0b0c0d0e0f");
    
    plan_tests(kTestTestCount);

    
    for(i=0; i<ALITTLEONTHESIDE; i++) {
        retval = CCCrypt(kCCEncrypt, kCCAlgorithmAES128, 0, key->bytes, key->len, NULL, iLikeBigBuffs+i, ILIKEEMDISBIG-16, andICannotLie+i, ILIKEEMDISBIG, &moved);
        retval = CCCrypt(kCCDecrypt, kCCAlgorithmAES128, 0, key->bytes, key->len, NULL, andICannotLie+i, moved, iLikeEmRoundandBig+i, ILIKEEMDISBIG, &moved);
        if(moved != (ILIKEEMDISBIG-16))
            retval = 99;
        else if(memcmp(iLikeBigBuffs+i, iLikeEmRoundandBig+i, moved))
            retval = 999;
        ok(retval == 0, "Encrypt/Decrypt Cycle");
        accum += retval;
    }
    
    return accum != 0;
}
예제 #2
0
static bool 
aes_operation(bool encrypt, const uint8_t *kek, size_t kek_len, uint8_t *block)
{
    uint64_t iv[2] = { 0 };
    size_t bytes_moved = 0;

    return (0 == CCCrypt(encrypt? kCCEncrypt : kCCDecrypt, 
                kCCAlgorithmAES128, 0, kek, kek_len, iv, 
                block, kCCBlockSizeAES128,
                block, kCCBlockSizeAES128, &bytes_moved));
}
예제 #3
0
static int p12Decrypt(pkcs12_context * context, const SecAsn1AlgId *algId,
	const SecAsn1Item *cipherText, SecAsn1Item *plainText)
{
	NSS_P12_PBE_Params pbep;
    // XXX/cs not requiring decoding, but if pbep is uninit this will fail later
	algIdParse(context, algId, &pbep);

	CCAlgorithm		alg = 0;
	uint32_t			keySizeInBits = 0;
	uint32_t			blockSizeInBytes = 0;	// for IV, optional
	CCOptions		options = 0;
	require_noerr_quiet(pkcsOidToParams(&algId->algorithm, &alg, &keySizeInBits, 
        &blockSizeInBytes, &options), out);

	uint32_t iterCount = 0;
	require_noerr(p12DataToInt(&pbep.iterations, &iterCount), out);

	/* P12 style key derivation */
	SecAsn1Item key = {0, NULL};
	if(keySizeInBits)
        alloc_item(context, &key, (keySizeInBits+7)/8);
    require_noerr(p12_pbe_gen(context->passphrase, pbep.salt.Data, pbep.salt.Length, 
        iterCount, PBE_ID_Key, key.Data, key.Length), out);
        
	/* P12 style IV derivation, optional */
	SecAsn1Item iv = {0, NULL};
	if(blockSizeInBytes) {
		alloc_item(context, &iv, blockSizeInBytes);
        require_noerr(p12_pbe_gen(context->passphrase, pbep.salt.Data, pbep.salt.Length, 
            iterCount, PBE_ID_IV, iv.Data, iv.Length), out);
    }

	SecAsn1Item ourPtext = {0, NULL};
    alloc_item(context, &ourPtext, cipherText->Length);
    require_noerr(CCCrypt(kCCDecrypt, alg, options/*kCCOptionPKCS7Padding*/, 
        key.Data, key.Length, iv.Data, cipherText->Data, cipherText->Length, 
        ourPtext.Data, ourPtext.Length, &ourPtext.Length), out);
    *plainText = ourPtext;

    return 0;
out:
    return -1;
}
예제 #4
0
파일: mschap.c 프로젝트: carriercomm/osx-2
static void
rc4_encrypt(const void * clear, uint32_t clear_length,
	    const void * key, uint32_t key_length,
	    void * cypher)
{
    size_t 		bytes_processed;
    CCCryptorStatus	status;

    /* sizeof(cypher) == clear_length */
    status = CCCrypt(kCCEncrypt, kCCAlgorithmRC4, 0,
		     key, key_length, NULL,
		     clear, clear_length,
		     cypher, clear_length,
		     &bytes_processed);
    if (status != kCCSuccess) {
	fprintf(stderr, "rc4_encrypt: CCCrypt failed with %d\n",
		status);
	return;
    }
    return;
}
  u2_weak
  j2_mcd(Pt5, aesc, de)(u2_wire wir_r,
                        u2_atom a,
                        u2_atom b)
  {
    c3_y    a_y[32];
    c3_y    b_y[16];
#if defined(U2_OS_osx)
    size_t  siz_i = 0;
#else
    AES_KEY key_u;
#endif

    c3_assert(u2_cr_met(3, a) <= 32);
    c3_assert(u2_cr_met(3, b) <= 16);

    u2_cr_bytes(0, 32, a_y, a);
    u2_cr_bytes(0, 16, b_y, b);

#if defined(U2_OS_osx)
    if ( kCCSuccess != CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                               kCCOptionECBMode, a_y, kCCKeySizeAES256, 0, b_y,
                               16, b_y, 16, &siz_i) )
    {
      return u2_bl_bail(wir_r, c3__exit);
    }
    else c3_assert(16 == siz_i);
#else
    if ( 0 != AES_set_decrypt_key(a_y, 256, &key_u) ) {
      return u2_bl_bail(wir_r, c3__exit);
    }
    else {
      AES_decrypt(b_y, b_y, &key_u);
    }
#endif

    return u2_ci_bytes(16, b_y);
  }
예제 #6
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;
}
예제 #7
0
/**
 * Encrypts a buffer using the crypto API
 *
 * @param SrcBuffer the source data being encrypted
 * @param SrcLen the size of the buffer in bytes
 * @param DestBuffer (out) chunk of memory that is written to
 * @param DestLen (in) the size of the dest buffer, (out) the size of the encrypted data
 *
 * @return true if the encryption worked, false otherwise
 */
static bool EncryptBuffer(const uint8* SrcBuffer,const uint32 SrcLen,uint8* DestBuffer,uint32& DestLen)
{
	bool bEncryptedOk = false;

#if PLATFORM_MAC
	unsigned long long MacAddress = 0;
	uint32 AddressSize = sizeof(unsigned long long);
	GetMacAddress((uint8*)&MacAddress,AddressSize);
	unsigned long long Entropy = 5148284414757334885ull;
	Entropy ^= MacAddress;

	uint8 Key[kCCKeySizeAES128];
	check(kCCKeySizeAES128 == 2*sizeof(unsigned long long));
	FMemory::Memcpy(Key,&Entropy,sizeof(Entropy));
	FMemory::Memcpy(Key+sizeof(Entropy),&Entropy,sizeof(Entropy));

	size_t OutBufferSize = SrcLen + kCCBlockSizeAES128;
	uint8* OutBuffer = (uint8*)FMemory::Malloc(OutBufferSize);
	FMemory::Memset(OutBuffer,0,OutBufferSize);

	size_t BytesEncrypted = 0;
	CCCryptorStatus Status = CCCrypt( kCCEncrypt, kCCAlgorithmAES128,
		kCCOptionPKCS7Padding, Key, kCCKeySizeAES128, NULL, SrcBuffer,
		SrcLen, OutBuffer, OutBufferSize, &BytesEncrypted);
	if (Status == kCCSuccess)
	{
		DestLen = BytesEncrypted;
		FMemory::Memcpy(DestBuffer,OutBuffer,DestLen);
		bEncryptedOk = true;
	}
	else
	{
		UE_LOG(LogTaskBrowser, Log, TEXT("CCCrypt failed w/ 0x%08x"), Status);
	}
	FMemory::Free(OutBuffer);
#elif PLATFORM_LINUX
	printf("STaskBrowser.cpp: LINUX EncryptBuffer()\n");
#elif PLATFORM_WINDOWS
	DATA_BLOB SourceBlob, EntropyBlob, FinalBlob;
	// Set up the datablob to encrypt
	SourceBlob.cbData = SrcLen;
	SourceBlob.pbData = (uint8*)SrcBuffer;
	// Get the mac address for mixing into the entropy (ties the encryption to a location)
	ULONGLONG MacAddress = 0;
	uint32 AddressSize = sizeof(ULONGLONG);
	GetMacAddress((uint8*)&MacAddress,AddressSize);
	// Set up the entropy blob (changing this breaks all previous encrypted buffers!)
	ULONGLONG Entropy = 5148284414757334885ui64;
	Entropy ^= MacAddress;
	EntropyBlob.cbData = sizeof(ULONGLONG);
	EntropyBlob.pbData = (uint8*)&Entropy;
	// Zero the output data
	FMemory::Memzero(&FinalBlob,sizeof(DATA_BLOB));
	// Now encrypt the data
	if (CryptProtectData(&SourceBlob,
		NULL,
		&EntropyBlob,
		NULL,
		NULL,
		CRYPTPROTECT_UI_FORBIDDEN,
		&FinalBlob))
	{
		if (FinalBlob.cbData <= DestLen)
		{
			// Copy the final results
			DestLen = FinalBlob.cbData;
			FMemory::Memcpy(DestBuffer,FinalBlob.pbData,DestLen);
			bEncryptedOk = true;
		}
		// Free the encryption buffer
		LocalFree(FinalBlob.pbData);
	}
	else
	{
		uint32 Error = GetLastError();
		UE_LOG(LogTaskBrowser, Log, TEXT("CryptProtectData failed w/ 0x%08x"), Error);
	}
#else
	unimplemented();
#endif
	return bEncryptedOk;
}
예제 #8
0
PSCryptorStatus PSCryptor::EncryptDecrypt (bool encrypt, const void* dataIn, size_t dataLen,
								void *dataOut, size_t dataOutAvailable, size_t *dataOutMoved)
{

#if _WIN32
	if (fSessionKey == NULL)
		return kCryptorUnknownErr; // for lack of better error

	BOOL result = 0;

	// if encrypting or decrypting not in place
	if (dataIn != dataOut)
		memcpy (dataOut, dataIn, dataLen);

	DWORD pdwDataLen = (DWORD) dataLen;

	if (encrypt)
		{
		result = CryptEncrypt ( fSessionKey,
								NULL,
								TRUE,
								0,
								(LPBYTE) dataOut,
								&pdwDataLen,
								(DWORD) dataOutAvailable);

		}
	else
		{
		result = CryptDecrypt ( fSessionKey,
								NULL,
								TRUE,
								0,
								(LPBYTE) dataOut,
								&pdwDataLen);
		}

	if (!result)
		return MapPlatformStatusToPSCryptorStatus (GetLastError ());

	*dataOutMoved = (size_t) pdwDataLen;
	return kCryptorSuccess;
#else
	CCOperation op = (encrypt ? kCCEncrypt : kCCDecrypt);

	CCCryptorStatus status = CCCrypt ( op,
									   kCCAlgorithm3DES,
									   kCCOptionPKCS7Padding,
									   (const void *) fDerivedKey,
									   kPBKDKeyLength,
									   NULL,
									   dataIn,
									   dataLen,
									   dataOut,
									   dataOutAvailable,
									   dataOutMoved);

	if (status == kCCSuccess)
		return kCryptorSuccess;

	return MapPlatformStatusToPSCryptorStatus (status);
#endif

}