コード例 #1
0
ファイル: aes.cpp プロジェクト: EricPlusPlus/CPlusPlus-Notes
void aesDecrypt(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);

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

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

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

	std::ofstream out(filename + "_decrypted.txt", std::ios::binary);

	for (size_t i = 0; i < ciphertext.size(); i += 16) {
		StateBlock state(ciphertext.begin() + i);
		invCipher(state, RoundKeys);
		state.writeToFile(out);
	}

	out.close();
}
コード例 #2
0
ファイル: cryptlib.cpp プロジェクト: 13971643458/qtum
	size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking)
	{
		FILTER_BEGIN;
		m_ciphertextQueue.Put(inString, length);

		if (messageEnd)
		{
			{
			size_t ciphertextLength;
			if (!SafeConvert(m_ciphertextQueue.CurrentSize(), ciphertextLength))
				throw InvalidArgument("PK_DefaultDecryptionFilter: ciphertext too long");
			size_t maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);

			SecByteBlock ciphertext(ciphertextLength);
			m_ciphertextQueue.Get(ciphertext, ciphertextLength);
			m_plaintext.resize(maxPlaintextLength);
			m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
			if (!m_result.isValidCoding)
				throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
			}

			FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
		}
		FILTER_END_NO_MESSAGE_END;
	}
コード例 #3
0
ファイル: validat2.cpp プロジェクト: hovatterz/cryptopp
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;
}
コード例 #4
0
  QByteArray CppRsaPublicKeyImpl::Encrypt(const QByteArray &data) const
  {
    if(!IsValid()) {
      return QByteArray();
    }

    RSAES<OAEP<SHA> >::Encryptor encryptor(*m_public_key);
    int clength = ((data.size() / AES::BLOCKSIZE) + 1) * AES::BLOCKSIZE;
    int data_start = encryptor.FixedCiphertextLength() + AES::BLOCKSIZE;
    QByteArray ciphertext(data_start + clength, 0);

    CryptoRandom rand;
    QByteArray skey(AES::BLOCKSIZE, 0);
    rand.GenerateBlock(skey);

    QByteArray iv(AES::BLOCKSIZE, 0);
    rand.GenerateBlock(iv);
    ciphertext.replace(encryptor.FixedCiphertextLength(), iv.size(), iv);

    CBC_Mode<AES>::Encryption enc;
    enc.SetKeyWithIV(reinterpret_cast<byte *>(skey.data()), skey.size(),
        reinterpret_cast<byte *>(iv.data()));

    StringSource(reinterpret_cast<const byte *>(data.data()), data.size(), true,
        new StreamTransformationFilter(enc,
          new ArraySink(reinterpret_cast<byte *>(ciphertext.data() + data_start), clength)));

    encryptor.Encrypt(GetCppRandom(rand),
        reinterpret_cast<const byte *>(skey.data()),
        skey.size(), reinterpret_cast<byte *>(ciphertext.data()));

    return ciphertext;
  }
