Example #1
0
bool ValidateRC2()
{
	cout << "\nRC2 validation suite running...\n\n";

	FileSource valdata("rc2val.dat", true, new HexDecoder);
	HexEncoder output(new FileSink(cout));
	SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE);
	SecByteBlock key(128);
	bool pass=true, fail;

	while (valdata.MaxRetrievable())
	{
		byte keyLen, effectiveLen;

		valdata.Get(keyLen);
		valdata.Get(effectiveLen);
		valdata.Get(key, keyLen);
		valdata.Get(plain, RC2Encryption::BLOCKSIZE);
		valdata.Get(cipher, RC2Encryption::BLOCKSIZE);

		apbt transE(new RC2Encryption(key, keyLen, effectiveLen));
		transE->ProcessBlock(plain, out);
		fail = memcmp(out, cipher, RC2Encryption::BLOCKSIZE) != 0;

		apbt transD(new RC2Decryption(key, keyLen, effectiveLen));
		transD->ProcessBlock(out, outplain);
		fail=fail || memcmp(outplain, plain, RC2Encryption::BLOCKSIZE);

		pass = pass && !fail;

		cout << (fail ? "FAILED   " : "passed   ");
		output.Put(key, keyLen);
		cout << "   ";
		output.Put(outplain, RC2Encryption::BLOCKSIZE);
		cout << "   ";
		output.Put(out, RC2Encryption::BLOCKSIZE);
		cout << endl;
	}
	return pass;
}
Example #2
0
bool ValidateRC2()
{
	std::cout << "\nRC2 validation suite running...\n\n";

	FileSource valdata("TestData/rc2val.dat", true, new HexDecoder);
	HexEncoder output(new FileSink(std::cout));
	SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE);
	SecByteBlock key(128);
	bool pass=true, fail;

	while (valdata.MaxRetrievable())
	{
		byte keyLen, effectiveLen;

		valdata.Get(keyLen);
		valdata.Get(effectiveLen);
		valdata.Get(key, keyLen);
		valdata.Get(plain, RC2Encryption::BLOCKSIZE);
		valdata.Get(cipher, RC2Encryption::BLOCKSIZE);

		auto_ptr<BlockTransformation> transE(new RC2Encryption(key, keyLen, effectiveLen));
		transE->ProcessBlock(plain, out);
		fail = !VerifyBufsEqual(out, cipher, RC2Encryption::BLOCKSIZE);

		auto_ptr<BlockTransformation> transD(new RC2Decryption(key, keyLen, effectiveLen));
		transD->ProcessBlock(out, outplain);
		fail=fail || !VerifyBufsEqual(outplain, plain, RC2Encryption::BLOCKSIZE);

		pass = pass && !fail;

		std::cout << (fail ? "FAILED   " : "passed   ");
		output.Put(key, keyLen);
		std::cout << "   ";
		output.Put(outplain, RC2Encryption::BLOCKSIZE);
		std::cout << "   ";
		output.Put(out, RC2Encryption::BLOCKSIZE);
		std::cout << std::endl;
	}
	return pass;
}
Example #3
0
int main(int argc, char* argv[])
{
    //stops the program if there are no command line arguments
    if (argc != 2)
    {
        printf("You must enter an argument.\n");
        return 1;
    }
    
    else
    {
        //key is changed to integer
        int k = atoi(argv[1]);
        printf("Enter a string you would like to encrypt with Caesar's cipher: \n");
        //gets the string from the user that we would like to encrypt
        char* s = GetString();
        char cipheredNum;
        int result;
        
        //loops through each char of the string
        for (int i = 0, n = strlen(s); i < n; i++)
        {
            //if the char is a capital or lowercase letter
            if (capital(s[i]) == 1 || lowerCase(s[i]) == 1)
            {
                //change to alphanumeric value, run the cipher, then change back to ascii
                int alphaNum = toAlpha(s[i]);
                cipheredNum = cipher(alphaNum, k);
                result = toAscii(cipheredNum);
            }
            //if the char is neither capital or lowercase, it stays the same
            else
                result = s[i];
            //prints the ciphered char before moving on to next char
            printf("%c", result);
        }
        printf("\n");
        return 0;
    }
}
Example #4
0
static int decrypt_input()
{
    Util::CipherInfo ci;
    ci.name = opt_decrypt;
    ci.password = opt_password;
    ci.encrypt = false;
    ci.aead = is_aead(ci);
    Util::Cipher cipher(ci);
    { // restore IV
        std::string iv;
        auto params= cipher.get_cipher_params();
        ci.iv.resize(params.ivsize);
        if (ci.aead) {
            opt_read_size += params.tag_size;
        }
        std::ifstream read_iv(opt_iv, std::ifstream::in | std::ifstream::binary);
        read_iv.read(&ci.iv[0], ci.iv.size());
    }
    cipher.accept();
    process_with(cipher);
    return 0;
}
Example #5
0
bool Exporter::write(const SecureByteArray &data, const SecureString &pwd)
{
  Q_D(Exporter);
  Q_ASSERT((data.size() % Crypter::AESBlockSize) == 0);
  QByteArray salt = Crypter::generateSalt();
  SecureByteArray iv;
  SecureByteArray key;
  Crypter::makeKeyAndIVFromPassword(pwd.toUtf8(), salt, key, iv);
  CryptoPP::CBC_Mode<CryptoPP::AES>::Encryption enc;
  enc.SetKeyWithIV(reinterpret_cast<const byte*>(key.constData()), key.size(), reinterpret_cast<const byte*>(iv.constData()));
  const int cipherSize = data.size();
  QByteArray cipher(cipherSize, static_cast<char>(0));
  CryptoPP::ArraySource s(
        reinterpret_cast<const byte*>(data.constData()), data.size(),
        true,
        new CryptoPP::StreamTransformationFilter(
          enc,
          new CryptoPP::ArraySink(reinterpret_cast<byte*>(cipher.data()), cipher.size()),
          CryptoPP::StreamTransformationFilter::NO_PADDING
          )
        );
  Q_UNUSED(s); // just to please the compiler
  QFile file(d->filename);
  bool opened = file.open(QIODevice::WriteOnly);
  if (!opened)
    return false;
  QByteArray block = salt + cipher;
  file.write(PemPreamble.toUtf8());
  file.write("\n");
  const SecureByteArray &b64 = block.toBase64();
  for (int i = 0; i < b64.size(); i += 64) {
    file.write(b64.mid(i, qMin(64, b64.size() - i)));
    file.write("\n");
  }
  file.write(PemEpilog.toUtf8());
  file.write("\n");
  file.close();
  return true;
}
Example #6
0
QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction)
{
    QCA::Initializer init;
    QByteArray temp = cipherText;

    // do padding ourselves
    if (direction) {
        while ((temp.length() % 8) != 0)
            temp.append('\0');
    }
    else {
        // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input
        if ((temp.length() % 12) != 0)
            return cipherText;

        temp = b64ToByte(temp);
        while ((temp.length() % 8) != 0)
            temp.append('\0');
    }

    QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
    QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key);
    QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
    temp2 += cipher.final().toByteArray();

    if (!cipher.ok())
        return cipherText;

    if (direction) {
        // Sanity check
        if ((temp2.length() % 8) != 0)
            return cipherText;

        temp2 = byteToB64(temp2);
    }

    return temp2;
}
Example #7
0
inline void EncContent(std::string& encryptedPackage, const std::string& org, const CipherParam& param, const std::string& key, const std::string& salt)
{
	uint64_t orgSize = org.size();
	const size_t blockSize = 4096;
	std::string data = org;
	data.resize(RoundUp(data.size(), size_t(16)));
#ifdef SAME_KEY
	data[data.size() - 2] = 0x4b; // QQQ remove this
	data[data.size() - 1] = 0x6a;
#endif
	encryptedPackage.reserve(data.size() + 8);
	encryptedPackage.resize(8);
	cybozu::Set64bitAsLE(&encryptedPackage[0], orgSize);

	const size_t n = (data.size() + blockSize - 1) / blockSize;
	for (size_t i = 0; i < n; i++) {
		const size_t len = (i < n - 1) ? blockSize : (data.size() % blockSize);
		std::string blockKey(4, 0);
		cybozu::Set32bitAsLE(&blockKey[0], static_cast<uint32_t>(i));
		const std::string iv = generateKey(param, salt, blockKey);
		encryptedPackage.append(cipher(param.cipherName, data.c_str() + i * blockSize, len, key, iv, cybozu::crypto::Cipher::Encoding));
	}
}
Example #8
0
/* Decrypt stdin to stdout, and exit */
int
decrypt()
{
	char buf[8*1024], *cp;
	int n;

	while ((n = fread(buf, 1, sizeof buf, stdin)) > 0) {
		if ((cp = cipher(buf, n, 0)) == NULL) {
			fprintf(stderr, "ermt: Error decoding input; see daemon.err syslog\n");
			exit(1);
		}
		fwrite(cp, 1, n, stdout);
	}
	if (ferror(stdin)) {
		perror("ermt: stdin: read");
		exit(1);
	}
	if (fflush(stdout)) {
		perror("ermt: stdout: write");
		exit(1);
	}
	exit(0);
}
Example #9
0
LLSD LLInventoryItem::asLLSD() const
{
	LLSD sd = LLSD();
	sd[INV_ITEM_ID_LABEL] = mUUID;
	sd[INV_PARENT_ID_LABEL] = mParentUUID;
	sd[INV_PERMISSIONS_LABEL] = ll_create_sd_from_permissions(mPermissions);

	U32 mask = mPermissions.getMaskBase();
	if(((mask & PERM_ITEM_UNRESTRICTED) == PERM_ITEM_UNRESTRICTED)
		|| (mAssetUUID.isNull()))
	{
		sd[INV_ASSET_ID_LABEL] = mAssetUUID;
	}
	else
	{
		// *TODO: get rid of this. Phoenix 2008-01-30
		LLUUID shadow_id(mAssetUUID);
		LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
		cipher.encrypt(shadow_id.mData, UUID_BYTES);
		sd[INV_SHADOW_ID_LABEL] = shadow_id;
	}
	sd[INV_ASSET_TYPE_LABEL] = LLAssetType::lookup(mType);
	sd[INV_INVENTORY_TYPE_LABEL] = mInventoryType;
	const char* inv_type_str = LLInventoryType::lookup(mInventoryType);
	if(inv_type_str)
	{
		sd[INV_INVENTORY_TYPE_LABEL] = inv_type_str;
	}
	//sd[INV_FLAGS_LABEL] = (S32)mFlags;
	sd[INV_FLAGS_LABEL] = ll_sd_from_U32(mFlags);
	sd[INV_SALE_INFO_LABEL] = mSaleInfo;
	sd[INV_NAME_LABEL] = mName;
	sd[INV_DESC_LABEL] = mDescription;
	sd[INV_CREATION_DATE_LABEL] = (S32) mCreationDate;

	return sd;
}
Example #10
0
bool Packet::dearmor(const void *key)
{
	unsigned char mangledKey[32];
	unsigned char macKey[32];
	unsigned char mac[16];
	const unsigned int payloadLen = size() - ZT_PACKET_IDX_VERB;
	unsigned char *const payload = field(ZT_PACKET_IDX_VERB,payloadLen);
	unsigned int cs = cipher();

	if ((cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_NONE)||(cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)) {
		_salsa20MangleKey((const unsigned char *)key,mangledKey);
		Salsa20 s20(mangledKey,256,field(ZT_PACKET_IDX_IV,8)/*,ZT_PROTO_SALSA20_ROUNDS*/);

		s20.encrypt12(ZERO_KEY,macKey,sizeof(macKey));
		Poly1305::compute(mac,payload,payloadLen,macKey);
		if (!Utils::secureEq(mac,field(ZT_PACKET_IDX_MAC,8),8))
			return false;

		if (cs == ZT_PROTO_CIPHER_SUITE__C25519_POLY1305_SALSA2012)
			s20.decrypt12(payload,payload,payloadLen);

		return true;
	} else return false; // unrecognized cipher suite
}
Example #11
0
// THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING
QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction)
{
    QCA::Initializer init;
    QByteArray temp = cipherText;
    if (direction) {
        // make sure cipherText is an interval of 8 bits. We do this before so that we
        // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail
        while ((temp.length() % 8) != 0)
            temp.append('\0');

        QCA::InitializationVector iv(8);
        temp.prepend(iv.toByteArray());  // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation
    }
    else {
        temp = QByteArray::fromBase64(temp);
        // supposedly nescessary if we get a truncated message also allows for decryption of 'crazy'
        // en/decoding clients that use STANDARDIZED PADDING TECHNIQUES
        while ((temp.length() % 8) != 0)
            temp.append('\0');
    }

    QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode;
    QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0")));
    QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray();
    temp2 += cipher.final().toByteArray();

    if (!cipher.ok())
        return cipherText;

    if (direction)  // send in base64
        temp2 = temp2.toBase64();
    else  // cut off the 8bits of IV
        temp2 = temp2.remove(0, 8);

    return temp2;
}
Example #12
0
      std::vector<Test::Result> run() override
         {
         Test::Result result("Package transform");

         std::unique_ptr<Botan::BlockCipher> cipher(Botan::BlockCipher::create("AES-128"));
         std::vector<uint8_t> input = unlock(Test::rng().random_vec(Test::rng().next_byte()));
         std::vector<uint8_t> output(input.size() + cipher->block_size());

         // aont_package owns/deletes the passed cipher object, kind of a bogus API
         Botan::aont_package(Test::rng(),
                             cipher->clone(),
                             input.data(), input.size(),
                             output.data());

         std::vector<uint8_t> decoded(output.size() - cipher->block_size());
         Botan::aont_unpackage(cipher->clone(),
                               output.data(), output.size(),
                               decoded.data());
         result.test_eq("Package transform is reversible", decoded, input);

         output[0] ^= 1;
         Botan::aont_unpackage(cipher->clone(),
                               output.data(), output.size(),
                               decoded.data());
         result.test_ne("Bitflip breaks package transform", decoded, input);

         output[0] ^= 1;
         Botan::aont_unpackage(cipher->clone(),
                               output.data(), output.size(),
                               decoded.data());
         result.test_eq("Package transform is still reversible", decoded, input);

         // More tests including KATs would be useful for these functions

         return std::vector<Test::Result>{result};
         }
