Пример #1
0
void aesEncrypt(std::string filename, std::string key) {
	if (!(key.length() == 16 || key.length() == 24 || key.length() == 32)) {
		std::cout << "Key is not a valid length\n";
		return;
	}

	auto RoundKeys = rijindaelKeySchedule(key); //todo fix 192bit and 256bit keys in schedule.

	std::ifstream input(filename, std::ios::binary);

	if (input.fail()) {
		std::cerr << "Failed to open file\n";
		return;
	}

	std::vector<BYTE> plaintext((std::istreambuf_iterator<char>(input)), std::istreambuf_iterator<char>());
	input.close();

	addPadding(plaintext);
	std::ofstream out(filename + "_aes_enc", std::ios::binary);

	for (auto it = plaintext.begin(); it != plaintext.end(); it += 16) {
		StateBlock state(it);
		cipher(state, RoundKeys);
		state.writeToFile(out);
	}

	out.close();
}
Пример #2
0
/*
    Cracks the rail cipher by just brute-forcing the key.
    There's no statistics involved in this cipher, so its just a matter
    of rearranging the ciphertext to reveal the plaintext.
*/
std::string crackRailCipher(const std::string& ciphertext)
{
    int maxKeyLength = 40;
    if (maxKeyLength >= ciphertext.size())
        maxKeyLength = ciphertext.size();

    for (int keyLength = 2; keyLength < maxKeyLength; keyLength++)
    {
        std::string plaintext(ciphertext);

        int cipherIndex = 0;
        for (int offset = 0; offset < keyLength; offset++)
        {
            int diff = (keyLength - 1) * 2 - offset * 2;

            if (offset == keyLength - 1)
                diff = (keyLength - 1) * 2;

            for (int j = offset; j < ciphertext.size(); j += diff)
            {
                plaintext[j] = ciphertext[cipherIndex];
                cipherIndex++;
            }
        }

        std::cout << keyLength << ": " << plaintext << std::endl;
    }

    return "";
}
Пример #3
0
void InsetSpecialChar::forOutliner(docstring & os, size_t const,
								   bool const) const
{
	odocstringstream ods;
	plaintext(ods, OutputParams(0));
	os += ods.str();
}
Пример #4
0
bool CryptoSystemValidate(PK_Decryptor &priv, PK_Encryptor &pub, bool thorough = false)
{
	bool pass = true, fail;

	fail = !pub.GetMaterial().Validate(GlobalRNG(), thorough ? 3 : 2) || !priv.GetMaterial().Validate(GlobalRNG(), thorough ? 3 : 2);
	pass = pass && !fail;

	cout << (fail ? "FAILED    " : "passed    ");
	cout << "cryptosystem key validation\n";

	static const byte message[] = "test message";
	const int messageLen = COUNTOF(message);

	SecByteBlock ciphertext(priv.CiphertextLength(messageLen));
	SecByteBlock plaintext(priv.MaxPlaintextLength(ciphertext.size()));

	pub.Encrypt(GlobalRNG(), message, messageLen, ciphertext);
	fail = priv.Decrypt(GlobalRNG(), ciphertext, priv.CiphertextLength(messageLen), plaintext) != DecodingResult(messageLen);
	fail = fail || !VerifyBufsEqual(message, plaintext, messageLen);
	pass = pass && !fail;

	cout << (fail ? "FAILED    " : "passed    ");
	cout << "encryption and decryption\n";

	return pass;
}
Пример #5
0
 QByteArray decode(const QByteArray& ciphertext, char mask_init, int, char mask_step, int remix_step, int len)
 {
     int size = ciphertext.size();
     QByteArray plaintext(qMin(len, size) & ~1, '\0');
     char mask = mask_init;
     int read_cursor = 0;
     int write_cursor = 0;
     for (int j = plaintext.size(); j > 0; j -= remix_step)
     {
         if (remix_step > j)
             remix_step = j;
         int write_cursor_copy = write_cursor + remix_step;
         write_cursor = write_cursor_copy - 1;
         for (int i = ((remix_step + 1) >> 1) ; i > 0; --i)
         {
             plaintext[write_cursor] = ciphertext[read_cursor] ^ mask;
             mask += mask_step;
             ++read_cursor;
             write_cursor -= 2;
         }
         write_cursor = write_cursor_copy - 2;
         for (int i = (remix_step >> 1) ; i > 0; --i)
         {
             plaintext[write_cursor] = ciphertext[read_cursor] ^ mask;
             mask += mask_step;
             ++read_cursor;
             write_cursor -= 2;
         }
         write_cursor = write_cursor_copy;
     }
     plaintext.append(ciphertext.mid(plaintext.size()));
     return plaintext;
 }
