Exemplo n.º 1
1
string RNEncryptor::encrypt(string plaintext, string password, RNCryptorSchema schemaVersion)
{
	this->configureSettings(schemaVersion);

	RNCryptorPayloadComponents components;
	components.schema = (char)schemaVersion;
	components.options = (char)this->options;
	components.salt = this->generateSalt();
	components.hmacSalt = this->generateSalt();
	components.iv = this->generateIv(this->ivLength);

	SecByteBlock key = this->generateKey(components.salt, password);

	switch (this->aesMode) {
		case MODE_CTR: {

			CTR_Mode<AES>::Encryption encryptor;
			encryptor.SetKeyWithIV((const byte *)key.data(), key.size(), (const byte *)components.iv.data());

			StringSource(plaintext, true,
				// StreamTransformationFilter adds padding as required.
				new StreamTransformationFilter(encryptor,
					new StringSink(components.ciphertext)
				)
			);

			break;
		}
		case MODE_CBC: {

			CBC_Mode<AES>::Encryption encryptor;
			encryptor.SetKeyWithIV(key.BytePtr(), key.size(), (const byte *)components.iv.data());

			StringSource(plaintext, true,
				// StreamTransformationFilter adds padding as required.
				new StreamTransformationFilter(encryptor,
					new StringSink(components.ciphertext)
				)
			);

			break;
		}
	}

	stringstream binaryData;
	binaryData << components.schema;
	binaryData << components.options;
	binaryData << components.salt;
	binaryData << components.hmacSalt;
	binaryData << components.iv;
	binaryData << components.ciphertext;

	std::cout << "Hex encoded: " << this->hex_encode(binaryData.str()) << std::endl;

	binaryData << this->generateHmac(components, password);

	return this->base64_encode(binaryData.str());
}
Exemplo n.º 2
0
QString QuizDatabase::Encrypt(QString src)
{
    QString t_output;
    byte key[AES::DEFAULT_KEYLENGTH] = EncryptionKey;
    byte iv[AES::BLOCKSIZE] = EncryptionKey_2;
    OFB_Mode<AES>::Encryption t_Encrypt;
    t_Encrypt.SetKeyWithIV(key,sizeof(key),iv);
    string t_Str,t_strNonHex,t_strCompletelyEncrypted;
    t_Str = src.toStdString();
    StringSource(t_Str,true,new StreamTransformationFilter(t_Encrypt,new StringSink(t_strNonHex)));
    StringSource(t_strNonHex,true,new HexEncoder(new StringSink(t_strCompletelyEncrypted)));
    t_output = QString::fromStdString(t_strCompletelyEncrypted);
    return t_output;
}
Exemplo n.º 3
0
void encrypt_file(string oFile, string encMode)
{
    // SecByteBlock key(AES::MAX_KEYLENGTH);
    // byte iv[ AES::BLOCKSIZE ];
   
    string ofilename = oFile;
    string outFile = oFile + ".egg";
    string efilename = outFile;   
    
    std::ifstream ifile(oFile.c_str(), ios::binary);
    std::ifstream::pos_type size = ifile.seekg(0, std::ios_base::end).tellg();
    ifile.seekg(0, std::ios_base::beg);

    string temp;
    temp.resize(size);
    ifile.read((char*)temp.data(), temp.size());
   
    if(encMode == "OFB")
    {
        OFB_Mode< AES >::Encryption e1;
        e1.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );
       
        StringSource( temp, true,
                        new StreamTransformationFilter( e1,
                        new FileSink( efilename.c_str() ))); 
    }
    else if(encMode == "CFB")
    {
        CFB_Mode< AES >::Encryption e1;
        e1.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );

        StringSource( temp, true,
                        new StreamTransformationFilter( e1,
                        new FileSink( efilename.c_str() ))); 
    }
    else if(encMode == "GCM")
    {
        GCM< AES >::Encryption e1;
        e1.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );
       
        StringSource ss1( temp, true,
                        new AuthenticatedEncryptionFilter( e1,
                        new FileSink( efilename.c_str() )));
    }
    else
    {
        cerr << "Invalid Mode" <<endl;
    }
}
Exemplo n.º 4
0
int main(int argc, char* argv[])
{
  AutoSeededRandomPool prng;
  byte fkey[SHA256::DIGESTSIZE];
  string key_from_file, plain;
  byte key[AES::MAX_KEYLENGTH]; // 32 bytes
  string filename=argv[2];
  string share_fkey;
  FileSource(argv[1], true,
             new HexDecoder(
                            new StringSink(key_from_file))
             );
  //removing directory paths if any
  filename = filename.substr(filename.find_last_of("/")+1,filename.length());

  byte iv[AES::BLOCKSIZE]; // 16 bytes
  iv[0] = 0;
  //prng.GenerateBlock(iv, sizeof(iv));
  string temp = key_from_file+filename;
  byte digest_input[temp.length()];
  for (int i=0;i<=temp.length();i++)
    digest_input[i]=temp[i];

  SHA256().CalculateDigest(fkey, digest_input, sizeof(digest_input));


  StringSource(fkey, sizeof(fkey),true,
               new HexEncoder(
                              new StringSink(share_fkey))
               );

  cout<<"fkey to share : "<<share_fkey<<endl;

  string new_filename = filename.substr(filename.find_last_of(".")+1,filename.length()) + '.' + filename.substr(0,filename.find_last_of("."));
  byte efile[SHA256::DIGESTSIZE];
  string encoded_efile;
  byte filename_plain_input[new_filename.length()];
  for (int i=0;i<=new_filename.length();i++)
    filename_plain_input[i]=(byte)new_filename[i];

  SHA256().CalculateDigest(efile, filename_plain_input, sizeof(filename_plain_input));
  StringSource(efile, sizeof(efile), true,
               new HexEncoder(
                              new StringSink(encoded_efile)
                              ) // HexEncoder
               ); // StringSource
  cout<<"the filename on cloud server : "<<encoded_efile<<endl<<endl;
  return 0;
}
Exemplo n.º 5
0
int HASH224_message(char* message, int len, 
				char* hash_message, int hash_len)
{
	AutoSeededRandomPool prng;
	
	SecByteBlock key(16);
	prng.GenerateBlock(key, key.size());

	string plain;
	CharToString(plain, message, len);
	string mac, encoded;

	encoded.clear();
	StringSource(key, key.size(), true,
					new HexEncoder(
					new StringSink(encoded)
					)
				); //StringSource

	try
	{
		HMAC<SHA224> hmac(key, key.size());

		StringSource(plain, true, 
			new HashFilter(hmac, 
			new StringSink(mac)
			)
			);
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr<<e.what()<<endl;
		return 0;
		exit(1);
	}

	encoded.clear();
	StringSource(mac, true, 
			new HexEncoder(
			new StringSink(encoded)
			)
			);

	if(hash_len <= encoded.length())
		return -1;
	StringToChar(encoded, hash_message);
	return (int)encoded.length();
}
Exemplo n.º 6
0
unsigned int rcry_encryptInContext(string *input, string *output)
{
	if (target == RCRY_RIJNDAEL)
	{

		try
		{
			CTR_Mode<AES>::Encryption e;
			e.SetKeyWithIV(vault_key, sizeof(vault_key), context->iv);
			StringSource((*input), true,
					new StreamTransformationFilter(e,
							new StringSink((*output))));
		} catch (const CryptoPP::Exception& e)
		{
			cerr << e.what() << endl;
			return 0x44;
		}
	}
	else
	{
		cerr << "Context not implemented! Use RCRY_RIJNAEL INSTEAD!" << endl;
		return 0xFAF;
	}

	return 0;
}
void signature_verify( const string & account_num, string & signature){
  
  RSA::PublicKey publicKey;
  string recovered, message;
  
  // Load public key
  CryptoPP::ByteQueue bytes;
  FileSource file("pubkey.txt", true, new Base64Decoder);
  file.TransferTo(bytes);
  bytes.MessageEnd();
  publicKey.Load(bytes);
  
  // Verify and Recover
  RSASS<PSSR, SHA1>::Verifier verifier(publicKey);
  
  StringSource(signature, true,
               new SignatureVerificationFilter(
                                               verifier,
                                               new StringSink(recovered),
                                               SignatureVerificationFilter::THROW_EXCEPTION |
                                               SignatureVerificationFilter::PUT_MESSAGE
                                               ) // SignatureVerificationFilter
               ); // StringSource
  
  assert(account_num == recovered);
  cout << "Verified signature on message" << endl;
  cout << "Message: " << "'" << recovered << "'" << endl;
  
}
void signature_sign(const string & account_num, string & signature){
  
  // Setup
  string message = account_num;
  RSA::PrivateKey privateKey;
  AutoSeededRandomPool rng;
  
  // Load private key
  CryptoPP::ByteQueue bytes;
  FileSource file("privkey.txt", true, new Base64Decoder);
  file.TransferTo(bytes);
  bytes.MessageEnd();
  privateKey.Load(bytes);
  
  // Sign and Encode
  RSASS<PSSR, SHA1>::Signer signer(privateKey);
  
  // StringSource
  StringSource(message, true,
               new SignerFilter(rng, signer,
                                new StringSink(signature),
                                true // putMessage
                                ) // SignerFilter
               );
  
}
Exemplo n.º 9
0
//signature
string signature_sign(const string & msg){
  
  // Setup
  string message = msg;
  cout << "unsigned message: "<< msg <<endl;
  RSA::PrivateKey privateKey = privkey;
  AutoSeededRandomPool rng;
  
  // Load private key
  /*
  CryptoPP::ByteQueue bytes;
  FileSource file("privkey.txt", true, new Base64Decoder);
  file.TransferTo(bytes);
  bytes.MessageEnd();
  privateKey.Load(bytes);
   */
  
  // Sign and Encode
  RSASS<PSSR, SHA1>::Signer signer(privateKey);
  
  string signature;
  // StringSource
  StringSource(message, true,
               new SignerFilter(rng, signer,
                                new StringSink(signature),
                                true // putMessage
                                ) // SignerFilter
               );
  return signature;
}
Exemplo n.º 10
0
void encrypt_file(string oFile)
{
    // SecByteBlock key(AES::MAX_KEYLENGTH);
    // byte iv[ AES::BLOCKSIZE ];
   
    string ofilename = oFile;
    string outFile = oFile + ".egg";
    string efilename = outFile;   
    //try {
       
        /*********************************\
         \*********************************/
       
    OFB_Mode< AES >::Encryption e1;
    e1.SetKeyWithIV( key, key.size(), iv, sizeof(iv) );
   
    std::ifstream ifile(oFile.c_str(), ios::binary);
    std::ifstream::pos_type size = ifile.seekg(0, std::ios_base::end).tellg();
    ifile.seekg(0, std::ios_base::beg);
   
    string temp;
    temp.resize(size);
    ifile.read((char*)temp.data(), temp.size());
   
    StringSource( temp, true,
                    new StreamTransformationFilter( e1,
                    new FileSink( efilename.c_str() )
                    ) // StreamTransformationFilter
                    ); // StringSource
   
    /*********************************\
     \*********************************/
}
Exemplo n.º 11
0
int QuizDatabase::DecryptToInt(QString &src)
{
    QString t_input;
    int lResult;
    QString temp;
    byte key[AES::DEFAULT_KEYLENGTH] = EncryptionKey;
    byte iv[AES::BLOCKSIZE] = EncryptionKey_2;
    OFB_Mode<AES>::Decryption t_Decrypt;
    t_Decrypt.SetKeyWithIV(key,sizeof(key),iv);
    string t_Str,t_strNonHex,t_strCompletelyEncrypted;
    t_strCompletelyEncrypted = src.toStdString();
    StringSource(t_strCompletelyEncrypted,true,new HexDecoder(new StringSink(t_strNonHex)));
    StringSource(t_strNonHex,true,new StreamTransformationFilter(t_Decrypt,new StringSink(t_Str)));
    t_input = QString::fromStdString(t_Str);
    lResult = t_input.toInt();
    return lResult;
}
Exemplo n.º 12
0
int main(int argc, char* argv[])
{
	std::clock_t start,finish;
	start=clock();
	AutoSeededRandomPool prng;
    
	/* generate key for mac */
	unsigned char key1[16];
	prng.GenerateBlock(key1, sizeof(key1));
	
	/* generate key for encrypt */
	unsigned char key2[AES::DEFAULT_KEYLENGTH];
	prng.GenerateBlock(key2, sizeof(key2));
    
	string encoded1,encoded2;
	encoded1.clear();
	encoded2.clear();
	
	StringSource(key1, sizeof(key1), true,
                 new HexEncoder(
                                new StringSink(encoded1)
                                )
                 );
	cout << "key for mac is:" << key1 <<endl;
	cout << "hexadecimal key for mac is: " << encoded1 << endl;
	
	StringSource(key2, sizeof(key2), true,
                 new HexEncoder(
                                new StringSink(encoded2)
                                )
                 );
	cout << "key for encrypt is:" << key2 <<endl;
	cout << "hexadecimal key for encrypto is: " << encoded2 << endl;
    
    
    std::fstream f("key.txt",std::ios::out);
    f<<encoded1<<endl;
    f<<encoded2<<endl;
    f.close();
    
    finish=clock();
    cout<< "the keygen running time is " << difftime(finish,start) << " ms" << endl;
    
    return 0;
}
Exemplo n.º 13
0
std::string Encryptor::encrypt(const std::string& word)
		throw (CryptoPP::Exception) {
	std::string cipher;

	ECB_Mode<AES>::Encryption e;
	e.SetKey(key, AES_SIZE);

	// The StreamTransformationFilter adds padding
	//  as required. ECB and CBC Mode must be padded
	//  to the block size of the cipher.
	StringSource(word, true,
			new StreamTransformationFilter(e, new StringSink(cipher)) // StreamTransformationFilter
	); // StringSource

	std::string encoded;
	StringSource(cipher, true, new HexEncoder(new StringSink(encoded))); // StringSource
	return encoded;

}
Exemplo n.º 14
0
unsigned int rcry_toBase64Converter(byte *binary, string *base64, bool print)
{
	if (base64 == NULL) return 0xB0;

	// TODO: Figure out WHY?
	(*base64).clear();
	StringSource(binary, sizeof(binary) * 2, true,
			new HexEncoder(new StringSink((*base64))));

	if (print) cout << "=> " << (*base64) << endl;
	return 0;
}
Exemplo n.º 15
0
bool VerifyMessage(const ECDSA<ECP, SHA1>::PublicKey& key, 
				const string& message, const string& signature)
{
	bool result = false;

	StringSource(signature + message, true,
		new SignatureVerificationFilter(
		ECDSA<ECP, SHA1>::Verifier(key),
		new ArraySink((byte*)&result, sizeof(result))
		) // SignatureVerificationFilter
		);

	return result;
}
Exemplo n.º 16
0
int Cryption::decrypt(int fd){

  string IVContents, decryptionKey, decodedKey, decodedIV;

  IVContents = read(fd);
  string encodedIV = IVContents.substr(0,32);
  string FileContents = IVContents.substr(encodedIV.length());

  //Decoding the Key
  decryptionKey = getKey();
  StringSource(decryptionKey, true, new HexDecoder(new StringSink(decodedKey)));
  const byte* dbyteKey = (const byte*) decodedKey.data();

  //Decoding the IV
  StringSource(encodedIV, true, new HexDecoder(new StringSink(decodedIV)));
  const byte* IV = (const byte*) decodedIV.data();

  string decryptedContents;
  //Decrypting actual file
  try{
    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV(dbyteKey, CryptoPP::AES::DEFAULT_KEYLENGTH, IV);
    StringSource de(FileContents, true, new StreamTransformationFilter(d, new StringSink (decryptedContents)));
  }
  catch(const CryptoPP::Exception& e){
    cerr<<e.what()<<endl;
    exit(1);
  }


  string DContents = decryptedContents;
  const char *OriginalContents = DContents.c_str();
  ssize_t WriteLength = pwrite(fd, OriginalContents, DContents.length(), 0);
  ftruncate(fd, DContents.length());

  return 0;
}
Exemplo n.º 17
0
int Cryption::encrypt(int fd){
  AutoSeededRandomPool prng;
  string encryptedBytes, encodedKey, decodedKey;

  encodedKey = getKey();
  cout<<"Encode: "<<encodedKey<<endl;
  StringSource(encodedKey, true, new HexDecoder(new StringSink(decodedKey)));
  cout<<"Decode: "<<decodedKey<<endl;
  const byte* ebyteKey = (const byte*) decodedKey.data();

  string encodedIV;
  //createIV
  byte IVBytes[AES::BLOCKSIZE];
  prng.GenerateBlock(IVBytes, sizeof(IVBytes));
  StringSource(IVBytes, sizeof(IVBytes), true, new HexEncoder(new StringSink(encodedIV)));

  encryptedBytes = read(fd);

  string encryptedContents;
  //Encrypting the file contents
  try{
    CBC_Mode< AES >::Encryption e;
    e.SetKeyWithIV(ebyteKey, CryptoPP::AES::DEFAULT_KEYLENGTH, IVBytes);
    StringSource file(encryptedBytes, true, new StreamTransformationFilter(e,new StringSink(encryptedContents)));
  }
  catch( const CryptoPP::Exception& e ){
    cerr << e.what() << endl;
    exit(1);
  }

  string output = encodedIV + encryptedContents;
  const char *bufContents = output.c_str();
  ssize_t WriteLength = pwrite(fd, bufContents, output.length(), 0);
  ftruncate(fd, output.length());
  
  return 0;
}
Exemplo n.º 18
0
std::string Encryptor::decrypt(const std::string& word)
		throw (CryptoPP::Exception) {
	ECB_Mode<AES>::Decryption d;
	d.SetKey(key, AES_SIZE);

	std::string cipher;
	StringSource(word, true, new HexDecoder(new StringSink(cipher)));

	std::string recovered;
	StringSource s(cipher, true,
			new StreamTransformationFilter(d, new StringSink(recovered)) // StreamTransformationFilter
			); // StringSource

	return recovered;
}
Exemplo n.º 19
0
bool SignMessage(const ECDSA<ECP, SHA1>::PrivateKey& key, const string& message, 
			string& signature)
{
	AutoSeededRandomPool prng;

	signature.erase();

	StringSource(message, true,
		new SignerFilter(prng,
		ECDSA<ECP, SHA1>::Signer(key),
		new StringSink(signature)
		)	//SignerFilter
		);  //StringSource
	return !signature.empty();
}
Exemplo n.º 20
0
int main(int argc, char *argv[])
{
    if (argc != 3){
        std::cout << "Usage: ch7 <input_file> <key>" << std::endl;
        return -1;
    }
    std::string filename {argv[1]};
    std::string key {argv[2]};
    std::string decoded, line, output;
    std::ifstream input {filename};

    if (key.size() != 16){
        std::cout << "The key must be 16 bytes long." << std::endl;
        exit(-1);
    }

    if (input.is_open()){
        while (std::getline(input, line)){
            decoded += base64_decrypt(line);
        }
    }

    byte buffer_key[16];
    int i = 0;
    for (char c : key){
        buffer_key[i] = c;
        i++;
    }

    ECB_Mode<AES>::Decryption dec;
    dec.SetKey(buffer_key, 16);

    StringSource(decoded, true,
            new StreamTransformationFilter(dec,
                new StringSink(output)
            )
    );

    std::cout << output << std::endl;

    return 0;
}
Exemplo n.º 21
0
string CRSAEncryptDecrypt::decrypt(string stringToDecrypt, RSA::PrivateKey privateKey)
{
   LOG4CPLUS_INFO(msLogger, "decrypt()");

   AutoSeededRandomPool rng;
   string recovered;

   LOG4CPLUS_INFO(msLogger, "Input string to decrypt: " + stringToDecrypt);

   ////////////////////////////////////////////////
   // Decryption
   RSAES_OAEP_SHA_Decryptor d(privateKey);

   StringSource(stringToDecrypt, true,
      new PK_DecryptorFilter(rng, d,
         new StringSink(recovered)
      ) // PK_DecryptorFilter
   ); // StringSource

   LOG4CPLUS_INFO(msLogger, "Output decrypted string: " + recovered);

   return recovered;
}
Exemplo n.º 22
0
string CRSAEncryptDecrypt::encrypt(string stringToEncrypt, RSA::PublicKey publicKey)
{
   LOG4CPLUS_INFO(msLogger, "encrypt()");

   AutoSeededRandomPool rng;
   string cipher;

   LOG4CPLUS_INFO(msLogger, "Input string to encrypt: " + stringToEncrypt);

   ////////////////////////////////////////////////
   // Encryption
   RSAES_OAEP_SHA_Encryptor e(publicKey);

   StringSource(stringToEncrypt, true,
       new PK_EncryptorFilter(rng, e,
       new StringSink(cipher)
    ) // PK_EncryptorFilter
   ); // StringSource

   LOG4CPLUS_INFO(msLogger, "Output encrypted string: " + string(cipher.c_str()));

   return cipher;
}
// fill txdescr with address, amount, timestamp, as strings
bool decryptblindtxt(std::string msg64,
                       std::string twofa,
                       std::vector<std::string> &txdescr) {

        std::string decoded, recovered;
        StringSource(msg64, true,
                new Base64Decoder(
                           new StringSink(decoded))); 

        // AES
        byte myiv[IV_SIZE];
        for (int idx=0; idx<IV_SIZE; idx++) {
            myiv[idx] = decoded[idx];
        }

        // needed to salt key derivation
        std::string iv_str;
        iv_str = decoded.substr(0, IV_SIZE);

	byte mykey[KEY_SIZE];
        SHAKD(twofa, iv_str, mykey);

        std::string ctxt = decoded.substr(IV_SIZE, decoded.size() - IV_SIZE);

        try
        {

            GCM< AES >::Decryption decryptor;
            decryptor.SetKeyWithIV(mykey, sizeof(mykey),
                                       myiv, sizeof(myiv));

            /* CGM ***************************************************/
            AuthenticatedDecryptionFilter df(decryptor,
                new StringSink(recovered),
                AuthenticatedDecryptionFilter::DEFAULT_FLAGS,
                TAG_SIZE
            ); // AuthenticatedDecryptionFilter

            StringSource(ctxt, true,
                new Redirector(df)
            ); // StringSource

            // If the object does not throw, here's the only
            //  opportunity to check the data's integrity
            bool b = df.GetLastResult();
            if (!b) {
                 return false;
             }
        }

        catch(const CryptoPP::Exception& e) {
            return false;
        }

        boost::split(txdescr, recovered, boost::is_any_of(","));

        // might as well check
        if (txdescr.size() != 3) {
          return false;
        }

	return true;
}
Exemplo n.º 24
0
int main(int argc, char* argv[])
{
    std::clock_t start,finish;
    start=clock();
    
    mapp['0'] = 0;
    mapp['1'] = 1;
    mapp['2'] = 2;
    mapp['3'] = 3;
    mapp['4'] = 4;
    mapp['5'] = 5;
    mapp['6'] = 6;
    mapp['7'] = 7;
    mapp['8'] = 8;
    mapp['9'] = 9;
    mapp['a'] = 10;
    mapp['b'] = 11;
    mapp['c'] = 12;
    mapp['d'] = 13;
    mapp['e'] = 14;
    mapp['f'] = 15;
    
    //SecByteBlock key1(16);
    //SecByteBlock key2(AES::DEFAULT_KEYLENGTH);
    unsigned char key1[16];
    unsigned char key2[AES::DEFAULT_KEYLENGTH];
    
    /* generate iv */
   // AutoSeededRandomPool prng;
    //unsigned char iv[AES::BLOCKSIZE];
    //prng.GenerateBlock(iv, sizeof(iv));
    //memset( iv, 0x00, CryptoPP::AES::BLOCKSIZE );
    /*std::fstream fiv("iv.txt",std::ios::out);
     fiv<<iv;
     fiv.close();
     cout << "iv is: " << iv << endl;*/
    
    string encoded1,encoded2,mac,plain,plainlen,cipher;
    
    encoded1.clear();
    encoded2.clear();
    
    std::fstream f(argv[1],std::ios::in);
    f>>encoded1;
    f>>encoded2;
    f.close();
    
    /* read in keys */
    for(int i=0,j=0;i<16*2;){
        key1[j]=mapp[encoded1[i]]*16+mapp[encoded1[i+1]];
        i+=2;
        j++;
    }
    cout << "hexadecimal key for mac is: " << encoded1 << endl;

    
    for(int i=0,j=0;i<AES::DEFAULT_KEYLENGTH*2;){
        key2[j]=mapp[encoded2[i]]*16+mapp[encoded2[i+1]];
        i+=2;
        j++;
    }
    cout << "hexadecimal key for encrypt: " << encoded2 << endl;
  
    
    /*read in plaintext*/
    std::fstream fplain(argv[2],std::ios::in);
    fplain>>plainlen;
    fplain>>plain;
    fplain.close();
    cout << "the length of plain is: " << plainlen << endl;
    cout << "plaint is: " << plain << endl;
    
    /* encrypt */
    try
	{
	    CBC_Mode< AES >::Encryption e;
	    unsigned char ivv[AES::BLOCKSIZE]="0";
	    e.SetKeyWithIV(key2, sizeof(key2), ivv);
        
	    StringSource(plain, true,
                     new StreamTransformationFilter(e,
                                                    new StringSink(cipher)
                                                    ) // StreamTransformationFilter
                     ); // StringSource
	}
	catch(const CryptoPP::Exception& e)
	{
	    cerr << e.what() << endl;
	    exit(1);
	}
    
    // print
    encoded2.clear();
    StringSource(cipher, true,
                 new HexEncoder(
                                new StringSink(encoded2)
                                ) // HexEncoder
                 ); // StringSource
    cout << "hexadecimal cipher text is: " << encoded2 << endl;
    cout << "cipher text is: " << cipher << endl;
    
    time_t ltime;
    time(&ltime);
    char tmp[20];
    sprintf(tmp, "%ld",ltime);
    string s=tmp;
    cout << "the time is: " << s << endl;
    
    try
    {
        CBC_MAC< CryptoPP::AES > cbcmac(key1, sizeof(key1));
        
        StringSource(cipher+s, true,
                     new HashFilter(cbcmac,
                                    new StringSink(mac)
                                    ) // HashFilter
                     ); // StringSource
    }
    catch(const CryptoPP::Exception& e)
    {
        cerr << e.what() << endl;
        exit(1);
    }
    
    encoded1.clear();
    StringSource(mac, true,
                 new HexEncoder(
                                new StringSink(encoded1)
                                ) // HexEncoder
                 ); // StringSource
    
    cout << "hexadecimal cbcmac: " << encoded1 << endl;
    cout << "cbcmac: " << mac << endl;
    
    std::fstream fcipher("ciphertext.txt",std::ios::out);
    fcipher << encoded2.length() <<endl;
    fcipher << s << endl;
    fcipher << encoded1 << endl;
    fcipher << encoded2 <<endl;
    fcipher.close();
	
    finish=clock();
    cout<< "the encrypto running time is " << difftime(finish,start) << " ms" << endl;
    
    return 0;
    
}
Exemplo n.º 25
0
int main(int argc, char* argv[])
{
	AutoSeededRandomPool prng;

	byte key[AES::DEFAULT_KEYLENGTH];
	prng.GenerateBlock(key, sizeof(key));

	byte iv[AES::BLOCKSIZE];
	prng.GenerateBlock(iv, sizeof(iv));

	string plain = "CBC Mode Test";
	string cipher, encoded, recovered;

	/*********************************\
	\*********************************/

	// Pretty print key
	encoded.clear();
	StringSource(key, sizeof(key), true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "key: " << encoded << endl;

	// Pretty print iv
	encoded.clear();
	StringSource(iv, sizeof(iv), true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "iv: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		cout << "plain text: " << plain << endl;

		CBC_Mode< AES >::Encryption e;
		e.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter removes
		//  padding as required.
		StringSource s(plain, true, 
			new StreamTransformationFilter(e,
				new StringSink(cipher)
			) // StreamTransformationFilter
		); // StringSource

#if 0
		StreamTransformationFilter filter(e);
		filter.Put((const byte*)plain.data(), plain.size());
		filter.MessageEnd();

		const size_t ret = filter.MaxRetrievable();
		cipher.resize(ret);
		filter.Get((byte*)cipher.data(), cipher.size());
#endif
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// Pretty print
	encoded.clear();
	StringSource(cipher, true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "cipher text: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		CBC_Mode< AES >::Decryption d;
		d.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter removes
		//  padding as required.
		StringSource s(cipher, true, 
			new StreamTransformationFilter(d,
				new StringSink(recovered)
			) // StreamTransformationFilter
		); // StringSource

#if 0
		StreamTransformationFilter filter(d);
		filter.Put((const byte*)cipher.data(), cipher.size());
		filter.MessageEnd();

		const size_t ret = filter.MaxRetrievable();
		recovered.resize(ret);
		filter.Get((byte*)recovered.data(), recovered.size());
#endif

		cout << "recovered text: " << recovered << endl;
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	return 0;
}
Exemplo n.º 26
0
std::string dec(std::string ciphertext) {

	//AutoSeededRandomPool prng;

	//byte key[AES::MAX_KEYLENGTH];

	//byte iv[AES::MAX_BLOCKSIZE];

	std::string cipher, encoded, recovered;


	// testing decodeing -- by ghamdan 

	// Pretty print
	encoded.clear();
	StringSource(ciphertext, true,
		new HexDecoder(
			new StringSink(cipher)
		) // HexEncoder
	); // StringSource

	//// Pretty print key
	//encoded.clear();
	//StringSource(key, sizeof(key), true,
	//	new HexEncoder(
	//		new StringSink(encoded)
	//	) // HexEncoder
	//); // StringSource


	//// Pretty print iv
	//encoded.clear();
	//StringSource(iv, sizeof(iv), true,
	//	new HexEncoder(
	//		new StringSink(encoded)
	//	) // HexEncoder
	//); // StringSource


	/*********************************\
	\*********************************/



	try
	{
		CBC_Mode< AES >::Decryption d;
		d.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter removes
		//  padding as required.
		StringSource s(cipher, true,
			new StreamTransformationFilter(d,
				new StringSink(recovered)
			) // StreamTransformationFilter
		); // StringSource

#if 0
		StreamTransformationFilter filter(d);
		filter.Put((const byte*)cipher.data(), cipher.size());
		filter.MessageEnd();

		const size_t ret = filter.MaxRetrievable();
		recovered.resize(ret);
		filter.Get((byte*)recovered.data(), recovered.size());
#endif

	}
	catch (const CryptoPP::Exception& e)
	{
		std::cerr << e.what() << std::endl;
		exit(1);
	}

	/*********************************\
	\*********************************/
	
	return recovered;
}
Exemplo n.º 27
0
int main(int argc, char* argv[])
{
  string encoded_mac;
  string line;
  ifstream encrypted_file(argv[1]);
  int count=0;
  string str_cipher, str_fkey, cipher;
  //encrypted_file.read(encoded_mac,64-1);
  if(encrypted_file.is_open())
    getline(encrypted_file,encoded_mac);
  while(!encrypted_file.eof()){
    getline(encrypted_file,str_cipher);
  }
  encrypted_file.close();


  StringSource(argv[2], true, new HexDecoder(
                                             new StringSink(str_fkey)
                                             )
               );

  byte fkey[str_fkey.length()];
  for (int i=0;i<=str_fkey.length();i++)
    fkey[i]=(byte)str_fkey[i];

  byte iv[AES::BLOCKSIZE]; // 16 bytes
  iv[0] = 0;

  string encoded, recovered;
  StringSource(str_cipher, true, new HexDecoder(
                                                new StringSink(cipher))
               );

  SecByteBlock mac_key(16);
  for (int i=0;i<sizeof(mac_key);i++){
    mac_key[i]=1;
  }
  string mac;

  // This step performs AES decryption

  try
    {
      CTR_Mode< AES >::Decryption d;
      d.SetKeyWithIV(fkey, sizeof(fkey), iv);

      // The StreamTransformationFilter removes
      //  padding as required.

      StringSource s(cipher, true,
                     new StreamTransformationFilter(d,
                                                    new StringSink(recovered)
                                                    )
                     ); // StringSource

      cout << "recovered text: " << recovered << endl;
    }
  catch(const CryptoPP::Exception& e)
    {
      cerr << e.what() << endl;
      exit(1);
    }


  StringSource(encoded_mac, true,
               new HexDecoder(
                              new StringSink(mac)
                              ) // HexEncoder
               );

  try
    {
      HMAC< SHA256 > hmac(mac_key, mac_key.size());
      const int flags = HashVerificationFilter::THROW_EXCEPTION | HashVerificationFilter::HASH_AT_END;
      StringSource(recovered + mac, true,
                   new HashVerificationFilter(hmac, NULL, flags)
                   ); // StringSource
      cout<<endl<<endl;
      cout << "HMAC has been implemented and plaintext message is verified" << endl;
    }
  catch(const CryptoPP::Exception& e)
    {
      cerr << e.what() << endl;
      exit(1);
    }

  return 0;
}
Exemplo n.º 28
0
int main(int argc, char* argv[])
{
    AutoSeededRandomPool prng;

    byte key[AES::DEFAULT_KEYLENGTH];
    prng.GenerateBlock(key, sizeof(key));

    byte iv[AES::BLOCKSIZE];
    prng.GenerateBlock(iv, sizeof(iv));

    // string plain = "CBC Mode Test";
    string encoded;

    string file_out("");


    char file_path[256];
    int action;

    // default initialization
    strcpy(file_path, "test.dat");
    action = 2;
    while(1)
    {

        static struct option long_option[] =
        {
            {"file", required_argument, 0, 'a'},
            {"action", required_argument, 0, 'b'},
            {"out", required_argument, 0, 'c'},
            {"help", no_argument, 0, 'i'},
            {"key", required_argument, 0, 'd'},
            {"iv", required_argument, 0, 'e'},
            {0, 0, 0, 0}
        };

#define HELP \
    printf("Usage: \n ./crypto_cbc_test [OPTIONS] \n"); \
    printf("    file:            file for doing encryption \n"); \
    printf("    action:          0: encryption, 1: decryption, 2: both Default 2 \n"); \
    printf("    out:             write out file, default no \n"); \
    printf("    key:             key in hex string, if it is not specified, automatically generate \n"); \
    printf("    iv:              Initialization vector, if it is not specified, automatically generate \n"); \
    printf("    help:            help  \n");


        int option_index = 0;
        int rc = getopt_long(argc, argv, "a:b:c:d:e:f:g:h:i", long_option, &option_index);

        if (rc == -1)
            break;

        switch(rc)
        {
        case 'a':
            printf("[Debug] file : %s \n", optarg);
            sprintf(file_path, optarg);
            break;
        case 'b':
            printf("[Debug] action: %s \n", optarg);
            action = atoi(optarg);
            break;
        case 'c':
            printf("[Debug] out: %s \n", optarg);
            file_out.append(optarg);
            break;
        case 'd':
            printf("[Debug] key: %s \n", optarg);
            for (int i = 0; i < 16; i++)
                key[i] = i;
            /*
            CryptoPP::ArraySink ar(key, sizeof(key));
            StringSource(new string(optarg), true, new CryptoPP::HexDecoder( ar ));
            */
            break;
        case 'e':
            printf("[Debug] iv: %s \n", optarg);
            for (int i = 0; i < 16; i++)
                iv[i] = i;

            break;
        case 'i':
            HELP
                    exit(1);
        default:
            printf("invalid option \n");
            exit(1);
        }

    }

    /*********************************\
    \*********************************/

    // Pretty print key
    encoded.clear();
    StringSource(key, sizeof(key), true,
                 new HexEncoder(
                     new StringSink(encoded)
                     ) // HexEncoder
                 ); // StringSource
    cout << "key: " << encoded << endl;

    // Pretty print iv
    encoded.clear();
    StringSource(iv, sizeof(iv), true,
                 new HexEncoder(
                     new StringSink(encoded)
                     ) // HexEncoder
                 ); // StringSource
    cout << "iv: " << encoded << endl;

    /*********************************\
    \*********************************/




    char file_buff[2*1024];


    std::ifstream infile(file_path, std::ifstream::binary);

    std::ofstream outfile;


    if (file_out.length() > 0)
        outfile.open(file_out.c_str());

    if (action == 0)
        cout << "[Encryption]:  ";
    else if (action == 1)
        cout << "[Decryption]:  ";
    else if (action == 2)
        cout << "[Encryption|Decryption]:  ";



    cout  << file_path <<  "size: " << fileSize(file_path) << " (Bytes)" << endl;

    timeCounter tc(true);

    CBC_Mode< AES >::Encryption e;
    e.SetKeyWithIV(key, sizeof(key), iv);


    CBC_Mode< AES >::Decryption d;
    d.SetKeyWithIV(key, sizeof(key), iv);


    // testing
    if (action == 0)
    { // encryption
        CryptoPP::FileSource file(file_path, true,
                                  new StreamTransformationFilter(e,
                                                                 new CryptoPP::FileSink(file_out.c_str())
                                                                 ) // StreamTransformationFilter
                                  ); // StringSource
    } else if (action == 1)
    { // decryption
        CryptoPP::FileSource file(file_path, true,
                                  new StreamTransformationFilter(d,
                                                                 new CryptoPP::FileSink(file_out.c_str())
                                                                 ) // StreamTransformationFilter
                                  ); // StringSource
    }

    return 0;

    int count;
    int acc_count = 0;
    while ((count = infile.read(file_buff, 16).gcount()) > 0)
    {
        string cipher, recovered;

        std::string plain(file_buff, count);
        acc_count += count;

        if (action == 0 || action == 2)
        {

            //cout << "data:" << plain << endl;
            try
            {

                // The StreamTransformationFilter removes
                //  padding as required.

                StringSource s(plain, true,
                               new StreamTransformationFilter(e,
                                                              new StringSink(cipher)
                                                              ) // StreamTransformationFilter
                               ); // StringSource

#if 0
                StreamTransformationFilter filter(e);
                filter.Put((const byte*)plain.data(), plain.size());
                filter.MessageEnd();

                const size_t ret = filter.MaxRetrievable();
                cipher.resize(ret);
                filter.Get((byte*)cipher.data(), cipher.size());
#endif
            }
            catch(const CryptoPP::Exception& e)
            {
                cerr << e.what() << endl;
                cerr << "ERRO 1" << endl;
                exit(1);
            }
        }

        if (action == 1 || action == 2)
        {
            if (action == 1) // just do decryption
                cipher = plain;



            /*********************************\
    \*********************************/
#if 0
            // Pretty print
            encoded.clear();
            StringSource(cipher, true,
                         new HexEncoder(
                             new StringSink(encoded)
                             ) // HexEncoder
                         ); // StringSource
            // cout << "cipher text: " << encoded << endl;
#endif

            /*********************************\
    \*********************************/

            try
            {

                // The StreamTransformationFilter removes
                //  padding as required.
                StringSource s(cipher, true,
                               new StreamTransformationFilter(d,
                                                              new StringSink(recovered)
                                                              ) // StreamTransformationFilter
                               ); // StringSource

#if 0
                StreamTransformationFilter filter(d);
                filter.Put((const byte*)cipher.data(), cipher.size());
                filter.MessageEnd();

                const size_t ret = filter.MaxRetrievable();
                recovered.resize(ret);
                filter.Get((byte*)recovered.data(), recovered.size());
#endif

                // cout << "recovered text: " << recovered << endl;
            }
            catch(const CryptoPP::Exception& e)
            {
                cerr << e.what() << endl;
                cout << "ERROR";
                exit(1);
            }

        }


        cout << "Size: " << acc_count << "," << count << ", " << cipher.size() << endl;

        if (outfile.is_open())
            if (action == 0)
                outfile.write(cipher.c_str(), cipher.size());
            else
                outfile.write(recovered.c_str(), recovered.size());

    }

    tc.Stop();
    printf("Elapsed: %s\n", tc.ToString().c_str());

    if (outfile.is_open())
        outfile.close();

    /*********************************\
    \*********************************/

    return 0;
}
Exemplo n.º 29
0
int benchmark()
{
	AutoSeededRandomPool prng;

	byte key[AES::DEFAULT_KEYLENGTH];
	prng.GenerateBlock(key, sizeof(key));


	byte iv[AES::BLOCKSIZE];
	prng.GenerateBlock(iv, sizeof(iv));


	byte *final_iv = (byte*) malloc(sizeof(iv));
	memcpy(final_iv, iv, sizeof(iv));


	string plain = "CTR Mode Test";
	string cipher, encoded, recovered;

	/*********************************\
	\*********************************/

	// Pretty print key
	encoded.clear();
	StringSource(key, sizeof(key), true, new HexEncoder(new StringSink(encoded)) // HexEncoder
			);// StringSource
	cout << "key: " << encoded << endl;

	// Pretty print iv
	encoded.clear();
	StringSource(final_iv, sizeof(iv), true, new HexEncoder(new StringSink(encoded)) // HexEncoder
			);// StringSource
	cout << "iv: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		cout << "plain text: " << plain << endl;

		CTR_Mode<AES>::Encryption e;
		e.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter adds padding
		//  as required. ECB and CBC Mode must be padded
		//  to the block size of the cipher.
		StringSource(plain, true,
				new StreamTransformationFilter(e, new StringSink(cipher)) // StreamTransformationFilter
						);// StringSource
	} catch (const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// Pretty print
	encoded.clear();
	StringSource(cipher, true, new HexEncoder(new StringSink(encoded)) // HexEncoder
			);// StringSource
	cout << "cipher text: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		CTR_Mode<AES>::Decryption d;
		d.SetKeyWithIV(key, sizeof(key), iv);

		// The StreamTransformationFilter removes
		//  padding as required.
		StringSource s(cipher, true,
				new StreamTransformationFilter(d, new StringSink(recovered)) // StreamTransformationFilter
						);// StringSource

		cout << "recovered text: " << recovered << endl;
	} catch (const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	return 0;
}
Exemplo n.º 30
0
int main(int argc, char* argv[])
{
	AutoSeededRandomPool prng;

	byte key[AES::DEFAULT_KEYLENGTH] = {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f};
	//prng.GenerateBlock(key, sizeof(key));  /* For pseudo random key generation */

	byte plain[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff};
	string cipher, encoded, recovered;

	/**************************************************************************************
	NOTE:
	***************************************************************************************
	-- plaintext can also be changed to type string of 16 bytes i.e. 16 characters
	-- Only Decryption can also be performed on the same basis
	****************************************************************************************/

	if(sizeof(key) != BLOCK_SIZE_BYTES || sizeof(plain) != BLOCK_SIZE_BYTES)
	{
		cerr << "Either plainText or Key has improper block size" << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// print key
	encoded.clear();
	StringSource(key, sizeof(key), true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	cout << "key: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		cout << "plain text: " << plain << endl;

		ECB_Mode< AES >::Encryption e;
		e.SetKey(key, sizeof(key));

		StringSource ss(plain, sizeof(plain), true, 
			new StreamTransformationFilter(e,
				new StringSink(cipher)//,
					//BlockPaddingScheme::NO_PADDING
			) // StreamTransformationFilter      
		); // StringSource
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	// print Cipher Text
	encoded.clear();
	StringSource(cipher, true,
		new HexEncoder(
			new StringSink(encoded)
		) // HexEncoder
	); // StringSource
	encoded.resize(16*2);
	cout << "cipher text: " << encoded << endl;

	/*********************************\
	\*********************************/

	try
	{
		ECB_Mode< AES >::Decryption d;
		d.SetKey(key, sizeof(key));

		StringSource s(cipher, true, 
			new StreamTransformationFilter(d,
				new StringSink(recovered)
			) // StreamTransformationFilter
		); // StringSource

		cout << "recovered text: " << recovered << endl;
	}
	catch(const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		exit(1);
	}

	/*********************************\
	\*********************************/

	return 0;
}