Example #13
0
// virtual
BOOL LLInventoryItem::importLegacyStream(std::istream& input_stream)
{
	// *NOTE: Changing the buffer size will require changing the scanf
	// calls below.
	char buffer[MAX_STRING];	/* Flawfinder: ignore */
	char keyword[MAX_STRING];	/* Flawfinder: ignore */
	char valuestr[MAX_STRING];	/* Flawfinder: ignore */
	char junk[MAX_STRING];	/* Flawfinder: ignore */
	BOOL success = TRUE;

	keyword[0] = '\0';
	valuestr[0] = '\0';

	mInventoryType = LLInventoryType::IT_NONE;
	mAssetUUID.setNull();
	while(success && input_stream.good())
	{
		input_stream.getline(buffer, MAX_STRING);
		sscanf(	/* Flawfinder: ignore */
			buffer,
			" %254s %254s",
			keyword, valuestr);
		if(0 == strcmp("{",keyword))
		{
			continue;
		}
		if(0 == strcmp("}", keyword))
		{
			break;
		}
		else if(0 == strcmp("item_id", keyword))
		{
			mUUID.set(valuestr);
		}
		else if(0 == strcmp("parent_id", keyword))
		{
			mParentUUID.set(valuestr);
		}
		else if(0 == strcmp("permissions", keyword))
		{
			success = mPermissions.importLegacyStream(input_stream);
		}
		else if(0 == strcmp("sale_info", keyword))
		{
			// Sale info used to contain next owner perm. It is now in
			// the permissions. Thus, we read that out, and fix legacy
			// objects. It's possible this op would fail, but it
			// should pick up the vast majority of the tasks.
			BOOL has_perm_mask = FALSE;
			U32 perm_mask = 0;
			success = mSaleInfo.importLegacyStream(input_stream, has_perm_mask, perm_mask);
			if(has_perm_mask)
			{
				if(perm_mask == PERM_NONE)
				{
					perm_mask = mPermissions.getMaskOwner();
				}
				// fair use fix.
				if(!(perm_mask & PERM_COPY))
				{
					perm_mask |= PERM_TRANSFER;
				}
				mPermissions.setMaskNext(perm_mask);
			}
		}
		else if(0 == strcmp("shadow_id", keyword))
		{
			mAssetUUID.set(valuestr);
			LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
			cipher.decrypt(mAssetUUID.mData, UUID_BYTES);
		}
		else if(0 == strcmp("asset_id", keyword))
		{
			mAssetUUID.set(valuestr);
		}
		else if(0 == strcmp("type", keyword))
		{
			mType = LLAssetType::lookup(valuestr);
		}
		else if(0 == strcmp("inv_type", keyword))
		{
			mInventoryType = LLInventoryType::lookup(std::string(valuestr));
		}
		else if(0 == strcmp("flags", keyword))
		{
			sscanf(valuestr, "%x", &mFlags);
		}
		else if(0 == strcmp("name", keyword))
		{
			//strcpy(valuestr, buffer + strlen(keyword) + 3);
			// *NOTE: Not ANSI C, but widely supported.
			sscanf(	/* Flawfinder: ignore */
				buffer,
				" %254s%254[\t]%254[^|]",
				keyword, junk, valuestr);

			// IW: sscanf chokes and puts | in valuestr if there's no name
			if (valuestr[0] == '|')
			{
				valuestr[0] = '\000';
			}

			mName.assign(valuestr);
			LLStringUtil::replaceNonstandardASCII(mName, ' ');
			LLStringUtil::replaceChar(mName, '|', ' ');
		}
		else if(0 == strcmp("desc", keyword))
		{
			//strcpy(valuestr, buffer + strlen(keyword) + 3);
			// *NOTE: Not ANSI C, but widely supported.
			sscanf(	/* Flawfinder: ignore */
				buffer,
				" %254s%254[\t]%254[^|]",
				keyword, junk, valuestr);

			if (valuestr[0] == '|')
			{
				valuestr[0] = '\000';
			}

			mDescription.assign(valuestr);
			LLStringUtil::replaceNonstandardASCII(mDescription, ' ');
			/* TODO -- ask Ian about this code
			const char *donkey = mDescription.c_str();
			if (donkey[0] == '|')
			{
				llerrs << "Donkey" << llendl;
			}
			*/
		}
		else if(0 == strcmp("creation_date", keyword))
		{
			S32 date;
			sscanf(valuestr, "%d", &date);
			mCreationDate = date;
		}
		else
		{
			llwarns << "unknown keyword '" << keyword
					<< "' in inventory import of item " << mUUID << llendl;
		}
	}

	// Need to convert 1.0 simstate files to a useful inventory type
	// and potentially deal with bad inventory tyes eg, a landmark
	// marked as a texture.
	if((LLInventoryType::IT_NONE == mInventoryType)
	   || !inventory_and_asset_types_match(mInventoryType, mType))
	{
		lldebugs << "Resetting inventory type for " << mUUID << llendl;
		mInventoryType = LLInventoryType::defaultForAssetType(mType);
	}
	return success;
}
Example #14
0
File: ecb.cpp Project: AlexNk/botan
Key_Length_Specification ECB_Mode::key_spec() const
   {
   return cipher().key_spec();
   }