Пример #6
0
/*!
  \internal
  Generates the OAuth signature.
  \see http://oauth.net/core/1.0a/#signing_process
*/
QString Token::generateSignature(const QUrl& requestUrl, const QMultiMap<QString, QString>& requestParameters, HttpMethod method) const
{
	QString key = encode(d->consumerSecret) + "&" + encode(d->oauthTokenSecret);
	QString baseString;

	switch (method) {
	case HttpGet:    baseString = "GET&";    break;
	case HttpPost:   baseString = "POST&";   break;
	case HttpPut:    baseString = "PUT&";    break;
	case HttpDelete: baseString = "DELETE&"; break;
	case HttpHead:   baseString = "HEAD&";   break;
	}

	baseString += encode(requestUrl.toString(QUrl::RemoveQuery)) + "&";

	// encode and concatenate the parameters into a string
	QStringList params;
	QMap<QString, QString>::const_iterator p = requestParameters.constBegin();
	while (p != requestParameters.constEnd()) {
		params << QString("%1=%2").arg(encode(p.key())).arg(encode(p.value()));
		++p;
	}
	qSort(params);

	baseString += encode(params.join("&"));

	// Ok, we have the normalized base string and the key, calculate the HMAC-SHA1 signature
    if(tokenService() == "dbox")
        return plaintext(baseString, key);
    else
        return hmac_sha1(baseString, key);
}
Пример #7
0
int crypto_aead_encrypt(
    unsigned char *c,unsigned long long *clen,
    const unsigned char *m,unsigned long long mlen,
    const unsigned char *ad,unsigned long long adlen,
    const unsigned char *nsec,
    const unsigned char *npub,
    const unsigned char *k
    )
{
    string K((const char *)k, (size_t)CRYPTO_KEYBYTES);
    string N((const char *)npub, (size_t)CRYPTO_NPUBBYTES);
    stringstream dummy;
    stringstream AD(string((const char *)ad, adlen));
    stringstream plaintext(string((const char *)m, mlen));
    stringstream ciphertext;
    stringstream tag;

    LakeKeyak instance;
    instance.StartEngine(K, N, false, dummy, false, false);
    instance.Wrap(plaintext, ciphertext, AD, tag, false, false);
    memcpy(c, ciphertext.str().data(), ciphertext.str().size());
    *clen = ciphertext.str().size();
    memcpy(c+ciphertext.str().size(), tag.str().data(), tag.str().size());
    *clen += tag.str().size();

    return 0;
}
Пример #8
0
bool CryptoHash::Digest(
    const HashType hashType,
    const String& data,
    OTData& digest)
{
    OTData plaintext(data.Get(), data.GetLength());

    return Digest(hashType, plaintext, digest);
}
Пример #9
0
void InsetSpecialChar::toString(odocstream & os) const
{
	switch (kind_) {
	case LIGATURE_BREAK:
		// Do not output ZERO WIDTH NON JOINER here
		// Spell checker would choke on it.
		return;
	default:
		break;
	}
	odocstringstream ods;
	plaintext(ods, OutputParams(0));
	os << ods.str();
}
Пример #10
0
QByteArray
NvPairingManager::decrypt(QByteArray ciphertext, AES_KEY* key)
{
    QByteArray plaintext(ciphertext.size(), 0);

    for (int i = 0; i < plaintext.size(); i += 16)
    {
        AES_decrypt(reinterpret_cast<unsigned char*>(&ciphertext.data()[i]),
                    reinterpret_cast<unsigned char*>(&plaintext.data()[i]),
                    key);
    }

    return plaintext;
}
Пример #11
0
	void endecryptTest()
	{
		const unsigned int bitLength = 128;
		KeyPair pair = RSA::makeKeyPair(bitLength);
		
		PublicKey pubKey = pair.getPublicKey();
		PrivateKey privKey = pair.getPrivateKey();

		RSA cipher(pubKey, privKey);
		MPInteger plaintext("12fbff45836b");
		MPInteger ciphertext = cipher.encrypt(plaintext);
		MPInteger decrypttext = cipher.decrypt(ciphertext);

		CPPUNIT_ASSERT(plaintext == decrypttext);
	}
