// if connected, send out a message // returns false if not connected or error. // auto-splits large messages larger than buffer. bool SockClient::sendc(CharString message){ CharString emsg = (encryptor!=0x0) ? encryptor(message) : message; // Apply encryption if(emsg.getSize() <= 2) return false; //cout << "Send message(" << emsg.getSize() << ")" << emsg.get() << endl; cout << "Send message(" << emsg.getSize() << ")"<< endl; int flags=0; int looptimes=1; int i, msgret, msgsize; char* msg; #ifdef LINUXXX if(!testAlive()){ // uh... return false; } if(ctype == SC_TCP){ //msgret = send(sockd, message.get(), message.getSize(), flags); //cout << "Pre-write SC_TCP " << emsg.getSize() << endl; if(testAlive()) msgret = write(sockd, emsg.get(), emsg.getSize()); //cout << "post-write" << endl; }else{ socklen_t addrlen = sizeof(struct sockaddr_in); //msgret = sendto(sockd, emsg.get(), emsg.getSize(), &cli_addr, address); } // detect error if(msgret == -1) return false; #endif return true; }
QByteArray Encryptor::encryptAsymmetricly(QByteArray &publicKey, QByteArray &data) { Botan::DataSource_Memory key_pub(publicKey.toStdString()); auto publicRsaKey = Botan::X509::load_key(key_pub); const uint DATA_SIZE = data.size(); Botan::byte msgtoencrypt[DATA_SIZE]; for (uint i = 0; i < DATA_SIZE; i++) { msgtoencrypt[i] = data[i]; } Botan::PK_Encryptor_EME encryptor(*publicRsaKey, "EME1(SHA-256)"); Botan::AutoSeeded_RNG rng; std::vector<Botan::byte> ciphertext = encryptor.encrypt(msgtoencrypt, DATA_SIZE, rng); QByteArray keyCipherData; keyCipherData.resize(ciphertext.size()); for ( uint i = 0; i < ciphertext.size(); i++ ) { keyCipherData[i] = ciphertext.at(i); } return keyCipherData; }
void AddressTester::onConnected() { timer.stop(); emit lagTestFinished(time.msecsTo(QTime::currentTime())); if (testingConnectivity) { Encryptor encryptor(encryptionMethod, encryptionPassword); /* * A http request to Google to test connectivity * The payload is dumped from * `curl http://www.google.com --socks5 127.0.0.1:1080` * * TODO: find a better way to check connectivity */ std::string dest = Common::packAddress(Address("www.google.com", 80)); static const QByteArray expected = QByteArray::fromHex( "474554202f20485454502f312e310d0a486f73743a" "207777772e676f6f676c652e636f6d0d0a55736572" "2d4167656e743a206375726c2f372e34332e300d0a" "4163636570743a202a2f2a0d0a0d0a"); std::string payload(expected.data(), expected.length()); std::string toWrite = encryptor.encrypt(dest + payload); socket.write(toWrite.data(), toWrite.size()); } else { socket.abort(); } }
std::string encrypt_string(const char *instr, const char *pass_phrase) { std::string out_str; CryptoPP::DefaultEncryptorWithMAC encryptor(pass_phrase, new CryptoPP::HexEncoder(new CryptoPP::StringSink(out_str))); encryptor.Put((byte *) instr, strlen(instr)); encryptor.MessageEnd(); return out_str; }
void Cipher::encrypt(std::istream& source, std::ostream& sink, Encoding encoding) { CryptoInputStream encryptor(source, createEncryptor()); switch (encoding) { case ENC_NONE: StreamCopier::copyStream(encryptor, sink); break; case ENC_BASE64: { Poco::Base64Encoder encoder(sink); StreamCopier::copyStream(encryptor, encoder); encoder.close(); } break; case ENC_BINHEX: { Poco::HexBinaryEncoder encoder(sink); StreamCopier::copyStream(encryptor, encoder); encoder.close(); } break; default: throw Poco::InvalidArgumentException("Invalid argument", "encoding"); } }
Test::Result PK_Encryption_Decryption_Test::run_one_test(const std::string&, const VarMap& vars) { const std::vector<uint8_t> plaintext = get_req_bin(vars, "Msg"); const std::vector<uint8_t> ciphertext = get_req_bin(vars, "Ciphertext"); const std::string padding = get_opt_str(vars, "Padding", default_padding(vars)); std::unique_ptr<Botan::RandomNumberGenerator> kat_rng; if(vars.count("Nonce")) { kat_rng.reset(new Fixed_Output_RNG(get_req_bin(vars, "Nonce"))); } Test::Result result(algo_name() + "/" + padding + " decryption"); std::unique_ptr<Botan::Private_Key> privkey = load_private_key(vars); // instead slice the private key to work around elgamal test inputs //std::unique_ptr<Botan::Public_Key> pubkey(Botan::X509::load_key(Botan::X509::BER_encode(*privkey))); Botan::PK_Encryptor_EME encryptor(*privkey, padding); result.test_eq("encryption", encryptor.encrypt(plaintext, kat_rng ? *kat_rng : Test::rng()), ciphertext); Botan::PK_Decryptor_EME decryptor(*privkey, padding); result.test_eq("decryption", decryptor.decrypt(ciphertext), plaintext); check_invalid_ciphertexts(result, decryptor, plaintext, ciphertext); return result; }
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; }
void TestSymmetricCipher(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::string key = GetDecodedDatum(v, "Key"); std::string ciphertext = GetDecodedDatum(v, "Ciphertext"); std::string plaintext = GetDecodedDatum(v, "Plaintext"); TestDataNameValuePairs pairs(v); if (test == "Encrypt") { std::auto_ptr<SymmetricCipher> encryptor(ObjectFactoryRegistry<SymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str())); encryptor->SetKey((const byte *)key.data(), key.size(), pairs); std::string encrypted; StringSource ss(plaintext, true, new StreamTransformationFilter(*encryptor, new StringSink(encrypted), StreamTransformationFilter::NO_PADDING)); if (encrypted != ciphertext) SignalTestFailure(); } else if (test == "Decrypt") { std::auto_ptr<SymmetricCipher> decryptor(ObjectFactoryRegistry<SymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str())); decryptor->SetKey((const byte *)key.data(), key.size(), pairs); std::string decrypted; StringSource ss(ciphertext, true, new StreamTransformationFilter(*decryptor, new StringSink(decrypted), StreamTransformationFilter::NO_PADDING)); if (decrypted != plaintext) SignalTestFailure(); } else { SignalTestError(); assert(false); } }
string EncryptString(const char *instr, const char *passPhrase) { string outstr; DefaultEncryptorWithMAC encryptor(passPhrase, new HexEncoder(new StringSink(outstr))); encryptor.Put((byte *)instr, strlen(instr)); encryptor.MessageEnd(); return outstr; }
bool Session::e_write(void const* buffer, std::size_t size) { CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption encryptor(this->aes.key, sizeof(aes_key), this->aes.iv); std::unique_ptr<uint8_t[]> buf(new uint8_t[size]); encryptor.ProcessData(buf.get(), (uint8_t const*)buffer, size); return (write(this->fd, buf.get(), size) > 0); }
bool Session::do_key_exchange() { aes_buffer aes_tmp; CryptoPP::AutoSeededRandomPool prng; prng.GenerateBlock(this->aes.key, sizeof(aes_key)); prng.GenerateBlock(this->aes.iv, sizeof(aes_iv)); std::memcpy(&aes_tmp, &this->aes, sizeof(aes_buffer)); CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption encryptor(aes_hard_key, sizeof(aes_key), aes_hard_iv); encryptor.ProcessData((uint8_t*)&aes_tmp, (uint8_t const*)&this->aes, sizeof(aes_buffer)); return (write(this->fd, &aes_tmp, sizeof(aes_buffer)) > 0); }
void EncryptorDefault::encrypt(const umf_string& input, umf_rawbuffer& output) { string outBuf; try { //or specify length of passphrase: encryptor(passphrase.c_str(), passphrase.length(), ...); DefaultEncryptorWithMAC encryptor(passphrase.c_str(), new StringSink(outBuf)); encryptor.Put((byte*)input.data(), input.length()); encryptor.MessageEnd(); } catch (CryptoPP::Exception const& e) { UMF_EXCEPTION(IncorrectParamException, "CryptoPP::Exception caught:" +string(e.what())); } output = umf_rawbuffer(outBuf.data(), outBuf.length()); }
void cryptos::_sha_encrypt(const bybuff& key, const bybuff& data, bybuff& out)const { //Key and IV setup //AES encryption uses a secret key of a variable length (128-bit, 196-bit or 256- //bit). This key is secretly exchanged between two parties before communication //begins. DEFAULT_KEYLENGTH= 16 bytes //uint8_t iv[ CryptoPP::AES::BLOCKSIZE ] = {0}; std::string encoded; try{ #if 0 CryptoPP::AES::Encryption aesEncryption(key.buffer(), key.length()); CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption( aesEncryption, iv ); CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink( encoded ) ); stfEncryptor.Put( data.buffer(), (size_t)data.length() ); stfEncryptor.MessageEnd(); out = encoded; _TRACE("_sha_e(" << key.to_string() <<","<< data.to_string() <<")=" << out.to_string()); bybuff r; _sha_decrypt(key, out, r); #endif //0 CryptoPP::ECB_Mode< CryptoPP::AES >::Encryption aes_128_ecb;//(key.buffer(), key.length(), iv); aes_128_ecb.SetKey( key.buffer(), key.length() ); CryptoPP::StreamTransformationFilter encryptor(aes_128_ecb, 0, CryptoPP::BlockPaddingSchemeDef::NO_PADDING); for(size_t j = 0; j < data.length(); j++) { encryptor.Put((byte)data[j]); } encryptor.MessageEnd(); size_t ready = encryptor.MaxRetrievable(); byte outa[32] = {0}; encryptor.Get((byte*) outa, ready); out.append(outa, ready); } catch( CryptoPP::Exception& e ) { ERROR( e.what()); assert(0); } // bybuff r; //_sha_decrypt(key, out, r); }
void InvertibleRSAFunction::GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs &alg) { int modulusSize = 2048; alg.GetIntValue(Name::ModulusSize(), modulusSize) || alg.GetIntValue(Name::KeySize(), modulusSize); assert(modulusSize >= 16); if (modulusSize < 16) throw InvalidArgument("InvertibleRSAFunction: specified modulus size is too small"); m_e = alg.GetValueWithDefault(Name::PublicExponent(), Integer(17)); assert(m_e >= 3); assert(!m_e.IsEven()); if (m_e < 3 || m_e.IsEven()) throw InvalidArgument("InvertibleRSAFunction: invalid public exponent"); RSAPrimeSelector selector(m_e); AlgorithmParameters primeParam = MakeParametersForTwoPrimesOfEqualSize(modulusSize) (Name::PointerToPrimeSelector(), selector.GetSelectorPointer()); m_p.GenerateRandom(rng, primeParam); m_q.GenerateRandom(rng, primeParam); m_d = m_e.InverseMod(LCM(m_p-1, m_q-1)); assert(m_d.IsPositive()); m_dp = m_d % (m_p-1); m_dq = m_d % (m_q-1); m_n = m_p * m_q; m_u = m_q.InverseMod(m_p); if (FIPS_140_2_ComplianceEnabled()) { RSASS<PKCS1v15, SHA>::Signer signer(*this); RSASS<PKCS1v15, SHA>::Verifier verifier(signer); SignaturePairwiseConsistencyTest_FIPS_140_Only(signer, verifier); RSAES<OAEP<SHA> >::Decryptor decryptor(*this); RSAES<OAEP<SHA> >::Encryptor encryptor(decryptor); EncryptionPairwiseConsistencyTest_FIPS_140_Only(encryptor, decryptor); } }
void TestAsymmetricCipher(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); member_ptr<PK_Encryptor> encryptor(ObjectFactoryRegistry<PK_Encryptor>::Registry().CreateObject(name.c_str())); member_ptr<PK_Decryptor> decryptor(ObjectFactoryRegistry<PK_Decryptor>::Registry().CreateObject(name.c_str())); std::string keyFormat = GetRequiredDatum(v, "KeyFormat"); if (keyFormat == "DER") { decryptor->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PrivateKey")).Ref()); encryptor->AccessMaterial().Load(StringStore(GetDecodedDatum(v, "PublicKey")).Ref()); } else if (keyFormat == "Component") { TestDataNameValuePairs pairs(v); decryptor->AccessMaterial().AssignFrom(pairs); encryptor->AccessMaterial().AssignFrom(pairs); } if (test == "DecryptMatch") { std::string decrypted, expected = GetDecodedDatum(v, "Plaintext"); StringSource ss(GetDecodedDatum(v, "Ciphertext"), true, new PK_DecryptorFilter(GlobalRNG(), *decryptor, new StringSink(decrypted))); if (decrypted != expected) SignalTestFailure(); } else if (test == "KeyPairValidAndConsistent") { TestKeyPairValidAndConsistent(encryptor->AccessMaterial(), decryptor->GetMaterial()); } else { SignalTestError(); assert(false); } }
bool ValidateDLIES() { cout << "\nDLIES validation suite running...\n\n"; bool pass = true; { FileSource fc("TestData/dlie1024.dat", true, new HexDecoder); DLIES<>::Decryptor privC(fc); DLIES<>::Encryptor pubC(privC); pass = CryptoSystemValidate(privC, pubC) && pass; } { cout << "Generating new encryption key..." << endl; DLIES<>::GroupParameters gp; gp.GenerateRandomWithKeySize(GlobalRNG(), 128); DLIES<>::Decryptor decryptor; decryptor.AccessKey().GenerateRandom(GlobalRNG(), gp); DLIES<>::Encryptor encryptor(decryptor); pass = CryptoSystemValidate(decryptor, encryptor) && pass; } return pass; }
QByteArray Encryptor::encryptAsymmetricly(ConnectedUser *user, std::string &data) { const unsigned long DATA_SIZE = data.size(); Botan::byte msgtoencrypt[DATA_SIZE]; for (uint i = 0; i < DATA_SIZE; i++) { msgtoencrypt[i] = static_cast<unsigned char>(data[i]); } Botan::PK_Encryptor_EME encryptor(user->publicKey(), "EME1(SHA-256)"); Botan::AutoSeeded_RNG rng; auto ciphertext = encryptor.encrypt(msgtoencrypt, DATA_SIZE, rng); QByteArray keyCipherData; keyCipherData.resize(ciphertext.size()); for ( uint i = 0; i < ciphertext.size(); i++ ) { keyCipherData[i] = static_cast<char>(ciphertext[i]); } return keyCipherData; }
/* * Alon: this function should simply read the data on the given file, * copy it, and return it to the user as it is (encrypted or not). * The function's return value is the total amount of bytes read from the * file, or -1 if the function failed. */ ssize_t my_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) { if (check_buffer_size(count) != 0) { return -EINVAL; } int minor = get_minor_from_file(filp); int is_this_process_writer = is_writer(filp); int key = ((device_private_data *)((filp)->private_data))->private_key; down_interruptible(&read_lock[minor]); down_interruptible(&index_lock[minor]); int maxToRead = get_max_to_read(minor); if (maxToRead == 0) { int current_num_of_writers = get_current_num_of_writers(minor); if(current_num_of_writers == is_this_process_writer) { up(&index_lock[minor]); up(&read_lock[minor]); return 0; } //Going to sleep until something is written into the buffer up(&index_lock[minor]); int wake_up_reason = wait_event_interruptible(read_wq[minor], flag_is_empty[minor] == 0 || get_current_num_of_writers(minor) == is_this_process_writer); if(wake_up_reason != 0) { up(&read_lock[minor]); return -EINTR; } if (get_current_num_of_writers(minor) == is_this_process_writer) { up(&read_lock[minor]); return 0; } down_interruptible(&index_lock[minor]); maxToRead = get_max_to_read(minor); } int numToRead = MIN(maxToRead,count); int firstPartSize = 0; int retval = 0; char* tmpBuf =(char*)kmalloc(sizeof(char)*numToRead,GFP_KERNEL); if (!tmpBuf){ up(&index_lock[minor]); up(&read_lock[minor]); return -ENOMEM; } int numOfParts = ( (reading_position[minor] + numToRead) > BUF_SIZE) ? TWO : ONE ; char* source = tmpBuf; if(numOfParts == ONE ) { if (minor == 0) { encryptor(&buffer[minor][reading_position[minor]], tmpBuf, numToRead, key, minor); } else if(minor == 1){ // encryptor source = &buffer[minor][ reading_position[minor] ]; } retval = copy_to_user(buf, source, numToRead) ? -EFAULT : 0; reading_position[minor] = (reading_position[minor] + numToRead) % BUF_SIZE; } else { firstPartSize = BUF_SIZE - reading_position[minor]; if (minor == 0) { encryptor(&buffer[minor][ reading_position[minor] ], tmpBuf, firstPartSize, key, minor); encryptor(&buffer[minor][0],tmpBuf+firstPartSize , numToRead - firstPartSize, key, minor); } else if (minor == 1) { memcpy(tmpBuf, &buffer[minor][ reading_position[minor] ], firstPartSize); memcpy(tmpBuf+firstPartSize, &buffer[minor][0], numToRead - firstPartSize); } retval = copy_to_user(buf, tmpBuf, numToRead); reading_position[minor] = numToRead - firstPartSize; } kfree(tmpBuf); if(retval != 0){ up(&index_lock[minor]); up(&read_lock[minor]); return retval; } if((writing_position[minor] == reading_position[minor]) && numToRead){ flag_is_empty[minor] = 1; } if(numToRead != 0){ // if we have read SOMETHING, the buffer is not full anymore flag_is_full[minor] = 0; wake_up_interruptible(&write_wq[minor]); //Notifies any waiting writers that there is now room within the buffer } up(&index_lock[minor]); up(&read_lock[minor]); return numToRead; }
/* * Alon: This function should write the buffer given by the user into the file. * The function assumes the given buffer is encrypted, and will therefor * use the iKey to decypher each character before writing it to the file. * The function returns the amount of bytes it managed to write into the * file, and -1 in case of failure. */ ssize_t my_write(struct file *filp, const char *buf, size_t count, loff_t *f_pos) { if(check_buffer_size(count) != 0) { return -EINVAL; } int minor = get_minor_from_file(filp); int is_this_process_reader = is_reader(filp); int key = ((device_private_data *)((filp)->private_data))->private_key; down_interruptible(&write_lock[minor]); down_interruptible(&index_lock[minor]); int maxToWrite = get_max_to_write(minor); if (maxToWrite == 0) { int current_num_of_readers = get_current_num_of_readers(minor); if(current_num_of_readers == is_this_process_reader) { up(&index_lock[minor]); up(&write_lock[minor]); return 0; } //Going to sleep until a reader clears some room in the buffer up(&index_lock[minor]); int wake_up_reason = wait_event_interruptible(write_wq[minor], flag_is_full[minor] == 0 || get_current_num_of_readers(minor) == is_this_process_reader); if(wake_up_reason != 0) { up(&write_lock[minor]); return -EINTR; } if (get_current_num_of_readers(minor) == is_this_process_reader) { up(&write_lock[minor]); return 0; } down_interruptible(&index_lock[minor]); maxToWrite = get_max_to_write(minor); } int numToWrite = MIN(maxToWrite,count); int firstPartSize = 0; int retval = 0; char* tmpBuf =(char*)kmalloc(sizeof(char)*numToWrite,GFP_KERNEL); if (!tmpBuf){ up(&index_lock[minor]); up(&write_lock[minor]); return -ENOMEM; } retval = copy_from_user(tmpBuf, buf, numToWrite); //copy the data from user if(retval != 0){ kfree(tmpBuf); up(&index_lock[minor]); up(&write_lock[minor]); return retval; } int numOfParts = ( (writing_position[minor] + numToWrite) > BUF_SIZE) ? TWO : ONE ; if(numOfParts == ONE ) { if (minor == 1) { encryptor(tmpBuf, &buffer[minor][writing_position[minor]], numToWrite, key, minor); } else if(minor == 0){ memcpy(&buffer[minor][ writing_position[minor] ], tmpBuf, numToWrite); } writing_position[minor] = (writing_position[minor] + numToWrite) % BUF_SIZE; } else { firstPartSize = BUF_SIZE - writing_position[minor]; if (minor == 1) { encryptor(tmpBuf, &buffer[minor][writing_position[minor]], firstPartSize, key, minor); encryptor(tmpBuf + firstPartSize, &buffer[minor][0], numToWrite - firstPartSize, key, minor); } else if (minor == 0) { memcpy(&buffer[minor][writing_position[minor]], tmpBuf, firstPartSize); memcpy(&buffer[minor][0], tmpBuf + firstPartSize, numToWrite - firstPartSize); } writing_position[minor] = (numToWrite - firstPartSize); } if(( writing_position[minor] == reading_position[minor]) && numToWrite){ flag_is_full[minor] = 1; } if (numToWrite) { flag_is_empty[minor] = 0; wake_up_interruptible(&read_wq[minor]); } /* * If we wrote something into the buffer, this makes sure to wake up * any writer who may be waiting for input. */ kfree(tmpBuf); up(&index_lock[minor]); up(&write_lock[minor]); if(retval != 0){ return retval; } return numToWrite; }
static PyObject *tripledescbc_encrypt(tripledescbc *self, PyObject *args) { // std::cout << "hello enc 0" << std::endl; std::cout.flush(); PyObject *result = NULL; byte *ciphertext = NULL; try { byte *iv; unsigned int ivlength; byte *text; unsigned int textlength; if(!PyArg_ParseTuple(args, "s#s#", &iv, &ivlength, &text, &textlength)) { throw Exception(Exception::INVALID_ARGUMENT, "wrong type of parameters passed in from Python"); } if(ivlength != 8) { throw Exception(Exception::INVALID_ARGUMENT, "IV length must be 8"); } // std::cout << "hello enc 0.7" << std::endl; std::cout.flush(); // std::cout << "hello enc 0.7.1, self: " << self << std::endl; std::cout.flush(); // std::cout << "hello enc 0.7.2, self->key: "; // std::cout << self->key; // std::cout << std::endl; // std::cout.flush(); // std::cout << "hello enc 0.7.3, iv: " << iv << std::endl; std::cout.flush(); CBC_CTS_Mode<DES_XEX3>::Encryption encryption(self->key, 24, iv); // std::cout << "hello enc 0.8" << std::endl; std::cout.flush(); ciphertext = new byte[textlength]; // std::cout << "hello enc 0.9" << std::endl; std::cout.flush(); if (ciphertext == NULL) { throw MemoryException(); } // std::cout << "hello enc 1" << std::endl; std::cout.flush(); StreamTransformationFilter encryptor(encryption, new ArraySink(ciphertext, textlength)); // std::cout << "hello enc 2" << std::endl; std::cout.flush(); encryptor.PutMessageEnd(text, textlength); // std::cout << "hello enc 3" << std::endl; std::cout.flush(); result = Py_BuildValue("s#", ciphertext, textlength); // std::cout << "hello enc 4" << std::endl; std::cout.flush(); if(result == NULL) { throw MemoryException(); } // std::cout << "hello enc 5" << std::endl; std::cout.flush(); xdeletear(ciphertext); // std::cout << "hello enc 6" << std::endl; std::cout.flush(); return result; } catch(CryptoPP::Exception &e) { if(result != NULL) { PyMem_DEL(result); } xdeletear(ciphertext); PyErr_SetString(TripleDESCBCError, e.what()); return NULL; } catch(MemoryException &e) { if(result != NULL) { PyMem_DEL(result); } xdeletear(ciphertext); PyErr_SetString(PyExc_MemoryError, "Can't allocate memory to do encryption"); return NULL; } // std::cout << "goodbye enc" << std::endl; std::cout.flush(); }
/*! \brief Input: flag for multiple runs Output: Message. * * This test creates a public and private key. The functions were tested for correctness in testSmall.c * Here we look at the integration of these functions to create the keys to have the properties * required of the GGH algortihm. */ int testGGH(int mruns){ printf("* Executing %i GGH run(s)\n",mruns); gsl_matrix *uniMatrix = gsl_matrix_alloc(SIZE,SIZE); gsl_matrix *privKey = gsl_matrix_alloc(SIZE,SIZE); gsl_matrix *pubKey = gsl_matrix_alloc(SIZE,SIZE); gsl_matrix *message = gsl_matrix_alloc(SIZE,SIZE); gsl_matrix *Cmessage = gsl_matrix_alloc(SIZE,SIZE); gsl_matrix *Dmessage = gsl_matrix_alloc(SIZE,SIZE); int i, match, mismatch =0; if (mruns == 1){ // Choose a good basis (Private key) [V] printf("Choose a good basis (Private key) [V]\n"); privKey = create_private_key(); // Create the unimodular matrix [U] printf("Create the unimodular matrix [U]\n"); uniMatrix = genU(); // Compute a bad basis (Public Key) printf("Compute a bad basis (Public Key)\n"); pubKey = create_public_key(privKey,uniMatrix); // Generate the message printf("Generate the message\n"); message = genM(); // Encrypt printf("Compute cypher text.\n"); Cmessage = encryptor(message,pubKey); // Decrypt printf("Decrypt\n"); Dmessage = decryptor(Cmessage,privKey,uniMatrix); // Compare Messages printf("Compare Messages\n"); if(compare(message,Dmessage)==0){ printf("The messages match.\n"); } else{ printf("Message and decryped message do not match.\n"); } } else{ uniMatrix = genU(); printf("Reusing the generated unimodular matrix [U] on 100 GGH runs.\n"); for(i =0;i < (mruns+1); i++){ // Choose a good basis (Private key) [V] privKey = create_private_key(); // Compute a bad basis (Public Key) pubKey = create_public_key(privKey,uniMatrix); // Generate the message message = genM(); // Encrypt Cmessage = encryptor(message,pubKey); // Decrypt Dmessage = decryptor(Cmessage,privKey,uniMatrix); // Compare Messages if(compare(message,Dmessage)==0){ match++; } else{ mismatch++; } } } printf(" Number of matches: %i",match); return 1; }
void TestSymmetricCipher(TestData &v) { std::string name = GetRequiredDatum(v, "Name"); std::string test = GetRequiredDatum(v, "Test"); std::string key = GetDecodedDatum(v, "Key"); std::string plaintext = GetDecodedDatum(v, "Plaintext"); TestDataNameValuePairs pairs(v); if (test == "Encrypt" || test == "EncryptXorDigest") { std::auto_ptr<SymmetricCipher> encryptor(ObjectFactoryRegistry<SymmetricCipher, ENCRYPTION>::Registry().CreateObject(name.c_str())); std::auto_ptr<SymmetricCipher> decryptor(ObjectFactoryRegistry<SymmetricCipher, DECRYPTION>::Registry().CreateObject(name.c_str())); ConstByteArrayParameter iv; if (pairs.GetValue(Name::IV(), iv) && iv.size() != encryptor->IVSize()) SignalTestFailure(); encryptor->SetKey((const byte *)key.data(), key.size(), pairs); decryptor->SetKey((const byte *)key.data(), key.size(), pairs); int seek = pairs.GetIntValueWithDefault("Seek", 0); if (seek) { encryptor->Seek(seek); decryptor->Seek(seek); } std::string encrypted, xorDigest, ciphertext, ciphertextXorDigest; StringSource ss(plaintext, false, new StreamTransformationFilter(*encryptor, new StringSink(encrypted), StreamTransformationFilter::NO_PADDING)); ss.Pump(plaintext.size()/2 + 1); ss.PumpAll(); /*{ std::string z; encryptor->Seek(seek); StringSource ss(plaintext, false, new StreamTransformationFilter(*encryptor, new StringSink(z), StreamTransformationFilter::NO_PADDING)); while (ss.Pump(64)) {} ss.PumpAll(); for (int i=0; i<z.length(); i++) assert(encrypted[i] == z[i]); }*/ if (test == "Encrypt") ciphertext = GetDecodedDatum(v, "Ciphertext"); else { ciphertextXorDigest = GetDecodedDatum(v, "CiphertextXorDigest"); xorDigest.append(encrypted, 0, 64); for (size_t i=64; i<encrypted.size(); i++) xorDigest[i%64] ^= encrypted[i]; } if (test == "Encrypt" ? encrypted != ciphertext : xorDigest != ciphertextXorDigest) { std::cout << "incorrectly encrypted: "; StringSource xx(encrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } std::string decrypted; StringSource dd(encrypted, false, new StreamTransformationFilter(*decryptor, new StringSink(decrypted), StreamTransformationFilter::NO_PADDING)); dd.Pump(plaintext.size()/2 + 1); dd.PumpAll(); if (decrypted != plaintext) { std::cout << "incorrectly decrypted: "; StringSource xx(decrypted, false, new HexEncoder(new FileSink(std::cout))); xx.Pump(256); xx.Flush(false); std::cout << "\n"; SignalTestFailure(); } } else if (test == "Decrypt") { } else { SignalTestError(); assert(false); } }
/* * Create a new Client Key Exchange message */ Client_Key_Exchange::Client_Key_Exchange(Handshake_IO& io, Handshake_State& state, const Policy& policy, Credentials_Manager& creds, const Public_Key* server_public_key, const std::string& hostname, RandomNumberGenerator& rng) { const std::string kex_algo = state.ciphersuite().kex_algo(); if(kex_algo == "PSK") { std::string identity_hint = ""; if(state.server_kex()) { TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params()); identity_hint = reader.get_string(2, 0, 65535); } const std::string psk_identity = creds.psk_identity("tls-client", hostname, identity_hint); append_tls_length_value(m_key_material, psk_identity, 2); SymmetricKey psk = creds.psk("tls-client", hostname, psk_identity); std::vector<byte> zeros(psk.length()); append_tls_length_value(m_pre_master, zeros, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } else if(state.server_kex()) { TLS_Data_Reader reader("ClientKeyExchange", state.server_kex()->params()); SymmetricKey psk; if(kex_algo == "DHE_PSK" || kex_algo == "ECDHE_PSK") { std::string identity_hint = reader.get_string(2, 0, 65535); const std::string psk_identity = creds.psk_identity("tls-client", hostname, identity_hint); append_tls_length_value(m_key_material, psk_identity, 2); psk = creds.psk("tls-client", hostname, psk_identity); } if(kex_algo == "DH" || kex_algo == "DHE_PSK") { BigInt p = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); BigInt Y = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); if(reader.remaining_bytes()) throw Decoding_Error("Bad params size for DH key exchange"); if(p.bits() < policy.minimum_dh_group_size()) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "Server sent DH group of " + std::to_string(p.bits()) + " bits, policy requires at least " + std::to_string(policy.minimum_dh_group_size())); /* * A basic check for key validity. As we do not know q here we * cannot check that Y is in the right subgroup. However since * our key is ephemeral there does not seem to be any * advantage to bogus keys anyway. */ if(Y <= 1 || Y >= p - 1) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "Server sent bad DH key for DHE exchange"); DL_Group group(p, g); if(!group.verify_group(rng, false)) throw TLS_Exception(Alert::INSUFFICIENT_SECURITY, "DH group validation failed"); DH_PublicKey counterparty_key(group, Y); DH_PrivateKey priv_key(rng, group); PK_Key_Agreement ka(priv_key, "Raw"); secure_vector<byte> dh_secret = CT::strip_leading_zeros( ka.derive_key(0, counterparty_key.public_value()).bits_of()); if(kex_algo == "DH") m_pre_master = dh_secret; else { append_tls_length_value(m_pre_master, dh_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } append_tls_length_value(m_key_material, priv_key.public_value(), 2); } else if(kex_algo == "ECDH" || kex_algo == "ECDHE_PSK") { const byte curve_type = reader.get_byte(); if(curve_type != 3) throw Decoding_Error("Server sent non-named ECC curve"); const u16bit curve_id = reader.get_u16bit(); const std::string name = Supported_Elliptic_Curves::curve_id_to_name(curve_id); if(name == "") throw Decoding_Error("Server sent unknown named curve " + std::to_string(curve_id)); EC_Group group(name); std::vector<byte> ecdh_key = reader.get_range<byte>(1, 1, 255); ECDH_PublicKey counterparty_key(group, OS2ECP(ecdh_key, group.get_curve())); ECDH_PrivateKey priv_key(rng, group); PK_Key_Agreement ka(priv_key, "Raw"); secure_vector<byte> ecdh_secret = ka.derive_key(0, counterparty_key.public_value()).bits_of(); if(kex_algo == "ECDH") m_pre_master = ecdh_secret; else { append_tls_length_value(m_pre_master, ecdh_secret, 2); append_tls_length_value(m_pre_master, psk.bits_of(), 2); } append_tls_length_value(m_key_material, priv_key.public_value(), 1); } #if defined(BOTAN_HAS_SRP6) else if(kex_algo == "SRP_SHA") { const BigInt N = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); const BigInt g = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); std::vector<byte> salt = reader.get_range<byte>(1, 1, 255); const BigInt B = BigInt::decode(reader.get_range<byte>(2, 1, 65535)); const std::string srp_group = srp6_group_identifier(N, g); const std::string srp_identifier = creds.srp_identifier("tls-client", hostname); const std::string srp_password = creds.srp_password("tls-client", hostname, srp_identifier); std::pair<BigInt, SymmetricKey> srp_vals = srp6_client_agree(srp_identifier, srp_password, srp_group, "SHA-1", salt, B, rng); append_tls_length_value(m_key_material, BigInt::encode(srp_vals.first), 2); m_pre_master = srp_vals.second.bits_of(); } #endif else { throw Internal_Error("Client_Key_Exchange: Unknown kex " + kex_algo); } reader.assert_done(); } else { // No server key exchange msg better mean RSA kex + RSA key in cert if(kex_algo != "RSA") throw Unexpected_Message("No server kex but negotiated kex " + kex_algo); if(!server_public_key) throw Internal_Error("No server public key for RSA exchange"); if(auto rsa_pub = dynamic_cast<const RSA_PublicKey*>(server_public_key)) { const Protocol_Version offered_version = state.client_hello()->version(); m_pre_master = rng.random_vec(48); m_pre_master[0] = offered_version.major_version(); m_pre_master[1] = offered_version.minor_version(); PK_Encryptor_EME encryptor(*rsa_pub, "PKCS1v15"); const std::vector<byte> encrypted_key = encryptor.encrypt(m_pre_master, rng); append_tls_length_value(m_key_material, encrypted_key, 2); } else throw TLS_Exception(Alert::HANDSHAKE_FAILURE, "Expected a RSA key in server cert but got " + server_public_key->algo_name()); } state.hash().update(io.send(*this)); }