Example #15
0
      Test::Result run_one_test(const std::string& algo, const VarMap& vars) override
         {
         const std::vector<uint8_t> key      = get_req_bin(vars, "Key");
         const std::vector<uint8_t> expected = get_req_bin(vars, "Out");
         const std::vector<uint8_t> nonce    = get_opt_bin(vars, "Nonce");
         const size_t seek                   = get_opt_sz(vars, "Seek", 0);
         std::vector<uint8_t> input          = get_opt_bin(vars, "In");

         if(input.empty())
            input.resize(expected.size());

         Test::Result result(algo);

         const std::vector<std::string> providers =
            provider_filter(Botan::StreamCipher::providers(algo));

         if(providers.empty())
            {
            result.note_missing("block cipher " + algo);
            return result;
            }

         for(auto&& provider_ask : providers)
            {
            std::unique_ptr<Botan::StreamCipher> cipher(Botan::StreamCipher::create(algo, provider_ask));

            if(!cipher)
               {
               result.test_failure("Stream " + algo + " supported by " + provider_ask + " but not found");
               continue;
               }

            const std::string provider(cipher->provider());
            result.test_is_nonempty("provider", provider);
            result.test_eq(provider, cipher->name(), algo);
            cipher->set_key(key);

            if(nonce.size())
               {
               if(!cipher->valid_iv_length(nonce.size()))
                  throw Test_Error("Invalid nonce for " + algo);
               cipher->set_iv(nonce.data(), nonce.size());
               }
            else
               {
               /*
               * If no nonce was set then implicitly the cipher is using a
               * null/empty nonce. Call set_iv with such a nonce to make sure
               * set_iv accepts it.
               */
               if(!cipher->valid_iv_length(0))
                  throw Test_Error("Stream cipher " + algo + " requires nonce but none provided");
               cipher->set_iv(nullptr, 0);
               }

            if (seek != 0)
               cipher->seek(seek);

            // Test that clone works and does not affect parent object
            std::unique_ptr<Botan::StreamCipher> clone(cipher->clone());
            result.confirm("Clone has different pointer", cipher.get() != clone.get());
            result.test_eq("Clone has same name", cipher->name(), clone->name());
            clone->set_key(Test::rng().random_vec(cipher->maximum_keylength()));

            std::vector<uint8_t> buf = input;
            cipher->encrypt(buf);

            cipher->clear();

            result.test_eq(provider, "encrypt", buf, expected);
            }

         return result;
         }