コード例 #5
0
ファイル: encrypt.cpp プロジェクト: 0x64616E69656C/supercop
int crypto_aead_decrypt(
    unsigned char *m,unsigned long long *mlen,
    unsigned char *nsec,
    const unsigned char *c,unsigned long long clen,
    const unsigned char *ad,unsigned long long adlen,
    const unsigned char *npub,
    const unsigned char *k
    )
{
    if (clen < CRYPTO_ABYTES)
        return -1;

    string K((const char *)k, CRYPTO_KEYBYTES);
    string N((const char *)npub, CRYPTO_NPUBBYTES);
    stringstream dummy;
    stringstream AD(string((const char *)ad, adlen));
    stringstream plaintext;
    stringstream ciphertext(string((const char *)c, clen-CRYPTO_ABYTES));
    stringstream tag(string((const char *)c+clen-CRYPTO_ABYTES, CRYPTO_ABYTES));

    LakeKeyak instance;
    instance.StartEngine(K, N, false, dummy, true, false);
    bool result = instance.Wrap(ciphertext, plaintext, AD, tag, true, false);

    if (result) {
        memcpy(m, plaintext.str().data(), plaintext.str().size());
        *mlen = plaintext.str().size();
        return 0;
    }
   else
       return -1;
}
コード例 #6
0
ファイル: data_message.cpp プロジェクト: reaper/libfscp
size_t data_message::get_cleartext(void* buf, size_t buf_len, session_number_type session_number, const void* enc_key, size_t enc_key_len) const
{
    assert(enc_key);

    if (buf)
    {
        cryptoplus::cipher::cipher_algorithm cipher_algorithm(CIPHER_ALGORITHM);

        const std::vector<uint8_t> iv = compute_initialization_vector<uint8_t>(session_number, sequence_number(), enc_key, enc_key_len);

        cryptoplus::cipher::cipher_context cipher_context;
        cipher_context.initialize(cipher_algorithm, cryptoplus::cipher::cipher_context::decrypt, enc_key, enc_key_len, &iv[0], iv.size());
        cipher_context.set_padding(false);
        size_t cnt = cipher_context.update(buf, buf_len, ciphertext(), ciphertext_size());
        cnt += cipher_context.finalize(static_cast<uint8_t*>(buf) + cnt, buf_len - cnt);

        try
        {
            cnt = cipher_context.verify_iso_10126_padding(buf, cnt);
        }
        catch (std::logic_error&)
        {
            throw std::runtime_error("Incorrect padding in the RSA ciphertext");
        }

        return cnt;
    }
    else
    {
        return ciphertext_size();
    }
}
コード例 #7
0
QByteArray
NvPairingManager::encrypt(QByteArray plaintext, AES_KEY* key)
{
    QByteArray ciphertext(plaintext.size(), 0);

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

    return ciphertext;
}
コード例 #8
0
QString QgsAuthCrypto::encryptdecrypt( QString passstr,
                                       QString cipheriv,
                                       QString textstr,
                                       bool encrypt )
{
  QString outtxt = QString();
  if ( QgsAuthCrypto::isDisabled() )
    return outtxt;

  QCA::InitializationVector iv( QCA::hexToArray( cipheriv ) );

  QCA::SymmetricKey key( QCA::SecureArray( QByteArray( passstr.toUtf8().constData() ) ) );

  if ( encrypt )
  {
    QCA::Cipher cipher = QCA::Cipher( CIPHER_TYPE, CIPHER_MODE, CIPHER_PADDING,
                                      QCA::Encode, key, iv,
                                      CIPHER_PROVIDER );

    QCA::SecureArray securedata( textstr.toUtf8() );
    QCA::SecureArray encrypteddata( cipher.process( securedata ) );
    if ( !cipher.ok() )
    {
      qDebug( "Encryption failed!" );
      return outtxt;
    }
    outtxt = QCA::arrayToHex( encrypteddata.toByteArray() );
    // qDebug( "Encrypted hex: %s", qPrintable( outtxt ) );
  }
  else
  {
    QCA::Cipher cipher = QCA::Cipher( CIPHER_TYPE, CIPHER_MODE, CIPHER_PADDING,
                                      QCA::Decode, key, iv,
                                      CIPHER_PROVIDER );

    QCA::SecureArray ciphertext( QCA::hexToArray( textstr ) );
    QCA::SecureArray decrypteddata( cipher.process( ciphertext ) );
    if ( !cipher.ok() )
    {
      qDebug( "Decryption failed!" );
      return outtxt;
    }

    outtxt = QString( decrypteddata.toByteArray() );
    // qDebug( "Decrypted text %s", qPrintable( outtxt ) ); // DO NOT LEAVE THIS LINE UNCOMMENTED
  }

  return outtxt;
}
コード例 #9
0
ファイル: bench.cpp プロジェクト: freegroup/DigitalSimulator
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);
}
コード例 #10
0
ファイル: bench2.cpp プロジェクト: Andy-Amoy/cryptopp
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);
}
コード例 #11
0
ファイル: validat2.cpp プロジェクト: mentat/nnim
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;
}
コード例 #12
0
ファイル: bench2.cpp プロジェクト: Andy-Amoy/cryptopp
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);
	}
}
コード例 #13
0
ファイル: cryptlib.cpp プロジェクト: LjApps/eMule-VeryCD
	unsigned int Put2(const byte *inString, unsigned int length, int messageEnd, bool blocking)
	{
		FILTER_BEGIN;
		m_ciphertextQueue.Put(inString, length);

		if (messageEnd)
		{
			{
			unsigned int ciphertextLength = m_ciphertextQueue.CurrentSize();
			unsigned int maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);

			SecByteBlock ciphertext(ciphertextLength);
			m_ciphertextQueue.Get(ciphertext, ciphertextLength);
			m_plaintext.resize(maxPlaintextLength);
			m_result = m_decryptor.Decrypt(m_rng, ciphertext, ciphertextLength, m_plaintext, m_parameters);
			if (!m_result.isValidCoding)
				throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
			}

			FILTER_OUTPUT(1, m_plaintext, m_result.messageLength, messageEnd);
		}
		FILTER_END_NO_MESSAGE_END;
	}
