/**
 * Convert a string to Hexadecimal
 *
 * @param aData			String descriptor
 * @param aDes			Descriptor where Hex value is stored
 *
 * @return				N/A
 *
 * @leave				System wide error
 */
void CT_DataVerify::ConvertString2HexL( const TDesC8& aData, TDes8& aDes )
    {
	TBuf8<DataVerify::KCharlength> charBuf;

	// Check that buffer is even number
	if( ( aData.Length() % DataVerify::KCharlength ) != 0 )
		{
		User::Leave( KErrBadDescriptor );
		}

	// Go through the data and convert it two characters at a time
	// buffer overflow does not occur because buffer is checked to be even number first
	for( TInt i = 0, limit = aData.Length()-DataVerify::KCharlength; i <= limit; i+=DataVerify::KCharlength )
		{
		// Clean char buffer first
		charBuf.Delete( 0, charBuf.Length() );
		
		// Add KCharlength characters into buffer
		for ( TInt j = 0; j < DataVerify::KCharlength; j++ )
			{
			charBuf.Append( aData[i+j] );
			}

		TUint number;
		TLex8 converter = TLex8( charBuf );
		// Two characters together represent a hex number in MD5 checksum
		User::LeaveIfError( converter.Val( number, EHex ) );

		aDes.Append( number );
		}
	}
// -----------------------------------------------------------------------------
// CSdpConnectionField::ParseIP6AddressL
// Parses IP6 address and checks that it is valid
// -----------------------------------------------------------------------------
//
HBufC8* CSdpConnectionField::ParseIP6AddressL(
    TInt aPos,
    TInetAddr& aAddr,
    const TDesC8& aAddress,
    TInt& aTTL,
    TUint& aNumberOfAddresses ) const
    {
    HBufC8* address = NULL;

    if ( aAddr.IsMulticast() )
        {
        // Multicast address - CAN contain one extra attribute,
        // number of addresses
        if ( aPos != aAddress.Length() )
            {
            // Validity check for number strings

            TBool digit = SdpUtil::IsDigit(
                aAddress.Mid( aPos + 1, aAddress.Length() - aPos - 1 ) );
            if ( !digit )
                {
                User::Leave( KErrSdpCodecConnectionField );
                }

            User::LeaveIfError( TLex8( aAddress.Mid(
                aPos + 1, aAddress.Length() - aPos - 1 ) ).Val(
                    aNumberOfAddresses, EDecimal ) );

            __ASSERT_ALWAYS( aNumberOfAddresses > 0,
                             User::Leave( KErrSdpCodecConnectionField ) );
            }
        else
            {
            aNumberOfAddresses = 1;
            }

        aTTL = KErrNotFound;    // IP6 does not use TTL
        address = aAddress.Left( aPos ).AllocL();
        }
    else
        {
        // Unicast address - cannot contain any multicast TTLs etc.
        if ( aPos == aAddress.Length() )
            {
            address = aAddress.AllocL();
            aTTL = KErrNotFound;
            aNumberOfAddresses = 1;
            }
        else
            {
            User::Leave( KErrSdpCodecConnectionField );
            }
        }

    return address;
    }
// -----------------------------------------------------------------------------
// CSdpOriginField::Get63Msbs
// Returns a maximum of 63 bits of information from the descriptor containing a
// decimal number.
// -----------------------------------------------------------------------------
//
TInt64 CSdpOriginField::Get63Msbs( const TDesC8& aDecimalValue ) const
	{	
	// The maximum amount of digits in a decimal number, that is guaranteed to
  	// fit into 63 bits, is 18. Even if all the 18 digits are 9, the decimal
  	// number is 999999999999999999.
  	const TInt64 KMaxAmountOfDecimalDigits = 18;

    TInt64 value( 0 );
    TPtrC8 msbPart = aDecimalValue.Left( KMaxAmountOfDecimalDigits );
	TLex8( msbPart ).Val( value );
    return value;
	}