void FSWSAssetBlacklist::loadBlacklist()
{
	if (gDirUtilp->fileExists(mBlacklistFileName))
	{
		llifstream blacklist_data_stream(mBlacklistFileName);
		if (blacklist_data_stream.is_open())
		{
			LLSD data;
			if (LLSDSerialize::fromXML(data, blacklist_data_stream) >= 1)
			{
				for (LLSD::map_const_iterator itr = data.beginMap(); itr != data.endMap(); ++itr)
				{
					LLUUID uid = LLUUID(itr->first);
					LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
					cipher.decrypt(uid.mData, UUID_BYTES);
					LLSD data = itr->second;
					if (uid.isNull())
					{
						continue;
					}

					LLAssetType::EType type = S32toAssetType(data["asset_type"].asInteger());
					if (type == LLAssetType::AT_NONE)
					{
						continue;
					}
					
					addNewItemToBlacklistData(uid, data, false);
				}
			}
		}
		blacklist_data_stream.close();
	}
	else
	{
		// Try to import old blacklist data from Phoenix
		std::string old_file = gDirUtilp->getOSUserDir() + gDirUtilp->getDirDelimiter() + "SecondLife" + gDirUtilp->getDirDelimiter() + "user_settings" + gDirUtilp->getDirDelimiter() + "floater_blist_settings.xml";
		if (gDirUtilp->fileExists(old_file))
		{
			LLSD datallsd;
			llifstream oldfile;
			oldfile.open(old_file.c_str());
			if (oldfile.is_open())
			{
				LLSDSerialize::fromXMLDocument(datallsd, oldfile);
				for (LLSD::map_const_iterator itr = datallsd.beginMap(); itr != datallsd.endMap(); ++itr)
				{
					LLUUID uid = LLUUID(itr->first);
					LLSD data = itr->second;
					if (uid.isNull() || !data.has("entry_name") || !data.has("entry_type") || !data.has("entry_date"))
					{
						continue;
					}
					LLAssetType::EType type = S32toAssetType(data["entry_type"].asInteger());
					
					LLSD newdata;
					newdata["asset_name"] = "[PHOENIX] " + data["entry_name"].asString();
					newdata["asset_type"] = type;
					newdata["asset_date"] = data["entry_date"].asString();

					//if (!data["ID_hashed"].asBoolean())
					//{
					//	uid = LLUUID::generateNewID(uid.asString() + "hash");
					//}
					
					addNewItemToBlacklistData(uid, newdata, false);
				}
			}
			oldfile.close();
			saveBlacklist();
			llinfos << "Using old Phoenix file: " << old_file << llendl;
		}
		else
		{
			llinfos << "No Settings file found." << old_file << llendl;
		}
	}
}
Example #17
0
void Transport::prepareHeaders(bool compressed, bool chunked,
    const String &response, const String& orig_response) {
  for (HeaderMap::const_iterator iter = m_responseHeaders.begin();
       iter != m_responseHeaders.end(); ++iter) {
    const vector<string> &values = iter->second;
    for (unsigned int i = 0; i < values.size(); i++) {
      addHeaderImpl(iter->first.c_str(), values[i].c_str());
    }
  }

  for (CookieMap::const_iterator iter = m_responseCookies.begin();
       iter != m_responseCookies.end(); ++iter) {
    addHeaderImpl("Set-Cookie", iter->second.c_str());
  }

  if (compressed) {
    addHeaderImpl("Content-Encoding", "gzip");
    removeHeaderImpl("Content-Length");
    // Remove the Content-MD5 header coming from PHP if we compressed the data,
    // as the checksum is going to be invalid.
    auto it = m_responseHeaders.find("Content-MD5");
    if (it != m_responseHeaders.end()) {
      removeHeaderImpl("Content-MD5");
      // Re-add it back unless this is a chunked response. We'd have to buffer
      // the response completely to compute the MD5, which defeats the purpose
      // of chunking.
      if (chunked) {
        raise_warning("Cannot use chunked HTTP response and Content-MD5 header "
          "at the same time. Dropping Content-MD5.");
      } else {
        string cur_md5 = it->second[0];
        String expected_md5 = StringUtil::Base64Encode(StringUtil::MD5(
          orig_response, true));
        // Can never trust these PHP people...
        if (expected_md5.c_str() != cur_md5) {
          raise_warning("Content-MD5 mismatch. Expected: %s, Got: %s",
            expected_md5.c_str(), cur_md5.c_str());
        }
        addHeaderImpl("Content-MD5", StringUtil::Base64Encode(StringUtil::MD5(
          response, true)).c_str());
      }
    }
  }

  if (m_responseHeaders.find("Content-Type") == m_responseHeaders.end() &&
      m_responseCode != 304) {
    string contentType = "text/html; charset="
                         + RuntimeOption::DefaultCharsetName;
    addHeaderImpl("Content-Type", contentType.c_str());
  }

  if (RuntimeOption::ExposeHPHP) {
    addHeaderImpl("X-Powered-By", "HPHP");
  }

  if ((RuntimeOption::ExposeXFBServer || RuntimeOption::ExposeXFBDebug) &&
      !RuntimeOption::XFBDebugSSLKey.empty() &&
      m_responseHeaders.find("X-FB-Debug") == m_responseHeaders.end()) {
    String ip = RuntimeOption::ServerPrimaryIP;
    String key = RuntimeOption::XFBDebugSSLKey;
    String cipher("AES-256-CBC");
    int iv_len = f_openssl_cipher_iv_length(cipher).toInt32();
    String iv = f_openssl_random_pseudo_bytes(iv_len);
    String encrypted =
      f_openssl_encrypt(ip, cipher, key, k_OPENSSL_RAW_DATA, iv);
    String output = StringUtil::Base64Encode(iv + encrypted);
    if (debug) {
      String decrypted =
        f_openssl_decrypt(encrypted, cipher, key, k_OPENSSL_RAW_DATA, iv);
      assert(decrypted->same(ip.get()));
    }
    addHeaderImpl("X-FB-Debug", output.c_str());
  }

  // shutting down servers, so need to terminate all Keep-Alive connections
  if (!RuntimeOption::EnableKeepAlive || isServerStopping()) {
    addHeaderImpl("Connection", "close");
    removeHeaderImpl("Keep-Alive");

    // so lower level transports can ignore incoming "Connection: keep-alive"
    removeRequestHeaderImpl("Connection");
  }
}
Example #18
0
void Transport::prepareHeaders(bool compressed, const void *data, int size) {
  for (HeaderMap::const_iterator iter = m_responseHeaders.begin();
       iter != m_responseHeaders.end(); ++iter) {
    const vector<string> &values = iter->second;
    for (unsigned int i = 0; i < values.size(); i++) {
      addHeaderImpl(iter->first.c_str(), values[i].c_str());
    }
  }

  for (CookieMap::const_iterator iter = m_responseCookies.begin();
       iter != m_responseCookies.end(); ++iter) {
    addHeaderImpl("Set-Cookie", iter->second.c_str());
  }

  if (compressed) {
    addHeaderImpl("Content-Encoding", "gzip");
    removeHeaderImpl("Content-Length");
    if (m_responseHeaders.find("Content-MD5") != m_responseHeaders.end()) {
      String response((const char *)data, size, AttachLiteral);
      removeHeaderImpl("Content-MD5");
      addHeaderImpl("Content-MD5", StringUtil::Base64Encode(
                      StringUtil::MD5(response, true)).c_str());
    }
  }

  if (m_responseHeaders.find("Content-Type") == m_responseHeaders.end() &&
      m_responseCode != 304) {
    string contentType = "text/html; charset="
                         + RuntimeOption::DefaultCharsetName;
    addHeaderImpl("Content-Type", contentType.c_str());
  }

  if (RuntimeOption::ExposeHPHP) {
    addHeaderImpl("X-Powered-By", "HPHP");
  }

  if ((RuntimeOption::ExposeXFBServer || RuntimeOption::ExposeXFBDebug) &&
      !RuntimeOption::XFBDebugSSLKey.empty() &&
      m_responseHeaders.find("X-FB-Debug") == m_responseHeaders.end()) {
    String ip = RuntimeOption::ServerPrimaryIP;
    String key = RuntimeOption::XFBDebugSSLKey;
    String cipher("AES-256-CBC");
    int iv_len = f_openssl_cipher_iv_length(cipher);
    String iv = f_openssl_random_pseudo_bytes(iv_len);
    String encrypted =
      f_openssl_encrypt(ip, cipher, key, k_OPENSSL_RAW_DATA, iv);
    String output = StringUtil::Base64Encode(iv + encrypted);
    if (debug) {
      String decrypted =
        f_openssl_decrypt(encrypted, cipher, key, k_OPENSSL_RAW_DATA, iv);
      ASSERT(decrypted->same(ip.get()));
    }
    addHeaderImpl("X-FB-Debug", output);
  }

  // shutting down servers, so need to terminate all Keep-Alive connections
  if (!RuntimeOption::EnableKeepAlive || isServerStopping()) {
    addHeaderImpl("Connection", "close");
    removeHeaderImpl("Keep-Alive");

    // so lower level transports can ignore incoming "Connection: keep-alive"
    removeRequestHeaderImpl("Connection");
  }
}
bool LLInventoryItem::fromLLSD(const LLSD& sd, bool is_new)
{

	LL_RECORD_BLOCK_TIME(FTM_INVENTORY_SD_DESERIALIZE);
	if (is_new)
	{
		// If we're adding LLSD to an existing object, need avoid
		// clobbering these fields.
		mInventoryType = LLInventoryType::IT_NONE;
		mAssetUUID.setNull();
	}
	std::string w;

	w = INV_ITEM_ID_LABEL;
	if (sd.has(w))
	{
		mUUID = sd[w];
	}
	w = INV_PARENT_ID_LABEL;
	if (sd.has(w))
	{
		mParentUUID = sd[w];
	}
	w = INV_PERMISSIONS_LABEL;
	if (sd.has(w))
	{
		mPermissions = ll_permissions_from_sd(sd[w]);
	}
	w = INV_SALE_INFO_LABEL;
	if (sd.has(w))
	{
		// Sale info used to contain next owner perm. It is now in
		// the permissions. Thus, we read that out, and fix legacy
		// objects. It's possible this op would fail, but it
		// should pick up the vast majority of the tasks.
		BOOL has_perm_mask = FALSE;
		U32 perm_mask = 0;
		if (!mSaleInfo.fromLLSD(sd[w], has_perm_mask, perm_mask))
		{
			goto fail;
		}
		if (has_perm_mask)
		{
			if(perm_mask == PERM_NONE)
			{
				perm_mask = mPermissions.getMaskOwner();
			}
			// fair use fix.
			if(!(perm_mask & PERM_COPY))
			{
				perm_mask |= PERM_TRANSFER;
			}
			mPermissions.setMaskNext(perm_mask);
		}
	}
	w = INV_SHADOW_ID_LABEL;
	if (sd.has(w))
	{
		mAssetUUID = sd[w];
		LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
		cipher.decrypt(mAssetUUID.mData, UUID_BYTES);
	}
	w = INV_ASSET_ID_LABEL;
	if (sd.has(w))
	{
		mAssetUUID = sd[w];
	}
	w = INV_LINKED_ID_LABEL;
	if (sd.has(w))
	{
		mAssetUUID = sd[w];
	}
	w = INV_ASSET_TYPE_LABEL;
	if (sd.has(w))
	{
		if (sd[w].isString())
		{
			mType = LLAssetType::lookup(sd[w].asString().c_str());
		}
		else if (sd[w].isInteger())
		{
			S8 type = (U8)sd[w].asInteger();
			mType = static_cast<LLAssetType::EType>(type);
		}
	}
	w = INV_INVENTORY_TYPE_LABEL;
	if (sd.has(w))
	{
		if (sd[w].isString())
		{
			mInventoryType = LLInventoryType::lookup(sd[w].asString().c_str());
		}
		else if (sd[w].isInteger())
		{
			S8 type = (U8)sd[w].asInteger();
			mInventoryType = static_cast<LLInventoryType::EType>(type);
		}
	}
	w = INV_FLAGS_LABEL;
	if (sd.has(w))
	{
		if (sd[w].isBinary())
		{
			mFlags = ll_U32_from_sd(sd[w]);
		}
		else if(sd[w].isInteger())
		{
			mFlags = sd[w].asInteger();
		}

		//<singu>
		// Define a few magic constants that are not accessible otherwise, from here.
		// mInventoryType:
		static U32 IT_WEARABLE = 18;	// LLInventoryType::IT_WEARABLE
		// mType, these are the two asset types that are IT_WEARABLE:
		static U32 AT_BODYPART = 13;	// LLAssetType::AT_BODYPART
		// Viewer local values:
		static U32 WT_UNKNOWN = 16;		// LLWearableType::WT_UNKNOWN
		static U32 WT_COUNT = 17;		// LLWearableType::WT_COUNT
		// The last 8 bits of mFlags contain the wearable type.
		static U32 II_FLAGS_WEARABLES_MASK = 0xff;	// LLInventoryItemFlags::II_FLAGS_WEARABLES_MASK

		// The wearable type is stored in the lower 8 bits of mFlags.
		U32 wt = mFlags & II_FLAGS_WEARABLES_MASK;

		// Because WT_UNKNOWN now has locally a special meaning, make sure we don't receive it from the server.
		if (wt == WT_UNKNOWN)
		{
			LL_DEBUGS() << "Received inventory item with wearable type WT_UNKNOWN from server!" << LL_ENDL;
			// Change this new wearable type to WT_COUNT, as if when we had not inserted WT_UNKNOWN locally.
			mFlags += 1;
			wt = WT_COUNT;
		}

		// Detect possible problematic items.
		if (wt == 0 && mInventoryType == IT_WEARABLE && mType != AT_BODYPART)
		{
			// This is not possible, and therefore is probably an item creatd by a pre-multiwear viewer (or Second Inventory, etc).
			// The wearable type is NOT a shape (0) in that case of course, but we don't know what it is without downloading the
			// asset.
			mFlags |= WT_UNKNOWN;
		}
		//</singu>
	}
	w = INV_NAME_LABEL;
	if (sd.has(w))
	{
		mName = sd[w].asString();
		LLStringUtil::replaceNonstandardASCII(mName, ' ');
		LLStringUtil::replaceChar(mName, '|', ' ');
	}
	w = INV_DESC_LABEL;
	if (sd.has(w))
	{
		mDescription = sd[w].asString();
		LLStringUtil::replaceNonstandardASCII(mDescription, ' ');
	}
	w = INV_CREATION_DATE_LABEL;
	if (sd.has(w))
	{
		mCreationDate = sd[w].asInteger();
	}

	// Need to convert 1.0 simstate files to a useful inventory type
	// and potentially deal with bad inventory tyes eg, a landmark
	// marked as a texture.
	if((LLInventoryType::IT_NONE == mInventoryType)
	   || !inventory_and_asset_types_match(mInventoryType, mType))
	{
		LL_DEBUGS() << "Resetting inventory type for " << mUUID << LL_ENDL;
		mInventoryType = LLInventoryType::defaultForAssetType(mType);
	}

	mPermissions.initMasks(mInventoryType);

	return true;
fail:
	return false;

}
Example #20
0
inline bool encode_in(
	std::string& encryptedPackage,
	EncryptionInfo& info,
	const std::string& data,
	cybozu::crypto::Cipher::Name cipherName,
	cybozu::crypto::Hash::Name hashName,
	int spinCount,
	const std::string& pass,
	const std::string& masterKey)
{
	if (spinCount > 10000000) throw cybozu::Exception("ms:encode_in:too large spinCount") << spinCount;
	CipherParam& keyData = info.keyData;
	CipherParam& encryptedKey = info.encryptedKey;

	keyData.setByName(cipherName, hashName);
	encryptedKey.setByName(cipherName, hashName);
	info.spinCount = spinCount;

	std::string& iv = encryptedKey.saltValue;
	FillRand(iv, encryptedKey.saltSize);
#ifdef SAME_KEY
	puts("QQQ defined SAME_KEY QQQ");
	iv = fromHex("F4994F9B2DCD5E0E84BC6386D4523D2C");
#endif
	const std::string pwHash = hashPassword(encryptedKey.hashName, iv, pass, spinCount);

	const std::string skey1 = generateKey(encryptedKey, pwHash, blkKey_VerifierHashInput);
	const std::string skey2 = generateKey(encryptedKey, pwHash, blkKey_encryptedVerifierHashValue);
	const std::string skey3 = generateKey(encryptedKey, pwHash, blkKey_encryptedKeyValue);

	std::string verifierHashInput;
	FillRand(verifierHashInput, encryptedKey.saltSize);
#ifdef SAME_KEY
	verifierHashInput = fromHex("FEDAECD950F9E82C47CADA29B7837C6D");
#endif

	verifierHashInput.resize(RoundUp(verifierHashInput.size(), encryptedKey.blockSize));

	info.encryptedVerifierHashInput = cipher(encryptedKey.cipherName, verifierHashInput, skey1, iv, cybozu::crypto::Cipher::Encoding);
	std::string hashedVerifier = cybozu::crypto::Hash::digest(encryptedKey.hashName, verifierHashInput);
	hashedVerifier.resize(RoundUp(hashedVerifier.size(), encryptedKey.blockSize));

	info.encryptedVerifierHashValue = cipher(encryptedKey.cipherName, hashedVerifier, skey2, iv, cybozu::crypto::Cipher::Encoding);

	std::string secretKey;
	FillRand(secretKey, encryptedKey.saltSize);
#ifdef SAME_KEY
	secretKey = fromHex("BF44FBB51BE1E88BF130156E117E7900");
#endif
	if (!masterKey.empty()) {
		secretKey = masterKey;
	}
	normalizeKey(secretKey, encryptedKey.keyBits / 8);

	info.encryptedKeyValue = cipher(encryptedKey.cipherName, secretKey, skey3, iv, cybozu::crypto::Cipher::Encoding);

	FillRand(keyData.saltValue, keyData.saltSize);
#ifdef SAME_KEY
	keyData.saltValue = fromHex("C49AAAEE99004C6B017EE5CD11B86729");
#endif

	EncContent(encryptedPackage, data, encryptedKey, secretKey, keyData.saltValue);

	GenerateIntegrityParameter(info.encryptedHmacKey, info.encryptedHmacValue, encryptedPackage, keyData, secretKey, keyData.saltValue);
	return true;
}
Example #21
0
File: ecb.cpp Project: AlexNk/botan
size_t ECB_Encryption::output_length(size_t input_length) const
   {
   return round_up(input_length, cipher().block_size());
   }