Пример #12
0
void BenchMarkEncryption(const char *name, PK_Encryptor &key, double timeTotal, bool pc=false)
{
	unsigned int len = 16;
	LC_RNG rng(time(NULL));
	SecByteBlock plaintext(len), ciphertext(key.CipherTextLength(len));
	rng.GetBlock(plaintext, len);

	clock_t start = clock();
	unsigned int i;
	double timeTaken;
	for (timeTaken=(double)0, i=0; timeTaken < timeTotal; timeTaken = double(clock() - start) / CLOCK_TICKS_PER_SECOND, i++)
		key.Encrypt(rng, plaintext, len, ciphertext);

	OutputResultOperations(name, "Encryption", pc, i, timeTaken);
}
Пример #13
0
void BenchMarkDecryption(const char *name, PK_Decryptor &priv, PK_Encryptor &pub, double timeTotal)
{
	unsigned int len = 16;
	SecByteBlock ciphertext(pub.CiphertextLength(len));
	SecByteBlock plaintext(pub.MaxPlaintextLength(ciphertext.size()));
	GlobalRNG().GenerateBlock(plaintext, len);
	pub.Encrypt(GlobalRNG(), plaintext, len, ciphertext);

	const clock_t start = clock();
	unsigned int i;
	double timeTaken;
	for (timeTaken=(double)0, i=0; timeTaken < timeTotal; timeTaken = double(clock() - start) / CLOCK_TICKS_PER_SECOND, i++)
		priv.Decrypt(GlobalRNG(), ciphertext, ciphertext.size(), plaintext);

	OutputResultOperations(name, "Decryption", false, i, timeTaken);
}
Пример #14
0
bool CryptoSystemValidate(PK_Decryptor &priv, PK_Encryptor &pub)
{
	LC_RNG rng(9375);
	const byte *message = (byte *)"test message";
	const int messageLen = 12;
	SecByteBlock ciphertext(priv.CipherTextLength(messageLen));
	SecByteBlock plaintext(priv.MaxPlainTextLength(ciphertext.size));
	bool pass = true, fail;

	pub.Encrypt(rng, message, messageLen, ciphertext);
	fail = (messageLen!=priv.Decrypt(ciphertext, priv.CipherTextLength(messageLen), plaintext));
	fail = fail || memcmp(message, plaintext, messageLen);
	pass = pass && !fail;

	cout << (fail ? "FAILED    " : "passed    ");
	cout << "encryption and decryption\n";

	return pass;
}
Пример #15
0
bool Sekrit::GetPlaintext(Plaintext& data) const
{
	if( !m_impl->data.empty() )
	{
		char hash[sha256::hashbits/8];
		Plaintext plaintext(DoDecrypt());
		ComputeHash(hash, plaintext, m_impl->header.iv);

		if( 0 == memcmp(hash, m_impl->header.hash, sizeof(hash)) )
		{
			data.swap(plaintext);
			return true;
		} else
			return false;
	} else
	{
		data.clear();
		return true;
	}
}
Пример #16
0
void BenchMarkEncryption(const char *name, PK_Encryptor &key, double timeTotal, bool pc=false)
{
	unsigned int len = 16;
	SecByteBlock plaintext(len), ciphertext(key.CiphertextLength(len));
	GlobalRNG().GenerateBlock(plaintext, len);

	const clock_t start = clock();
	unsigned int i;
	double timeTaken;
	for (timeTaken=(double)0, i=0; timeTaken < timeTotal; timeTaken = double(clock() - start) / CLOCK_TICKS_PER_SECOND, i++)
		key.Encrypt(GlobalRNG(), plaintext, len, ciphertext);

	OutputResultOperations(name, "Encryption", pc, i, timeTaken);

	if (!pc && key.GetMaterial().SupportsPrecomputation())
	{
		key.AccessMaterial().Precompute(16);
		BenchMarkEncryption(name, key, timeTotal, true);
	}
}
Пример #17
0
bool CryptoHash::Digest(
    const uint32_t type,
    const std::string& data,
    std::string& encodedDigest)
{
    OTData plaintext(data.c_str(), data.size());
    OTData result;

    bool success = Digest(
        static_cast<CryptoHash::HashType>(type),
        plaintext,
        result);

    if (success) {
        encodedDigest.assign(
            App::Me().Crypto().Util().Base58CheckEncode(result).Get());
    }

    return success;
}
Пример #18
0
	unsigned int Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
	{
		FILTER_BEGIN;
		m_plaintextQueue.Put(inString, length);

		if (messageEnd)
		{
			{
			unsigned int plaintextLength = m_plaintextQueue.CurrentSize();
			unsigned int ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);

			SecByteBlock plaintext(plaintextLength);
			m_plaintextQueue.Get(plaintext, plaintextLength);
			m_ciphertext.resize(ciphertextLength);
			m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
			}
			
			FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
		}
		FILTER_END_NO_MESSAGE_END;
	}