TBool CSmfCredMgrClientSymbian::isPluginAuthenticatedL(QString PluginID)
	{
	CBufFlat* buf = CBufFlat::NewL(KMinBufSize);
	CleanupStack::PushL(buf);

	RBufWriteStream stream(*buf);
	CleanupClosePushL(stream);

	TPtr idPtr(qt_QString2HBufC(PluginID)->Des());
	SmfUtils::ExternalizeDesL(idPtr, stream);

	stream.CommitL();

	// to get the data from server, we create a space.
	HBufC8* retBuf = HBufC8::NewL(32);
	CleanupStack::PushL(retBuf);

	TPtr8 bufPtr = buf->Ptr(0);
	TPtr8 flag(retBuf->Des());

	TIpcArgs args;

	args.Set(0, &bufPtr);
	args.Set(1, &flag);

	iSession.RequestService(ECheckPluginAuthentication, args);

	TLex8 iLex = TLex8(flag);
	TInt value = 0;
	iLex.Val(value);

	CleanupStack::PopAndDestroy(retBuf);
	CleanupStack::PopAndDestroy(&stream);
	CleanupStack::PopAndDestroy(buf);

	if (value)
		{
		RDebug::Printf("flag returned is ETrue");
		return ETrue;
		}
	else
		{
		RDebug::Printf("flag returned is EFalse");
		return EFalse;
		}
	}
OMX_ERRORTYPE 
CBellagioOpenMaxSymbianLoader::GetRolesOfComponent(OMX_STRING compName,
                                                   OMX_U32 *pNumRoles,
                                                   OMX_U8 **roles)
{
    TInt index = 0;

    index = GetInfoIndex(compName);

    if (index < 0)
    {
        return OMX_ErrorComponentNotFound;
    }

    TLex8 lexer = TLex8((componentInfos[index])->OpaqueData());
    lexer.Val((TUint32 &)(*pNumRoles), EDecimal);

    if((*pNumRoles) == 0) 
    {
        return OMX_ErrorNone;
    }

    // check if client is asking only for the number of roles
    if (roles == NULL)
    {
        return OMX_ErrorNone;
    }

    // TODO We copy only one role here and there might be several of those
    TBuf8<257> role;
    TBufC8<1> endOfString((TText8*)"\0");

    role.Append((componentInfos[index])->DataType());
    role.Append(endOfString);

    strcpy((char*)roles[0], (char*)role.Ptr());

    return OMX_ErrorNone;
}
// -----------------------------------------------------------------------------
// CSdpRepeatField::ConstructL
// Symbian 2nd phase constructor can leave.
// -----------------------------------------------------------------------------
//
void CSdpRepeatField::ConstructL(const TDesC8& aText)
	{
    iPool = SdpCodecStringPool::StringPoolL();
    RArray <TPtrC8> lines;
    lines = SdpUtil::DivideToLinesL(aText, KErrSdpCodecRepeatField);
    CleanupClosePushL(lines);
    RArray<TPtrC8> repeatArray;
    repeatArray = SdpUtil::GetElementsFromLineL(lines[0], 
                                                KErrSdpCodecRepeatField);
    CleanupClosePushL(repeatArray);
    const TDesC8& repeatName = iPool.StringF(SdpCodecStringConstants::ERepeat,
                                        SdpCodecStringConstants::Table).DesC();    
    __ASSERT_ALWAYS(lines.Count() == 1
        && repeatArray.Count() >= 3
        && repeatName.CompareF(repeatArray[0]) == 0,
        User::Leave(KErrSdpCodecRepeatField));

    // repeat interval
    __ASSERT_ALWAYS(TLex8(repeatArray[1]).Peek() != '0', 
        User::Leave(KErrSdpCodecRepeatField));
    iRepeatInterval = TSdpTypedTime::DecodeL(repeatArray[1]);
    
    // active duration
    iActiveDuration = TSdpTypedTime::DecodeL(repeatArray[2]);

	if (repeatArray.Count() > 3)
		{
		for (TInt i = 3; i < repeatArray.Count(); i++)
			{
            User::LeaveIfError(iTimeOffsets.Append(
                TSdpTypedTime::DecodeL(repeatArray[i])));
			}
		}
    CleanupStack::PopAndDestroy(2); // lines, repeatArray
	__TEST_INVARIANT;
	}