int KiesBNR::SMemoFiletoDecode(char* inputPath, char* outputPath){
	CString inputPathString = (CString)inputPath;
	if(!PathFileExists((LPCWSTR)inputPathString))
		return 0;

	UINT XMLDataOffset = 0;

	CFile input;
	if ( !input.Open((LPCWSTR)inputPathString, CFile::modeRead | CFile::modeNoTruncate | CFile::typeBinary) )
	{
		return false;
	}

	//XML 데이터 크기만큼의 버퍼 생성;
	int nBufSize = input.GetLength();
	char* XMLData = new char[nBufSize+1];
	ZeroMemory(XMLData, nBufSize+1);
	
	//버퍼에 XML 내용을 읽어들인다.;
	input.Seek(XMLDataOffset, input.begin);
	input.Read(XMLData, nBufSize+1);

	//XML 데이터가 NULL일경우 False 반환;
	if (XMLData == NULL) 
		return false;  

	//메모리상에 있는 XML 데이터를 오픈 (Parse);
	TiXmlDocument m_Document;
	m_Document.Parse(XMLData);	// xml open

	// 루트노드 접근.;
	TiXmlElement* pRoot = m_Document.FirstChildElement("SMemoItems"); 
	if (!pRoot) 
		goto END_PROCESS;

	// 값을 읽고자 하는 Welcome 엘리먼트로 접근.;
	TiXmlElement* pElem = pRoot->FirstChildElement("Items")->FirstChildElement();
	
	if (!pElem) 
		goto END_PROCESS;

	while(pElem)
	{
		CString str1 = _T("");
		CString str2 = _T("");
		CString str3 = _T("");
		CString str4 = _T("");
		CString element = _T("");
		DWORD str_Len = 0;
		TCHAR * dstTCHAR = NULL;

		char *psNode = (char*)pElem->Value();

		str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL);
		dstTCHAR = new TCHAR[str_Len + 1];
		memset(dstTCHAR, 0x00, str_Len * 2 + 2);

		MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len);
		element.Format(L"%s",dstTCHAR);
		delete [] dstTCHAR;


		if(element.Find(L"SMemoItem")!=-1)//SMemoItem이 들어옴..
		{
			TiXmlElement* pElem_1=pElem->FirstChildElement();

			while(pElem_1)
			{
				CString str_1=_T("");
				CString element_1=_T("");
				DWORD str_Len_1 = 0;
				TCHAR * dstTCHAR_1 = NULL;

				char *psNode_1 = (char*)pElem_1->Value();

				str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL);
				dstTCHAR_1 = new TCHAR[str_Len + 1];
				memset(dstTCHAR_1, 0x00, str_Len * 2 + 2);

				MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len);
				element_1.Format(L"%s",dstTCHAR_1);
				delete [] dstTCHAR_1;

				if(element_1.Find(_T("RecordID"))!= -1){
					TCHAR* dstTch1 = NULL;
					const char *text = pElem_1->GetText();

					if(text == NULL)
						break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch1 = new TCHAR[str_Len + 1];
					memset(dstTch1, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch1, str_Len);

					str1.Format((L"%s"),dstTch1);
					delete [] dstTch1;
				}else if(element_1.Find(_T("CreateDate"))!= -1){
					TCHAR* dstTch2 = NULL;
					const char *text = pElem_1->GetText();

					if(text == NULL)
						break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch2 = new TCHAR[str_Len + 1];
					memset(dstTch2, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch2, str_Len);

					str2.Format((L"%s"),dstTch2);
					str2.Format((L"%s"),UnixTimeToStrTime(str2.Left(10)));
					delete [] dstTch2;
				}else if(element_1.Find(_T("ModifiedDate"))!= -1){
					TCHAR* dstTch3 = NULL;
					const char *text = pElem_1->GetText();

					if(text == NULL)
						break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch3 = new TCHAR[str_Len + 1];
					memset(dstTch3, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch3, str_Len);

					str3.Format((L"%s"),dstTch3);
					str3.Format((L"%s"),UnixTimeToStrTime(str3.Left(10)));
					delete [] dstTch3;
				}else if((element_1.Right(8) == _T("Location") ))
				{
					TCHAR* dstTch4 = NULL;
					const char *text = pElem_1->GetText();

					if(text == NULL)
						break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch4 = new TCHAR[str_Len + 1];
					memset(dstTch4, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch4, str_Len);

					str4.Format((L"%s"),dstTch4);
					delete []dstTch4;
				}else if(element_1.Find(_T("LocationDecode"))!= -1){
					
					const char *text = pElem_1->GetText();

					if(text == NULL){
						stSMemoXml.recordID = str1;
						stSMemoXml.createDate = str2;
						stSMemoXml.modifiedDate = str3;
						stSMemoXml.location_ = str4;
						stSMemoXml.locationDecode = L"NULL";
						mSMemoXml.insert(pair_SMemoXml(stSMemoXml.recordID, stSMemoXml));
						stSMemoXml.recordID.Empty();
						stSMemoXml.createDate.Empty();
						stSMemoXml.modifiedDate.Empty();
						stSMemoXml.location_.Empty();
						stSMemoXml.locationDecode.Empty();
						break;
					}

					std::string cipher(text);
					PBYTE buf_cipher_ = (PBYTE)malloc(cipher.size()+1);
					buf_cipher_[cipher.size()] = 0x00;
					memcpy(buf_cipher_, cipher.c_str(), cipher.size());

					INT length = base64_decode((PCHAR)buf_cipher_, (unsigned char*)buf_cipher_, cipher.size()-8 );

					wchar_t *patt[4] = {L"<ThumbData>", L"<Text>", L"</ThumbData>", L"</Text>"};
					wchar_t strUnicode[256] = {0,};

					for(int i = 0 ; i < 2 ; i++){
						long startOffset = ps.patternFind((char*)buf_cipher_, length, 0, (char *)patt[i], wcslen(patt[i])*2, pattern_sp::eMethod_KMP) + wcslen(patt[i])*2;

						long endOffset = ps.patternFind((char*)buf_cipher_, length, 0, (char *)patt[i+2], wcslen(patt[i+2])*2, pattern_sp::eMethod_KMP);

						char* buf;int sizes = endOffset - startOffset;
						buf = new char[sizes];

						memcpy_s( buf, sizes, (char*)(buf_cipher_+startOffset), sizes );
						
						for(int a = 0 ; a < sizes ; a+=2){
							buf[a/2] = buf[a];
						}
						int halfsize = sizes/2;
						INT length2 = base64_decode(buf, (unsigned char*)buf, halfsize );

						if(i == 0){
							CFile file_;
							CString PNGFileName = NULL;
							PNGFileName.Format(L"%s%s%s", (CString)outputPath, str1, L"_memo.png");
							if ( !PathFileExists(PNGFileName) )	
							{
								if( file_.Open( PNGFileName, CFile::modeCreate | CFile::modeWrite ) == FALSE )
									return FALSE;
								file_.Write(buf,sizes/2);
								file_.Close();
							}
						}else{
							//int nLen = MultiByteToWideChar(CP_UTF8, 0, (const char*)buf, strlen((char*)buf), NULL, NULL);
							//MultiByteToWideChar(CP_UTF8, 0, (const char*)buf, strlen((const char*)buf), strUnicode, strlen((char*)buf)+10);// utf-8 to unicode
						} delete []buf;
					}
					
					stSMemoXml.recordID = str1;
					stSMemoXml.createDate = str2;
					stSMemoXml.modifiedDate = str3;
					stSMemoXml.location_ = str4;
					stSMemoXml.locationDecode = L"";
					mSMemoXml.insert(pair_SMemoXml(stSMemoXml.recordID, stSMemoXml));
					stSMemoXml.recordID.Empty();
					stSMemoXml.createDate.Empty();
					stSMemoXml.modifiedDate.Empty();
					stSMemoXml.location_.Empty();
					stSMemoXml.locationDecode.Empty();
				}
				pElem_1 = pElem_1->NextSiblingElement();
			}
		}
		pElem = pElem->NextSiblingElement();
	}


END_PROCESS:
	m_Document.Clear();
	if(XMLData)
		delete XMLData;
	CreateWriteSMemoXmlCSVFile((CString)outputPath);
	return 1;
}
int KiesBNR::OtherFilestoDecode(char* inputPath, char* outputPath, char* fileName){
	//Read Input File
	CString inputPathString = (CString)inputPath;
	if(!PathFileExists((LPCWSTR)inputPathString))
		return 0;

	UINT XMLDataOffset = 0;

	CFile input;
	if ( !input.Open((LPCWSTR)inputPathString, CFile::modeRead | CFile::modeNoTruncate | CFile::typeBinary) )
	{
		return false;
	}

	//XML 데이터 크기만큼의 버퍼 생성;
	int nBufSize = input.GetLength();
	char* XMLData = new char[nBufSize+1];
	ZeroMemory(XMLData, nBufSize+1);

	//버퍼에 XML 내용을 읽어들인다.;
	input.Seek(XMLDataOffset, input.begin);
	input.Read(XMLData, nBufSize+1);

	//XML 데이터가 NULL일경우 False 반환;
	if (XMLData == NULL) 
		return false;  

	//메모리상에 있는 XML 데이터를 오픈 (Parse);
	TiXmlDocument m_Document;
	m_Document.Parse(XMLData);	// xml open

	// 루트노드 접근.;
	TiXmlElement* pRoot = m_Document.FirstChildElement("MtpUtilItems"); 
	if (!pRoot) 
		goto END_PROCESS;

	// 값을 읽고자 하는 Welcome 엘리먼트로 접근.;
	TiXmlElement* pElem = pRoot->FirstChildElement("Items")->FirstChildElement();

	if (!pElem) 
		goto END_PROCESS;

	while(pElem)
	{
		CString str1=_T("");
		CString element=_T("");
		DWORD str_Len = 0;
		TCHAR * dstTCHAR = NULL;

		char *psNode = (char*)pElem->Value();

		str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL);
		dstTCHAR = new TCHAR[str_Len + 1];
		memset(dstTCHAR, 0x00, str_Len * 2 + 2);

		MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len);
		element.Format(L"%s",dstTCHAR);
		delete [] dstTCHAR;


		if(element.Find(L"MtpUtilItem")!=-1)
		{
			TiXmlElement* pElem_1=pElem->FirstChildElement();

			while(pElem_1)
			{
				CString str_1=_T("");
				CString element_1=_T("");
				DWORD str_Len_1 = 0;
				TCHAR * dstTCHAR_1 = NULL;

				char *psNode_1 = (char*)pElem_1->Value();

				str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL);
				dstTCHAR_1 = new TCHAR[str_Len + 1];
				memset(dstTCHAR_1, 0x00, str_Len * 2 + 2);

				MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len);
				element_1.Format(L"%s",dstTCHAR_1);
				delete [] dstTCHAR_1;

				if(element_1.Find(_T("FileContent"))!= -1){
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text == NULL)
						break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch = new TCHAR[str_Len + 1];
					memset(dstTch, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

					str1.Format((L"%s"),dstTch);
					delete [] dstTch;
					//base64 Decoding
					string cipher(text);
					PBYTE buf_cipher = (PBYTE)malloc(cipher.size()+1);
					buf_cipher[cipher.size()] = 0x00;
					memcpy(buf_cipher, cipher.c_str(), cipher.size());

					INT length = base64_decode((PCHAR)buf_cipher, buf_cipher, cipher.size());
					strcat_s(outputPath, strlen(outputPath)+8, "Decode_");
					strcat_s(outputPath, strlen(outputPath)+strlen(fileName)+1, fileName);
					
					CFile decodefileoutput;

					if ( !PathFileExists((CString)outputPath) )	
					{
						if( decodefileoutput.Open((CString)outputPath, CFile::modeCreate | CFile::modeWrite ) == FALSE)
							return FALSE;
						decodefileoutput.Write(buf_cipher, length);
						decodefileoutput.Close();
					}

					CArkLib ark;

					if(ark.Create(ARK_DLL_RELEASE_FILE_NAME)!=ARKERR_NOERR)
						return 0;
					if(ark.Open(outputPath) == FALSE)
						return 0;
					int len = strlen(outputPath)+2;
					strcat_s(outputPath, len + 2, "_");
					ark.ExtractAllTo(outputPath);
					ark.Destroy();
					
				}
				pElem_1 = pElem_1->NextSiblingElement();
			}
		}
		pElem = pElem->NextSiblingElement();
	}