Пример #19
0
		bool IsolatedMessageEnd(bool blocking)
		{
			switch (m_continueAt)
			{
			case 0:
				{
				unsigned int plaintextLength = m_inQueue.CurrentSize();
				m_ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);

				SecByteBlock plaintext(plaintextLength);
				m_inQueue.Get(plaintext, plaintextLength);
				m_ciphertext.resize(m_ciphertextLength);
				m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext);
				}

			case 1:
				if (!Output(1, m_ciphertext, m_ciphertextLength, 0, blocking))
					return false;
			};
			return true;
		}
Пример #20
0
	size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
	{
		FILTER_BEGIN;
		m_plaintextQueue.Put(inString, length);

		if (messageEnd)
		{
			{
			size_t plaintextLength;
			if (!SafeConvert(m_plaintextQueue.CurrentSize(), plaintextLength))
				throw InvalidArgument("PK_DefaultEncryptionFilter: plaintext too long");
			size_t ciphertextLength = m_encryptor.CiphertextLength(plaintextLength);

			SecByteBlock plaintext(plaintextLength);
			m_plaintextQueue.Get(plaintext, plaintextLength);
			m_ciphertext.resize(ciphertextLength);
			m_encryptor.Encrypt(m_rng, plaintext, plaintextLength, m_ciphertext, m_parameters);
			}

			FILTER_OUTPUT(1, m_ciphertext, m_ciphertext.size(), messageEnd);
		}
		FILTER_END_NO_MESSAGE_END;
	}