// ---------------------------------------------------------------------------
// CSdpMediaField::ParseMediaL
// ---------------------------------------------------------------------------
//
void CSdpMediaField::ParseMediaL()
{
    iElementArray = iSdpCodecParseUtil->FirstLineArrayElementL(iPool,
                    SdpCodecStringConstants::EMedia,
                    KErrSdpCodecMediaField);
    __ASSERT_ALWAYS (iElementArray.Count() >= 4,
                     User::Leave(KErrSdpCodecMediaField));

    RStringF media = iPool.OpenFStringL(iElementArray[1]);
    CleanupClosePushL(media);
    SetMediaL(media);
    CleanupStack::Pop();//media
    media.Close();

    iProtocol = iPool.OpenFStringL(iElementArray[3]);

    TInt lineEndPosition = iElementArray[2].Locate('/');
    TUint port;
    if(lineEndPosition == KErrNotFound)
    {
        User::LeaveIfError(
            TLex8(iElementArray[2]).Val(port, EDecimal));
        SetPortL(port);
    }
    else
    {
        User::LeaveIfError(TLex8(
                               (iElementArray[2]).Left(lineEndPosition)).Val(port, EDecimal));
        SetPortL(port);
        User::LeaveIfError(TLex8(
                               (iElementArray[2]).Mid(lineEndPosition +1)).Val(port, EDecimal));
        SetPortCountL(port);
    }
    __ASSERT_ALWAYS(SdpUtil::IsTokenCharWithOptionalSlash(iElementArray[3]),
                    User::Leave(KErrArgument));

    //iProtocol = iPool.OpenFStringL(iElementArray[3]);

    TInt length = 0;
    TInt i;
    for(i=4; i<iElementArray.Count(); i++)
    {
        length += iElementArray[i].Length();
        if(i + 1 <iElementArray.Count())
        {
            length += KSPStr().Length();
        }
    }
    HBufC8* value = HBufC8::NewLC(length);
    TPtr8 ptr(value->Des());
    for(i=4; i<iElementArray.Count(); i++)
    {
        ptr.Append(iElementArray[i]);
        if(i + 1 <iElementArray.Count())
        {
            ptr.Append(KSPStr);
        }
    }
    SetFormatListL(*value);
    CleanupStack::Pop();//value
    delete value;
    iElementArray.Reset();
    if (iSdpCodecParseUtil->LineArray().Count() > 0)
    {
        iSdpCodecParseUtil->LineArray().Remove(0);
    }
}
// -----------------------------------------------------------------------------
// CSdpConnectionField::ParseIP4AddressL
// Parses IP4 address and checks that it is valid
// -----------------------------------------------------------------------------
//
HBufC8* CSdpConnectionField::ParseIP4AddressL(
    TInt aPos,
    TInetAddr& aAddr,
    const TDesC8& aAddress,
    TInt& aTTL,
    TUint& aNumberOfAddresses ) const
    {
    HBufC8* address = NULL;

    if ( aAddr.IsMulticast() )
        {
        // Multicast address - MUST contain TTL and possibly
        // number of addresses
        if ( aPos != aAddress.Length() )
            {
            TInt pos2 = aAddress.Right( aAddress.Length() - aPos - 1 ).Locate(
                KSlashChar );

            if ( pos2 != KErrNotFound )
                {
                pos2 += aPos + 1;

                // Validity check for number strings
                TBool digit = SdpUtil::IsDigit(
                    aAddress.Mid( aPos + 1, pos2 - aPos - 1 ) );
                digit = digit && SdpUtil::IsDigit(
                    aAddress.Mid( pos2 + 1, aAddress.Length() - pos2 - 1 ) );
                if ( !digit )
                    {
                    User::Leave( KErrSdpCodecConnectionField );
                    }

                // TTL & number of addresses
                User::LeaveIfError(
                    TLex8( aAddress.Mid( aPos + 1, pos2 - aPos - 1 ) ).Val(
                        aTTL ) );
                User::LeaveIfError(
                    TLex8( aAddress.Mid(
                        pos2 + 1, aAddress.Length() - pos2 - 1 ) ).Val(
                            aNumberOfAddresses, EDecimal ) );

                __ASSERT_ALWAYS( aTTL >= 0
                                && aTTL <= 255
                                && aNumberOfAddresses > 0,
                                User::Leave( KErrSdpCodecConnectionField ) );
                }
            else
                {
                // Validity check for number strings
                TBool digit = SdpUtil::IsDigit(
                   aAddress.Mid( aPos + 1, aAddress.Length() - aPos - 1 ) );
                if ( !digit )
                    {
                    User::Leave( KErrSdpCodecConnectionField );
                    }

                // Plain TTL
                User::LeaveIfError(
                    TLex8( aAddress.Mid(
                        aPos + 1, aAddress.Length() - aPos - 1 ) ).Val(
                            aTTL ) );
                aNumberOfAddresses = 1;

                __ASSERT_ALWAYS( aTTL >= 0 && aTTL <= 255,
                                 User::Leave( KErrSdpCodecConnectionField ) );
                }

            address = aAddress.Left( aPos ).AllocL();
            }
        else
            {
            User::Leave( KErrSdpCodecConnectionField );
            }
        }
    else
        {
        // Unicast address - cannot contain any multicast TTLs etc.
        if ( aPos == aAddress.Length() )
            {
            address = aAddress.AllocL();
            aTTL = KErrNotFound;
            aNumberOfAddresses = 1;
            }
        else
            {
            User::Leave( KErrSdpCodecConnectionField );
            }
        }

    return address;
    }