END_PROCESS:
	m_Document.Clear();
	if(XMLData)
		delete XMLData;
	return 1;
}
int KiesBNR::MessageFiletoDecode(char* inputPath, char* outputPath){
	//Read Input File
	CString inputPathString = (CString)inputPath;
	if(!PathFileExists((LPCWSTR)inputPathString))
		return 0;

	UINT XMLDataOffset = 0;

	CFile input;
	if ( !input.Open((LPCWSTR)inputPathString, CFile::modeRead | CFile::modeNoTruncate | CFile::typeBinary) )
	{
		return false;
	}

	//XML 데이터 크기만큼의 버퍼 생성;
	int nBufSize = input.GetLength();
	char* XMLData = new char[nBufSize+1];
	ZeroMemory(XMLData, nBufSize+1);

	//버퍼에 XML 내용을 읽어들인다.;
	input.Seek(XMLDataOffset, input.begin);
	input.Read(XMLData, nBufSize+1);

	//XML 데이터가 NULL일경우 False 반환;
	if (XMLData == NULL) 
		return false;  

	//메모리상에 있는 XML 데이터를 오픈 (Parse);
	TiXmlDocument m_Document;
	m_Document.Parse(XMLData);	// xml open

	// 루트노드 접근.;
	TiXmlElement* pRoot = m_Document.FirstChildElement("MessageData"); 
	if (!pRoot) 
		goto END_PROCESS;

	// 값을 읽고자 하는 Welcome 엘리먼트로 접근.;
	TiXmlElement* pElem  = pRoot->FirstChildElement("SMSList")->FirstChildElement();
	TiXmlElement* pElem2 = pRoot->FirstChildElement("MMSList")->FirstChildElement();//HextoString

	if (!pElem) 
		goto END_PROCESS;

	while(pElem)
	{
		CString str1=_T("");
		CString str2=_T("");
		CString str3=_T("");
		CString str4=_T("");
		CString element=_T("");
		DWORD str_Len = 0;
		TCHAR * dstTCHAR = NULL;

		char *psNode = (char*)pElem->Value();

		str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL);
		dstTCHAR = new TCHAR[str_Len + 1];
		memset(dstTCHAR, 0x00, str_Len * 2 + 2);

		MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len);
		element.Format(L"%s",dstTCHAR);
		delete [] dstTCHAR;


		if(element.Find(L"SMSStoreItem") != -1)
		{
			TiXmlElement* pElem_1=pElem->FirstChildElement();

			//pElem1=pElem1->FirstChildElement();
			while(pElem_1)
			{
				CString str_1	   = _T("");
				CString element_1  = _T("");
				DWORD str_Len_1    = 0;
				TCHAR * dstTCHAR_1 = NULL;
				//	test.Format(L"%s", pElem->GetText()); 

				char *psNode_1 = (char*)pElem_1->Value();

				str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL);
				dstTCHAR_1 = new TCHAR[str_Len + 1];
				memset(dstTCHAR_1, 0x00, str_Len * 2 + 2);

				MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len);
				element_1.Format(L"%s",dstTCHAR_1);
				delete [] dstTCHAR_1;

				// CreateDate
				if(element_1.Find(_T("CreateDate"))!= -1) {
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text != NULL) {
						
						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str1.Format((L"%s"),dstTch);
						str1 = ConvertUTC(str1, 9); // UTC 시간 적용

						delete []dstTch;
					}
				}
				
				// Sender
				else if(element_1.Find(_T("Sender"))!= -1) {
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text != NULL) {
						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str2.Format((L"%s"),dstTch);
						delete []dstTch;
					}
					else
						str2 = L"NULL";
				}
				
				// Receivers
				else if(element_1.Find(_T("Receivers"))!= -1) {

					TiXmlElement* pElem_2 = pElem_1->FirstChildElement();
					const char *text = pElem_2->GetText();

					if(text != NULL) {
						TCHAR* dstTch = NULL;
						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str3.Format((L"%s"), dstTch);
						delete []dstTch;
					}
					else
						str3 = L"NULL";
				}
				
				else if(element_1.Find(_T("MsgState"))!= -1){
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text == NULL) break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch = new TCHAR[str_Len + 1];
					memset(dstTch, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

					str4.Format((L"%s"),dstTch);
					delete []dstTch;
				}
				
				// Encoded Content
				else if(element_1.Find(_T("EncodedContent"))!= -1)
				{
					const char *text = pElem_1->GetText();

					if(text == NULL) break;

					string cipher(text);
					PBYTE buf_cipher = (PBYTE)malloc(cipher.size()+1);
					buf_cipher[cipher.size()] = 0x00;
					memcpy(buf_cipher, cipher.c_str(), cipher.size());

					INT length = base64_decode((PCHAR)buf_cipher, buf_cipher, cipher.size());

					wchar_t strUnicode[256] = {0,};

					int nLen = MultiByteToWideChar(CP_UTF8, 0, (const char*)buf_cipher, strlen((const char*)buf_cipher), NULL, NULL);
					MultiByteToWideChar(CP_UTF8, 0, (const char*)buf_cipher, strlen((const char*)buf_cipher), strUnicode, nLen);// utf-8 to unicode
					
					//strUnicode 바꿔 저장
					stMessageXml.createDate		= str1;
					stMessageXml.sender			= str2;
					stMessageXml.receivers		= str3;
					stMessageXml.msgState		= str4;
					stMessageXml.encodedContent = strUnicode;
					mMessageXml.insert(pair_MessageXml(stMessageXml.createDate, stMessageXml));

					stMessageXml.createDate.Empty();
					stMessageXml.msgState.Empty();
					stMessageXml.sender.Empty();
					stMessageXml.receivers.Empty();
					stMessageXml.encodedContent.Empty();
				}

				pElem_1 = pElem_1->NextSiblingElement();
			}
		}
		pElem = pElem->NextSiblingElement();
	}

	while(pElem2)
	{
		CString str1=_T("");
		CString str2=_T("");
		CString str3=_T("");
		CString str4=_T("");
		CString str5=_T("");
		CString str6=_T("");
		CString element=_T("");
		DWORD str_Len = 0;
		TCHAR * dstTCHAR = NULL;

		char *psNode = (char*)pElem2->Value();

		str_Len = MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), NULL, NULL);
		dstTCHAR = new TCHAR[str_Len + 1];
		memset(dstTCHAR, 0x00, str_Len * 2 + 2);

		MultiByteToWideChar(CP_ACP, 0, psNode, strlen(psNode), dstTCHAR, str_Len);
		element.Format(L"%s",dstTCHAR);
		delete [] dstTCHAR;


		if(element.Find(L"MMSStoreItem") != -1)
		{
			TiXmlElement* pElem_1=pElem2->FirstChildElement();

			while(pElem_1)
			{
				CString str_1=_T("");
				CString element_1=_T("");
				DWORD str_Len_1 = 0;
				TCHAR * dstTCHAR_1 = NULL;

				char *psNode_1 = (char*)pElem_1->Value();

				str_Len = MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), NULL, NULL);
				dstTCHAR_1 = new TCHAR[str_Len + 1];
				memset(dstTCHAR_1, 0x00, str_Len * 2 + 2);

				MultiByteToWideChar(CP_ACP, 0, psNode_1, strlen(psNode_1), dstTCHAR_1, str_Len);
				element_1.Format(L"%s",dstTCHAR_1);
				delete [] dstTCHAR_1;

				if(element_1.Compare(_T("Folder")) == 0) {
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text != NULL) {
						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str1.Format((L"%s"),dstTch);
						delete []dstTch;
					}
				}

				// Sender
				else if(element_1.Find(_T("Sender"))!= -1) {
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text != NULL) {
						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str2.Format((L"%s"),dstTch);
						delete []dstTch;
					}
					else
						str2 = L"NULL";
						
				}

				// Receivers
				else if(element_1.Find(_T("Receivers"))!= -1) {

					TiXmlElement* pElem_2 = pElem_1->FirstChildElement();
					const char *text = pElem_2->GetText();

					if(text != NULL) {
						TCHAR* dstTch = NULL;
						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str3.Format((L"%s"), dstTch);
						delete []dstTch;
					}
					else
						str3 = L"NULL";
				}


				// CreateDate
				else if(element_1.Find(_T("CreateDate"))!= -1)
				{
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();

					if(text != NULL) {

						str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
						dstTch = new TCHAR[str_Len + 1];
						memset(dstTch, 0x00, str_Len * 2 + 2);

						MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

						str5.Format((L"%s"),dstTch);
						str5 = ConvertUTC(str5, 9); // UTC 시간 적용

						delete []dstTch;
					}
				}
				
				else if(element_1.Find(_T("MMSBody"))!= -1)
				{
					TCHAR* dstTch = NULL;
					const char *text = pElem_1->GetText();
					std::string newString;


					if(text == NULL)
						break;

					str_Len = MultiByteToWideChar(CP_ACP, 0, text, strlen(text), NULL, NULL);
					dstTch = new TCHAR[str_Len + 1];
					memset(dstTch, 0x00, str_Len * 2 + 2);

					MultiByteToWideChar(CP_ACP, 0, text, strlen(text), dstTch, str_Len);

					str6.Format((L"%s"),dstTch);
					delete []dstTch;

					CT2CA pszConvertedAnsiString (str6);

					string tmp(pszConvertedAnsiString);
					
					for(int i = 0; i < tmp.length() - 0x0c*2; i +=2)
					{
						string byte = tmp.substr(i+0x0c*2,2);
						char chr = (char) (int)strtol(byte.c_str(), NULL, 16);
						newString.push_back(chr);
					}

					wchar_t strUnicode[20480] = {0,};
					
					int nLen = MultiByteToWideChar(CP_UTF8, 0, (const char*)newString.c_str(), strlen((const char*)newString.c_str()), NULL, NULL);
					MultiByteToWideChar(CP_UTF8, 0, (const char*)newString.c_str(), strlen((const char*)newString.c_str()), strUnicode, nLen);// utf-8 to unicode
					

					//strUnicode 바꿔 저장
					stMMSMessageXml.folder     = str1;
					stMMSMessageXml.sender     = str2;
					stMMSMessageXml.receivers  = str3;
					stMMSMessageXml.createDate = str5;
					stMMSMessageXml.mMsbody    = strUnicode;
					mMMSMessageXml.insert(pair_MMSMessageXml(stMMSMessageXml.folder, stMMSMessageXml));

					stMMSMessageXml.folder.Empty();
					stMMSMessageXml.sender.Empty();
					stMMSMessageXml.receivers.Empty();
					stMMSMessageXml.createDate.Empty();
					stMMSMessageXml.mMsbody.Empty();
				}

				pElem_1 = pElem_1->NextSiblingElement();
			}
		}
		pElem2 = pElem2->NextSiblingElement();
	}