Пример #21
0
void InsetCitation::toString(odocstream & os) const
{
	plaintext(os, OutputParams(0));
}
Пример #22
0
std::vector<uint8_t> yaz0_decompress(std::vector<uint8_t> ciphertext) {
    std::string magic(ciphertext.begin(), ciphertext.begin() + 4);

    if (magic != "Yaz0" && magic != "Yaz1") {
        throw X::Yaz0::Decompress("Not actually a compressed file.");
    }

    // we don't really need to use the size param, since we're using vectors,
    // but it does make for a cooler-looking implementation if we have a
    // pre-sized vector over using push_back.

    uint32_t dsize = be_u32(ciphertext.begin() + 4);

    std::vector<uint8_t> plaintext(dsize, 0);

    // index pointers, quite important
    auto cipher_R_pnt = ciphertext.begin() + 16; // last 8 bytes of header unused
    auto plain_R_pnt  = plaintext.begin();
    auto plain_W_pnt  = plaintext.begin();

    while (cipher_R_pnt != ciphertext.end() && plain_W_pnt != plaintext.end()) {
        uint8_t opset = *cipher_R_pnt++;

        // the weird choice for comparison is because an unsigned int see 0 - 1
        // == -1 as a positive number, of course, so the standard 0 <= i is
        // useless.
        for (uint8_t i = 7; i <= 7; i--) {
            // each iteration, if we're now at the end of the cipher stream (or
            // write buffer), we'll just stop; it's permissible (AFAIK) to not
            // pad your data to use all of the last opset.
            if (cipher_R_pnt == ciphertext.end() || plain_W_pnt == plaintext.end()) {
                break;
            }

            if (opset & (1 << i)) { // bit on: copy byte
                *plain_W_pnt++ = *cipher_R_pnt++;
            } else { // bit off: run data
                // readcnt is 16-bit in the event that we get a size of
                // e.g. 0xFF for it; then 0xFF + 0x12 = 0x111
                uint16_t readcnt = (*cipher_R_pnt) >> 4;
                uint16_t backamt = (*cipher_R_pnt++) & 0x0F;
                backamt = (backamt << 8) | *cipher_R_pnt++;
                backamt++; // plus 1 to stated back amount

                if (readcnt == 0) {
                    readcnt = *cipher_R_pnt++ + 0x10;
                }

                readcnt += 0x2;

                // now to set up the other read pointer
                plain_R_pnt = plain_W_pnt - backamt;

                // and now to copy! (the line in this loop is the
                // "cooler-looking implementation" mentioned earlier)
                for (uint16_t i = 0; i < readcnt; i++) {
                    *plain_W_pnt++ = *plain_R_pnt++;
                }
            }
        }
    }

    // now to do a quick check in the event that the write buffer got filled out
    // before we read the whole cipher buffer
    while (cipher_R_pnt != ciphertext.end()) {
        if (*cipher_R_pnt != 0) {
            std::cerr << "Warning: Not likely to be padding found after write buffer filled.\n";
        }

        cipher_R_pnt++;
    }

    if (plain_W_pnt != plaintext.end()) {
        throw X::Yaz0::Decompress("Some kind of problem with decompressing, didn't fill up plaintext exactly.");
    }

    return plaintext;
}
Пример #23
0
void InsetHyperlink::toString(odocstream & os) const
{
	plaintext(os, OutputParams(0));
}
Пример #24
0
int InsetFormulaMacro::docbook(ostream & os,
			       OutputParams const & runparams) const
{
	return plaintext(os, runparams);
}
Пример #25
0
bool OTEnvelope::Seal(const OTAsymmetricKey & RecipPubKey, const OTString & theContents)
{
	bool retval = false;
    
	EVP_CIPHER_CTX	ctx;
    
	unsigned char	buffer[4096];
    unsigned char	buffer_out[4096 + EVP_MAX_IV_LENGTH];
    unsigned char	iv[EVP_MAX_IV_LENGTH];
    
	size_t			len = 0;
    int				len_out = 0;

    unsigned char *	ek = NULL;
    int				eklen = 0;
    uint32_t		eklen_n = 0;
	
	
	memset(buffer, 0, 4096);
	memset(buffer_out, 0, 4096 + EVP_MAX_IV_LENGTH);
	memset(iv, 0, EVP_MAX_IV_LENGTH);

	
	OTAsymmetricKey &	publicKey	= (OTAsymmetricKey &)RecipPubKey;
	EVP_PKEY *			pkey		= (EVP_PKEY *)publicKey.GetKey();
	
	if (NULL == pkey)
	{
		OTLog::Error("Null public key in OTEnvelope::Seal\n");
		return false;
	}
	
	// This is where the envelope final contents will be placed.
	m_dataContents.Release();
	
	
	EVP_CIPHER_CTX_init(&ctx);
    ek = (unsigned char*)malloc(EVP_PKEY_size(pkey));
	
	OT_ASSERT(NULL != ek);
	
	memset(ek, 0, EVP_PKEY_size(pkey));
	
    if (!EVP_SealInit(&ctx, EVP_aes_128_cbc(), &ek, &eklen, iv, &pkey, 1))
    {
        OTLog::Error("EVP_SealInit: failed.\n");
		free(ek); ek = NULL;
		return false;
    }
	
    // First we write out the encrypted key length, then the encrypted key,
	// then the iv (the IV length is fixed by the cipher we have chosen).
	
    eklen_n = htonl(eklen);
	
	OTData dataEKSize(&eklen_n, sizeof(eklen_n)); // Encrypted Key size. (EK). Bytes are in network order.
	OTData dataEK(ek, eklen); // Encrypted Key
	OTData dataIV(iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc())); // Initialization Vector
	
	// Concatenate (to the envelope result buffer) the three pieces of final data we have so far.
	m_dataContents += dataEKSize;
	m_dataContents += dataEK;
	m_dataContents += dataIV;
	
	// Next we put the plaintext into a data object so we can process it.
	OTData plaintext((const void*)theContents.Get(), theContents.GetLength()+1); // +1 for null terminator
	
    // Now we process the input and write the encrypted data to the
	// output.
	
    while (0 < (len = plaintext.OTfread((char*)buffer, sizeof(buffer))))
    {
        if (!EVP_SealUpdate(&ctx, buffer_out, &len_out, buffer, len))
        {
            OTLog::Error("EVP_SealUpdate: failed.\n");
			free(ek); ek = NULL;
			return false;
        }
		
		OTData dataSealUpdate(buffer_out, len_out);
		m_dataContents += dataSealUpdate;
	}
	
    if (!EVP_SealFinal(&ctx, buffer_out, &len_out))
    {
        OTLog::Error("EVP_SealFinal: failed.\n");
		free(ek); ek = NULL;
		return false;
    }
	
	OTData dataSealFinal(buffer_out, len_out);
	m_dataContents += dataSealFinal;
	
	retval = true;
	
    free(ek); ek = NULL;
	
    return retval;
}
Пример #26
0
void InsetRef::toString(odocstream & os) const
{
	odocstringstream ods;
	plaintext(ods, OutputParams(0));
	os << ods.str();
}