void CActionSet::PerformAction(TRequestStatus& aStatus)
{
    __UHEAP_MARK;
    TRequestStatus* status = &aStatus;
    iResult = EFalse;
    HBufC8* pkcs12Pwd = 0;

    // default value is NULL to avoid RVCT warning
    // C2874W: set may be used before being set
    CPBEncryptSet* set = 0;
    if (iKdf == 0)
    {
        CleanupStack::PushL(pkcs12Pwd);
        set = CPBEncryptSet::NewLC(*iPasswd, iCipher);
    }
    else
    {
        // if supply KDF, must also supply salt len and iteration count
        ASSERT(iSaltLenBytes != 0 && iIterCount != 0);

        CPBEncryptParms* ep = CPBEncryptParms::NewLC();

        ep->SetCipher(iCipher);

        TInt saltLenBytes;
        TInt r = TLex8(*iSaltLenBytes).Val(saltLenBytes);
        ASSERT(r == KErrNone);
        ep->ResizeSaltL(saltLenBytes);

        TInt iterCount;
        r = TLex8(*iIterCount).Val(iterCount);
        ASSERT(r == KErrNone);
        ep->SetIterations(iterCount);

        CleanupStack::PushL((CBase*)0);
        CleanupStack::Pop((CBase*)0);

        if (*iKdf == _L8("PKCS#5"))
        {
            ep->SetKdf(CPBEncryptParms::EKdfPkcs5);
            set = CPBEncryptSet::NewL(*iPasswd, *ep);
        }
        else if (*iKdf == _L8("PKCS#12"))
        {
            pkcs12Pwd = PKCS12KDF::GeneratePasswordLC(*iPasswd);
            ep->SetKdf(CPBEncryptParms::EKdfPkcs12);
            set = CPBEncryptSet::NewL(*pkcs12Pwd, *ep);
            CleanupStack::Pop(pkcs12Pwd);
        }
        else
            User::Panic(_L("Unrec KDF"), 0);

        CleanupStack::PopAndDestroy(ep);
        // encryption could leak here, but for reservation above
        CleanupStack::PushL(pkcs12Pwd);
        CleanupStack::PushL(set);
    }
    CPBEncryptor* encryptor = set->NewEncryptLC();
    HBufC8* ciphertextTemp = HBufC8::NewLC(encryptor->MaxFinalOutputLength(iInput->Length()));

    TPtr8 ciphertext = ciphertextTemp->Des();
    encryptor->ProcessFinalL(*iInput, ciphertext);
    TBuf<128> newPwdTemp(*iPasswd);
    newPwdTemp.Append('a');

    TBuf8<128> newPwdTemp8;

    TPBPassword newPassword(KNullDesC);
    if (pkcs12Pwd == 0)
        new(&newPassword) TPBPassword(newPwdTemp);
    else
    {
        HBufC8* newPwd = PKCS12KDF::GeneratePasswordLC(newPwdTemp);
        newPwdTemp8.Copy(*newPwd);
        new(&newPassword) TPBPassword(newPwdTemp8);
        CleanupStack::PopAndDestroy(newPwd);
    }

    set->ChangePasswordL(newPassword);

    //create a mem  buffer store
    CBufStore* store = CBufStore::NewLC(100);
    RStoreWriteStream write;

    //write the encrypted master key to a stream
    TStreamId keyStreamId = write.CreateLC(*store);
    write << set->EncryptedMasterKey();
    write.CommitL();
    CleanupStack::PopAndDestroy(); //CreateLC()

    //write the encryption data to another stream
    TStreamId dataStreamId = write.CreateLC(*store);
    set->EncryptionData().ExternalizeL(write);
    write.CommitL();
    CleanupStack::PopAndDestroy(); //CreateLC()

    //prepare to read the streams back in, creating a new TPBEncryptionData
    RStoreReadStream read;
    read.OpenLC(*store, dataStreamId);

    //read in Encryption data
    CPBEncryptionData* data = CPBEncryptionData::NewL(read);
    CleanupStack::PopAndDestroy(); //OpenLC()
    CleanupStack::PushL(data);

    //read in encrypted master key
    read.OpenLC(*store, keyStreamId);
    HBufC8* encryptedMasterKey = HBufC8::NewLC(read, 10000); //some large number

    //create a new set encryption class
    CPBEncryptSet* set2 = CPBEncryptSet::NewLC(*data, *encryptedMasterKey, newPassword);

    HBufC8* plaintextTemp = HBufC8::NewLC(ciphertext.Length());
    TPtr8 plaintext = plaintextTemp->Des();

    CPBDecryptor* decryptor = set2->NewDecryptLC();
    decryptor->Process(ciphertext, plaintext);

    //this Mid call is due to get rid of the decrypted padding at the end
    if(plaintext.Mid(0,iInput->Length()) == *iInput)
    {
        iResult = ETrue;
    }

    CleanupStack::PopAndDestroy(decryptor);
    CleanupStack::PopAndDestroy(plaintextTemp);
    CleanupStack::PopAndDestroy(set2);
    CleanupStack::PopAndDestroy(encryptedMasterKey);
    CleanupStack::PopAndDestroy(1); //OpenLC
    CleanupStack::PopAndDestroy(data);
    CleanupStack::PopAndDestroy(store);
    CleanupStack::PopAndDestroy(ciphertextTemp);
    CleanupStack::PopAndDestroy(encryptor);
    CleanupStack::PopAndDestroy(set);
    CleanupStack::PopAndDestroy(pkcs12Pwd);

    User::RequestComplete(status, KErrNone);
    iActionState = CTestAction::EPostrequisite;
    __UHEAP_MARKEND;
}