END_PROCESS:
	m_Document.Clear();
	if(XMLData)
		delete XMLData;
	CreateWriteSMSMessageXmlCSVFile((CString)outputPath);
	CreateWriteMMSMessageXmlCSVFile((CString)outputPath);
	return 1;
}
void LLSecAPIBasicHandler::_readProtectedData()
{	
	// attempt to load the file into our map
	LLPointer<LLSDParser> parser = new LLSDXMLParser();
	llifstream protected_data_stream(mProtectedDataFilename.c_str(), 
									llifstream::binary);

	if (!protected_data_stream.fail()) {
		int offset;
		U8 salt[STORE_SALT_SIZE];
		U8 buffer[BUFFER_READ_SIZE];
		U8 decrypted_buffer[BUFFER_READ_SIZE];
		int decrypted_length;	
		unsigned char unique_id[MAC_ADDRESS_BYTES];
        LLMachineID::getUniqueID(unique_id, sizeof(unique_id));
		LLXORCipher cipher(unique_id, sizeof(unique_id));

		// read in the salt and key
		protected_data_stream.read((char *)salt, STORE_SALT_SIZE);
		offset = 0;
		if (protected_data_stream.gcount() < STORE_SALT_SIZE)
		{
			throw LLProtectedDataException("Config file too short.");
		}

		cipher.decrypt(salt, STORE_SALT_SIZE);		

		// totally lame.  As we're not using the OS level protected data, we need to
		// at least obfuscate the data.  We do this by using a salt stored at the head of the file
		// to encrypt the data, therefore obfuscating it from someone using simple existing tools.
		// We do include the MAC address as part of the obfuscation, which would require an
		// attacker to get the MAC address as well as the protected store, which improves things
		// somewhat.  It would be better to use the password, but as this store
		// will be used to store the SL password when the user decides to have SL remember it, 
		// so we can't use that.  OS-dependent store implementations will use the OS password/storage 
		// mechanisms and are considered to be more secure.
		// We've a strong intent to move to OS dependent protected data stores.
		

		// read in the rest of the file.
		EVP_CIPHER_CTX ctx;
		EVP_CIPHER_CTX_init(&ctx);
		EVP_DecryptInit(&ctx, EVP_rc4(), salt, NULL);
		// allocate memory:
		std::string decrypted_data;	
		
		while(protected_data_stream.good()) {
			// read data as a block:
			protected_data_stream.read((char *)buffer, BUFFER_READ_SIZE);
			
			EVP_DecryptUpdate(&ctx, decrypted_buffer, &decrypted_length, 
							  buffer, protected_data_stream.gcount());
			decrypted_data.append((const char *)decrypted_buffer, protected_data_stream.gcount());
		}
		
		// RC4 is a stream cipher, so we don't bother to EVP_DecryptFinal, as there is
		// no block padding.
		EVP_CIPHER_CTX_cleanup(&ctx);
		std::istringstream parse_stream(decrypted_data);
		if (parser->parse(parse_stream, mProtectedDataMap, 
						  LLSDSerialize::SIZE_UNLIMITED) == LLSDParser::PARSE_FAILURE)
		{
			throw LLProtectedDataException("Config file cannot be decrypted.");
		}
	}
}
void LLSecAPIBasicHandler::_writeProtectedData()
{	
	std::ostringstream formatted_data_ostream;
	U8 salt[STORE_SALT_SIZE];
	U8 buffer[BUFFER_READ_SIZE];
	U8 encrypted_buffer[BUFFER_READ_SIZE];

	
	if(mProtectedDataMap.isUndefined())
	{
		LLFile::remove(mProtectedDataFilename);
		return;
	}
	// create a string with the formatted data.
	LLSDSerialize::toXML(mProtectedDataMap, formatted_data_ostream);
	std::istringstream formatted_data_istream(formatted_data_ostream.str());
	// generate the seed
	RAND_bytes(salt, STORE_SALT_SIZE);

	
	// write to a temp file so we don't clobber the initial file if there is
	// an error.
	std::string tmp_filename = mProtectedDataFilename + ".tmp";
	
	llofstream protected_data_stream(tmp_filename.c_str(), 
										llofstream::binary);
	try
	{
		
		EVP_CIPHER_CTX ctx;
		EVP_CIPHER_CTX_init(&ctx);
		EVP_EncryptInit(&ctx, EVP_rc4(), salt, NULL);
		unsigned char unique_id[MAC_ADDRESS_BYTES];
        LLMachineID::getUniqueID(unique_id, sizeof(unique_id));
		LLXORCipher cipher(unique_id, sizeof(unique_id));
		cipher.encrypt(salt, STORE_SALT_SIZE);
		protected_data_stream.write((const char *)salt, STORE_SALT_SIZE);

		while (formatted_data_istream.good())
		{
			formatted_data_istream.read((char *)buffer, BUFFER_READ_SIZE);
			if(formatted_data_istream.gcount() == 0)
			{
				break;
			}
			int encrypted_length;
			EVP_EncryptUpdate(&ctx, encrypted_buffer, &encrypted_length, 
						  buffer, formatted_data_istream.gcount());
			protected_data_stream.write((const char *)encrypted_buffer, encrypted_length);
		}
		
		// no EVP_EncrypteFinal, as this is a stream cipher
		EVP_CIPHER_CTX_cleanup(&ctx);

		protected_data_stream.close();
	}
	catch (...)
	{
		// it's good practice to clean up any secure information on error
		// (even though this file isn't really secure.  Perhaps in the future
		// it may be, however.
		LLFile::remove(tmp_filename);
		throw LLProtectedDataException("Error writing Protected Data Store");
	}

	// move the temporary file to the specified file location.
	if((((LLFile::isfile(mProtectedDataFilename) != 0) && 
		 (LLFile::remove(mProtectedDataFilename) != 0))) || 
	   (LLFile::rename(tmp_filename, mProtectedDataFilename)))
	{
		LLFile::remove(tmp_filename);
		throw LLProtectedDataException("Could not overwrite protected data store");
	}
}
Example #27
0
BUF_MEM *
retail_mac_des(const BUF_MEM * key, const BUF_MEM * in)
{
    /* ISO 9797-1 algorithm 3 retail mac without any padding */
    BUF_MEM * c_tmp = NULL, *d_tmp = NULL, *mac = NULL, *block = NULL;
    EVP_CIPHER_CTX * ctx = NULL;
    size_t len;

    check(key, "Invalid arguments");

    /* Flawfinder: ignore */
    len = EVP_CIPHER_block_size(EVP_des_cbc());
    check(key->length >= 2*len, "Key too short");

    ctx = EVP_CIPHER_CTX_new();
    if (!ctx)
        goto err;
    EVP_CIPHER_CTX_init(ctx);
    /* Flawfinder: ignore */
    if (!EVP_CipherInit_ex(ctx, EVP_des_cbc(), NULL,
            (unsigned char *) key->data, NULL, 1) ||
            !EVP_CIPHER_CTX_set_padding(ctx, 0))
        goto err;

    /* get last block of des_cbc encrypted input */
    /* Flawfinder: ignore */
    c_tmp = cipher(ctx, EVP_des_cbc(), NULL, NULL, NULL, 1, in);
    if (!c_tmp)
        goto err;
    block = BUF_MEM_create_init(c_tmp->data + c_tmp->length - len, len);

    /* decrypt last block with the rest of the key */
    /* IV is always NULL */
    /* Flawfinder: ignore */
    if (!block || !EVP_CipherInit_ex(ctx, EVP_des_cbc(), NULL,
            (unsigned char *) key->data + len, NULL, 0) ||
            !EVP_CIPHER_CTX_set_padding(ctx, 0))
        goto err;
    /* Flawfinder: ignore */
    d_tmp = cipher(ctx, EVP_des_cbc(), NULL, NULL, NULL, 0, block);

    /* encrypt last block with the first key */
    /* IV is always NULL */
    /* Flawfinder: ignore */
    if (!d_tmp || !EVP_CipherInit_ex(ctx, EVP_des_cbc(), NULL,
            (unsigned char *) key->data, NULL, 1) ||
            !EVP_CIPHER_CTX_set_padding(ctx, 0))
        goto err;
    /* Flawfinder: ignore */
    mac = cipher(ctx, EVP_des_cbc(), NULL, NULL, NULL, 1, d_tmp);

    BUF_MEM_free(block);
    BUF_MEM_free(c_tmp);
    BUF_MEM_free(d_tmp);
    EVP_CIPHER_CTX_free(ctx);

    return mac;

err:
    if (block)
        BUF_MEM_free(block);
    if (c_tmp)
        BUF_MEM_free(c_tmp);
    if (d_tmp)
        BUF_MEM_free(d_tmp);
    if (ctx)
        EVP_CIPHER_CTX_free(ctx);

    return NULL;
}
	void BuildMessage( bf_write& buf, byte msgtype, char const *mapname, unsigned int uSessionID )
	{
	
		bf_write	encrypted;
		byte		encrypted_data[ 2048 ];

		buf.WriteByte( C2M_PHONEHOME );
		buf.WriteByte( '\n' );
		buf.WriteByte( C2M_PHONEHOME_PROTOCOL_VERSION );
		buf.WriteLong( uSessionID ); // sessionid (request new id by sending 0)

		// encryption object
		IceKey cipher(1); /* medium encryption level */
		unsigned char ucEncryptionKey[8] = { 191, 1, 0, 222, 85, 39, 154, 1 };
		cipher.set( ucEncryptionKey );

		encrypted.StartWriting( encrypted_data, sizeof( encrypted_data ) );

		byte corruption_identifier = 0x01;

		encrypted.WriteByte( corruption_identifier );

		// Data version protocol
		encrypted.WriteByte( 1 );

		// Write the "build identifier"  -- unique to each person we give a build to.
		encrypted.WriteString( m_szBuildIdentifier ); 
		{
			char computername[ 64 ];
			Q_memset( computername, 0, sizeof( computername ) );
#if defined ( _WIN32 )
			DWORD length = sizeof( computername ) - 1;
			if ( !GetComputerName( computername, &length ) )
			{
				Q_strncpy( computername, "???", sizeof( computername )  );
			}
#else
			if ( gethostname( computername, sizeof(computername) ) == -1 )
			{
				Q_strncpy( computername, "Linux????", sizeof( computername ) );
			}
			computername[sizeof(computername)-1] = '\0';
#endif
			encrypted.WriteString( computername );
		}

		{
			char username[ 64 ];
			Q_memset( username, 0, sizeof( username ) );
#if defined ( _WIN32 )
			DWORD length = sizeof( username ) - 1;
			if ( !GetUserName( username, &length ) )
			{
				Q_strncpy( username, "???", sizeof( username )  );
			}
#else
			struct passwd *pass = getpwuid( getuid() );
			if ( pass )
			{
				Q_strncpy( username, pass->pw_name, sizeof( username ) );
			}
			else
			{
				Q_strncpy( username, "LinuxUser??", sizeof( username ) );
			}
			username[sizeof(username)-1] = '\0';
#endif
			encrypted.WriteString( username );
		}

		char gamedir[ 64 ];
		Q_FileBase( com_gamedir, gamedir, sizeof( gamedir ) );
		encrypted.WriteString( gamedir );

		unsigned int uBuildNumber = build_number();

		encrypted.WriteLong( (int)uBuildNumber );

		// WRite timestamp of engine
		encrypted.WriteFloat( (float)realtime );

		encrypted.WriteByte( msgtype );
		if ( mapname != NULL )
		{
			encrypted.WriteString( mapname );
		}

		int isDebugUser = ( Sys_IsDebuggerPresent() || CommandLine()->FindParm( "-allowdebug" ) ) ? 1 : 0;

		encrypted.WriteByte( isDebugUser );

		while ( encrypted.GetNumBytesWritten() % 8 )
		{
			encrypted.WriteByte( 0 );
		}

		EncryptBuffer( cipher, (unsigned char *)encrypted.GetData(), encrypted.GetNumBytesWritten() );

		buf.WriteShort( (int)encrypted.GetNumBytesWritten() );
		buf.WriteBytes( (unsigned char *)encrypted.GetData(), encrypted.GetNumBytesWritten() );
	}