コード例 #14
0
ファイル: cryptlib.cpp プロジェクト: randombit/hacrypto
		bool IsolatedMessageEnd(bool blocking)
		{
			switch (m_continueAt)
			{
			case 0:
				{
				unsigned int ciphertextLength = m_inQueue.CurrentSize();
				unsigned int maxPlaintextLength = m_decryptor.MaxPlaintextLength(ciphertextLength);

				SecByteBlock ciphertext(ciphertextLength);
				m_inQueue.Get(ciphertext, ciphertextLength);
				m_plaintext.resize(maxPlaintextLength);
				m_result = m_decryptor.Decrypt(ciphertext, ciphertextLength, m_plaintext);
				if (!m_result.isValidCoding)
					throw InvalidCiphertext(m_decryptor.AlgorithmName() + ": invalid ciphertext");
				}

			case 1:
				if (!Output(1, m_plaintext, m_result.messageLength, 0, blocking))
					return false;
			}
			return true;
		}
コード例 #15
0
ファイル: VEProver.cpp プロジェクト: myucel/cashlib
vector<ZZ> VEProver::encrypt(const vector<ZZ> &messages, const string &label,
							 const hashalg_t &hashAlg, int stat) {
	Environment e;
	// first create and give in our group
	ZZ bigN = pk->getN();
	e.groups["RSAGroup"] = new GroupRSA("arbiter", bigN, stat);
	ZZ bigNSquared = power(bigN, 2);
	e.groups["G"] = new GroupSquareMod("arbiter", bigNSquared, stat);
	// now add in elements
	e.variables["f"] = pk->getF();
	e.variables["b"] = pk->getB();
	vector<ZZ> as = pk->getAValues();
	// XXX: only add as many a values as there as message values
	// should come up with something better for this
	assert(as.size() >= messages.size());
	for (unsigned i = 0; i < messages.size(); i++) {
		string name = "a_" + lexical_cast<string>(i+1);
		e.variables[name] = as[i];
	}
	// now add x_i's
	for (unsigned i = 0; i < messages.size(); i++) {
		string name = "x_" + lexical_cast<string>(i+1);
		e.variables[name] = messages[i];
	}
	input_map inputs;
	int m = messages.size();
	inputs["m"] = m;	

	// now do the computation: this gives us r, u_i, v
	InterpreterProver calculator;
	calculator.check("ZKP/examples/encrypt.txt", inputs, e.groups);
	startTimer();
	calculator.compute(e.variables);
	printTimer("Computed stuff for normal encryption");

	// get new environment
	e = calculator.getEnvironment();
	// now need to compute w = abs([d * e^hash(...)]^r mod N^2)
	ZZ d = pk->getD();
	ZZ eVal = pk->getE();
	e.variables["d"] = d;
	e.variables["e"] = eVal;
	// need hash vector to be u_1, ..., u_m, v
	// set initial size for ciphertext so we can order it
	vector<ZZ> ciphertext(m+1);
	for (variable_map::iterator it = e.variables.begin();
								it != e.variables.end(); ++it) {
		if (it->first.find("u_") != string::npos) {
			// XXX: this is string parsing -- very undesirable!
			int index = lexical_cast<int>(it->first.substr(2));
			ciphertext[index-1] = it->second;
		} else if (it->first.find("v") != string::npos) {
			ciphertext[m] = it->second;
		}
	}
	string hashKey = pk->getHashKey();
	ZZ hash = CommonFunctions::ZZFromBytes(Hash::hash(ciphertext, label,
													  hashAlg, hashKey));
	e.variables["hash"] = hash;
	ZZ eHash = PowerMod(eVal, hash, bigNSquared);
	ZZ de = MulMod(d, eHash, bigNSquared);
	ZZ r = e.variables.at("r");
	ZZ w = CommonFunctions::abs(PowerMod(de, r, bigNSquared), bigNSquared);
	// insert w into environment
	e.variables["w"] = w;

	// save environment
	env = e;
	
	// now output full ciphertext u_1,...,u_m,v,w
	ciphertext.push_back(w);
	return ciphertext;
}
コード例 #16
0
bool OTEnvelope::Open(const OTPseudonym & theRecipient, 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 &	privateKey	= (OTAsymmetricKey &)theRecipient.GetPrivateKey();
	EVP_PKEY *			pkey		= (EVP_PKEY *)privateKey.GetKey();
	
	if (NULL == pkey)
	{
		OTLog::Error("Null private key in OTEnvelope::Open\n");
		return false;
	}
		
	EVP_CIPHER_CTX_init(&ctx);
    ek = (unsigned char*)malloc(EVP_PKEY_size(pkey));  // I assume this is for the AES key
	
	OT_ASSERT(NULL != ek);
	
	memset(ek, 0, EVP_PKEY_size(pkey));

	eklen = EVP_PKEY_size(pkey);
	
	
	//int EVP_OpenInit(EVP_CIPHER_CTX *ctx,
	//EVP_CIPHER *type,
	//unsigned char *ek, 
	//int ekl,
	//unsigned char *iv,
	//EVP_PKEY *priv);
	
	//EVP_OpenInit() initializes a cipher context ctx for decryption with cipher type. It decrypts the encrypted 
	//	symmetric key of length ekl bytes passed in the ek parameter using the private key priv. The IV is supplied 
	//	in the iv parameter.
		

	theContents.Release();	// This is where we'll put the decrypted data.
	m_dataContents.reset(); // reset the fread position on this object.
	
	int nReadLength = 0;
	int nReadKey = 0;
	int nReadIV = 0;
	
	// First we read the encrypted key size.
	if (0 == (nReadLength = m_dataContents.OTfread((char*)&eklen_n, sizeof(eklen_n))))
	{
		OTLog::Error("Error reading encrypted key size in OTEnvelope::Open\n");
		free(ek); ek = NULL;
		return false;
	}
	
	// convert it from network to host endian.
	eklen = ntohl(eklen_n);
	
	// Next we read the encrypted key itself.
	if (0 == (nReadKey = m_dataContents.OTfread((char*)ek, eklen)))
	{
		OTLog::Error("Error reading encrypted key size in OTEnvelope::Open\n");
		free(ek); ek = NULL;
		return false;
	}
	
	// Next we read the initialization vector.
	if (0 == (nReadIV = m_dataContents.OTfread((char*)iv, EVP_CIPHER_iv_length(EVP_aes_128_cbc()))))
	{
		OTLog::Error("Error reading initialization vector in OTEnvelope::Open\n");
		free(ek); ek = NULL;
		return false;
	}
	
	OTData ciphertext((const void*)((unsigned char *)m_dataContents.GetPointer() + nReadLength + nReadKey + nReadIV), 
					  m_dataContents.GetSize() - nReadLength - nReadKey - nReadIV);
	
	
	
	// Now we process ciphertext and write the decrypted data to plaintext.
	OTData plaintext;

	if (!EVP_OpenInit(&ctx, EVP_aes_128_cbc(), ek, eklen, iv, pkey))
    {
        OTLog::Error("EVP_OpenInit: failed.\n");
		free(ek); ek = NULL;
		return false;
    }
		
    while ((len = ciphertext.OTfread((char*)buffer, sizeof(buffer))) > 0)
    {
        if (!EVP_OpenUpdate(&ctx, buffer_out, &len_out, buffer, len))
        {
            OTLog::Error("EVP_OpenUpdate: failed.\n");
			free(ek); ek = NULL;
			return false;
        }
		
		OTData dataOpenUpdate(buffer_out, len_out);
		plaintext += dataOpenUpdate;
	}
	
    if (!EVP_OpenFinal(&ctx, buffer_out, &len_out))
    {
		OTLog::Error("EVP_OpenFinal: failed.\n");
 		free(ek); ek = NULL;
		return false;
    }
	
	OTData dataOpenFinal(buffer_out, len_out);
	plaintext += dataOpenFinal;
	
	// Make sure it's null terminated
	int nIndex = plaintext.GetSize()-1;
	((unsigned char*)plaintext.GetPointer())[nIndex] = 0;
	
	// Set it into theContents (to return the plaintext to the caller)
	theContents.Set((const char *)plaintext.GetPointer());
	
	retval = true;
	
    free(ek); ek = NULL;
	
    return retval;
	
}