Example #29
0
bool LLInventoryItem::fromLLSD(LLSD& sd)
{
	mInventoryType = LLInventoryType::IT_NONE;
	mAssetUUID.setNull();
	std::string w;

	w = INV_ITEM_ID_LABEL;
	if (sd.has(w))
	{
		mUUID = sd[w];
	}
	w = INV_PARENT_ID_LABEL;
	if (sd.has(w))
	{
		mParentUUID = sd[w];
	}
	w = INV_PERMISSIONS_LABEL;
	if (sd.has(w))
	{
		mPermissions = ll_permissions_from_sd(sd[w]);
	}
	w = INV_SALE_INFO_LABEL;
	if (sd.has(w))
	{
		// Sale info used to contain next owner perm. It is now in
		// the permissions. Thus, we read that out, and fix legacy
		// objects. It's possible this op would fail, but it
		// should pick up the vast majority of the tasks.
		BOOL has_perm_mask = FALSE;
		U32 perm_mask = 0;
		if (!mSaleInfo.fromLLSD(sd[w], has_perm_mask, perm_mask))
		{
			goto fail;
		}
		if (has_perm_mask)
		{
			if(perm_mask == PERM_NONE)
			{
				perm_mask = mPermissions.getMaskOwner();
			}
			// fair use fix.
			if(!(perm_mask & PERM_COPY))
			{
				perm_mask |= PERM_TRANSFER;
			}
			mPermissions.setMaskNext(perm_mask);
		}
	}
	w = INV_SHADOW_ID_LABEL;
	if (sd.has(w))
	{
		mAssetUUID = sd[w];
		LLXORCipher cipher(MAGIC_ID.mData, UUID_BYTES);
		cipher.decrypt(mAssetUUID.mData, UUID_BYTES);
	}
	w = INV_ASSET_ID_LABEL;
	if (sd.has(w))
	{
		mAssetUUID = sd[w];
	}
	w = INV_ASSET_TYPE_LABEL;
	if (sd.has(w))
	{
		if (sd[w].isString())
		{
			mType = LLAssetType::lookup(sd[w].asString().c_str());
		}
		else if (sd[w].isInteger())
		{
			S8 type = (U8)sd[w].asInteger();
			mType = static_cast<LLAssetType::EType>(type);
		}
	}
	w = INV_INVENTORY_TYPE_LABEL;
	if (sd.has(w))
	{
		if (sd[w].isString())
		{
			mInventoryType = LLInventoryType::lookup(sd[w].asString().c_str());
		}
		else if (sd[w].isInteger())
		{
			S8 type = (U8)sd[w].asInteger();
			mInventoryType = static_cast<LLInventoryType::EType>(type);
		}
	}
	w = INV_FLAGS_LABEL;
	if (sd.has(w))
	{
		if (sd[w].isBinary())
		{
			mFlags = ll_U32_from_sd(sd[w]);
		}
		else if(sd[w].isInteger())
		{
			mFlags = sd[w].asInteger();
		}
	}
	w = INV_NAME_LABEL;
	if (sd.has(w))
	{
		mName = sd[w].asString();
		LLStringUtil::replaceNonstandardASCII(mName, ' ');
		LLStringUtil::replaceChar(mName, '|', ' ');
	}
	w = INV_DESC_LABEL;
	if (sd.has(w))
	{
		mDescription = sd[w].asString();
		LLStringUtil::replaceNonstandardASCII(mDescription, ' ');
	}
	w = INV_CREATION_DATE_LABEL;
	if (sd.has(w))
	{
		mCreationDate = sd[w].asInteger();
	}

	// Need to convert 1.0 simstate files to a useful inventory type
	// and potentially deal with bad inventory tyes eg, a landmark
	// marked as a texture.
	if((LLInventoryType::IT_NONE == mInventoryType)
	   || !inventory_and_asset_types_match(mInventoryType, mType))
	{
		lldebugs << "Resetting inventory type for " << mUUID << llendl;
		mInventoryType = LLInventoryType::defaultForAssetType(mType);
	}

	return true;
fail:
	return false;

}
Example #30
0
/*
 * Algorithm independent ECB functions.
 */
int
ecb_cipher_contiguous_blocks(ecb_ctx_t *ctx, char *data, size_t length,
    crypto_data_t *out, size_t block_size,
    int (*cipher)(const void *ks, const uint8_t *pt, uint8_t *ct))
{
	size_t remainder = length;
	size_t need;
	uint8_t *datap = (uint8_t *)data;
	uint8_t *blockp;
	uint8_t *lastp;

	if (length + ctx->ecb_remainder_len < block_size) {
		/* accumulate bytes here and return */
		bcopy(datap,
		    (uint8_t *)ctx->ecb_remainder + ctx->ecb_remainder_len,
		    length);
		ctx->ecb_remainder_len += length;
		ctx->ecb_copy_to = datap;
		return (CRYPTO_SUCCESS);
	}

	lastp = (uint8_t *)ctx->ecb_iv;

	do {
		/* Unprocessed data from last call. */
		if (ctx->ecb_remainder_len > 0) {
			need = block_size - ctx->ecb_remainder_len;

			if (need > remainder)
				return (CRYPTO_DATA_LEN_RANGE);

			bcopy(datap, &((uint8_t *)ctx->ecb_remainder)
			    [ctx->ecb_remainder_len], need);

			blockp = (uint8_t *)ctx->ecb_remainder;
		} else {
			blockp = datap;
		}

		if (out == NULL) {
			cipher(ctx->ecb_keysched, blockp, blockp);

			ctx->ecb_lastp = blockp;
			lastp = blockp;

			if (ctx->ecb_remainder_len > 0) {
				bcopy(blockp, ctx->ecb_copy_to,
				    ctx->ecb_remainder_len);
				bcopy(blockp + ctx->ecb_remainder_len, datap,
				    need);
			}
		} else {
			cipher(ctx->ecb_keysched, blockp, lastp);
			(void) crypto_put_output_data(lastp, out, block_size);
			/* update offset */
			out->cd_offset += block_size;
		}

		/* Update pointer to next block of data to be processed. */
		if (ctx->ecb_remainder_len != 0) {
			datap += need;
			ctx->ecb_remainder_len = 0;
		} else {
			datap += block_size;
		}

		remainder = (size_t)&data[length] - (size_t)datap;

		/* Incomplete last block. */
		if (remainder > 0 && remainder < block_size) {
			bcopy(datap, ctx->ecb_remainder, remainder);
			ctx->ecb_remainder_len = remainder;
			ctx->ecb_copy_to = datap;
			goto out;
		}
		ctx->ecb_copy_to = NULL;

	} while (remainder > 0);

out:
	return (CRYPTO_SUCCESS);
}