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
               );
  
}
void Sign(string str){
	// string strContents = "A message to be signed";
	string strContents = str;
	//FileSource("tobesigned.dat", true, new StringSink(strContents));
	
	AutoSeededRandomPool rng;
	
	//Read private key
	CryptoPP::ByteQueue bytes;
	FileSource file("privkey.txt", true, new Base64Decoder);
	file.TransferTo(bytes);
	bytes.MessageEnd();
	RSA::PrivateKey privateKey;
	privateKey.Load(bytes);

	//Sign message
	RSASSA_PKCS1v15_SHA_Signer privkey(privateKey);
	SecByteBlock sbbSignature(privkey.SignatureLength());
	privkey.SignMessage( rng, (byte const*) strContents.data(), strContents.size(), sbbSignature);

	//Save result
	FileSink sink("message.dat"); //c
	sink.Put((byte const*) strContents.data(), strContents.size());
	FileSink sinksig("cipher.dat"); //m
	sinksig.Put(sbbSignature, sbbSignature.size());
}
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;
  
}
Example #4
0
void SaveKey(const std::string& filename, const Key& key) {
  CryptoPP::ByteQueue queue;
  key.Save(queue);
  CryptoPP::FileSink file(filename.c_str());
  
  queue.CopyTo(file);
  file.MessageEnd();
}
Example #5
0
inline std::string RSAKeyToString(const typename isRSAKey<T>::type& key) {
    CryptoPP::ByteQueue queue;
    key.Save(queue);

    std::string result;
    CryptoPP::StringSink sink(result);
    queue.CopyTo(sink);
    return result;
}
string SignLicense(AutoSeededRandomPool &rng, string strContents, string pass)
{
	//Read private key
	string encPrivKey;
	StringSink encPrivKeySink(encPrivKey);
	FileSource file("secondary-privkey-enc.txt", true, new Base64Decoder);
	file.CopyTo(encPrivKeySink);

	//Read initialization vector
	byte iv[AES::BLOCKSIZE];
	CryptoPP::ByteQueue bytesIv;
	FileSource file2("secondary-privkey-iv.txt", true, new Base64Decoder);
	file2.TransferTo(bytesIv);
	bytesIv.MessageEnd();
	bytesIv.Get(iv, AES::BLOCKSIZE);

	//Hash the pass phrase to create 128 bit key
	string hashedPass;
	RIPEMD128 hash;
	StringSource(pass, true, new HashFilter(hash, new StringSink(hashedPass)));

	//Decrypt private key
	byte test[encPrivKey.length()];
	CFB_Mode<AES>::Decryption cfbDecryption((const unsigned char*)hashedPass.c_str(), hashedPass.length(), iv);
	cfbDecryption.ProcessData(test, (byte *)encPrivKey.c_str(), encPrivKey.length());
	StringSource privateKeySrc(test, encPrivKey.length(), true, NULL);

	//Decode key
	RSA::PrivateKey privateKey;
	privateKey.Load(privateKeySrc);

	//Sign message
	RSASSA_PKCS1v15_SHA_Signer privkey(privateKey);
	SecByteBlock sbbSignature(privkey.SignatureLength());
	privkey.SignMessage(
		rng,
		(byte const*) strContents.data(),
		strContents.size(),
		sbbSignature);

	//Save result
	string out;
	Base64Encoder enc(new StringSink(out));
	enc.Put(sbbSignature, sbbSignature.size());
	enc.MessageEnd();

	return out;
}
Example #7
0
CryptoPP::RSA::PublicKey cKeysStorage::loadPubFile(std::string pPubKey)
{
	std::string fileName(pPubKey);
	//fileName += ".pub";
	std::cout << "Public key file: " << fileName << std::endl;
	/*std::string line;
	std::ifstream input(fileName);
	for (int i = 0; i < 3; i++)
	{
		input >> line;
		//std::cout << line << " ";
		input >> line;
		//std::cout << line << std::endl;
	}
	std::cout << "Load rsa data" << std::endl;
	input >> line; // END
	*/
	// load rsa data
	//char byte;
	
	//from .pub to tmp
	/*std::ofstream tmpFile("tmp", std::ios::trunc);
	
	while (!input.eof())
	{
		input >> std::noskipws >> byte;
		std::cout << byte;
		tmpFile << byte;
	}
	
	tmpFile.close();*/
	
	//Read public key
	CryptoPP::ByteQueue bytes;
	FileSource file(fileName.c_str(), true, new Base64Decoder);
	file.TransferTo(bytes);
	bytes.MessageEnd();
	RSA::PublicKey pubKey;
	pubKey.Load(bytes);
	
	std::cout << "end of loadPubFile" << std::endl;
	
	return pubKey;
}
int VerifyLicense(string signedTxt, string sigIn, string pubKeyEnc)
{
    //Read public key
    CryptoPP::ByteQueue bytes;
    StringSource file(pubKeyEnc, true, new Base64Decoder);
    file.TransferTo(bytes);
    bytes.MessageEnd();
    RSA::PublicKey pubKey;
    pubKey.Load(bytes);

    RSASSA_PKCS1v15_SHA_Verifier verifier(pubKey);

    //Read signed message
    CryptoPP::ByteQueue sig;
    StringSource sigFile(sigIn, true, new Base64Decoder);
    string sigStr;
    StringSink sigStrSink(sigStr);
    sigFile.TransferTo(sigStrSink);

    string combined(signedTxt);
    combined.append(sigStr);

    //Verify signature
    try
    {
        StringSource(combined, true,
                     new SignatureVerificationFilter(
                         verifier, NULL,
                         SignatureVerificationFilter::THROW_EXCEPTION
                     )
                    );
    }
    catch(SignatureVerificationFilter::SignatureVerificationFailed &err)
    {
        cout << err.what() << endl;
        return 0;
    }
    return 1;
}
Example #9
0
string RSA_Encryption(const string & plain){
  //Encryption
  AutoSeededRandomPool rng;
  
  //Load public key
  CryptoPP::RSA::PublicKey pubKey;
  CryptoPP::ByteQueue bytes;
  FileSource file("pubkey.txt", true, new Base64Decoder);
  file.TransferTo(bytes);
  bytes.MessageEnd();
  pubKey.Load(bytes);
  
  
  RSAES_OAEP_SHA_Encryptor e(pubKey);
  
  string cipher;
  StringSource ss1(plain, true,
                   new PK_EncryptorFilter(rng, e,
                                          new StringSink(cipher)
                                          ) // PK_EncryptorFilter
                   ); // StringSource
  return cipher;
}
Example #10
0
void Verify(){
	//Read public key
	CryptoPP::ByteQueue bytes;
	FileSource file("pubkey.txt", true, new Base64Decoder);
	file.TransferTo(bytes);
	bytes.MessageEnd();
	RSA::PublicKey pubKey;
	pubKey.Load(bytes);

	RSASSA_PKCS1v15_SHA_Verifier verifier(pubKey);

	//Read signed message
	string signedTxt;
	FileSource("message.dat", true, new StringSink(signedTxt)); //c
	string sig;
	FileSource("cipher.dat", true, new StringSink(sig)); //m

	string combined(signedTxt);
	combined.append(sig);

	//Verify signature
	try
	{
		StringSource(combined, true,
			new SignatureVerificationFilter(
				verifier, NULL,
				SignatureVerificationFilter::THROW_EXCEPTION
		   )
		);
		// cout << "Signature OK" << endl;
	}
	catch(SignatureVerificationFilter::SignatureVerificationFailed &err)
	{
		cout << err.what() << endl;
	}

}
Example #11
0
int main (int argc, const char* argv[]) {
    string toSign;
    FileSource(argv[1], true, new StringSink(toSign));

    AutoSeededRandomPool rng;

    //Read private key
    CryptoPP::ByteQueue bytes;
    FileSource file(argv[2], true, new Base64Decoder);
    file.TransferTo(bytes);
    bytes.MessageEnd();
    RSA::PrivateKey privateKey;
    privateKey.Load(bytes);

    //Sign message
    RSASSA_PKCS1v15_SHA_Signer signer(privateKey);
    SecByteBlock signature(signer.SignatureLength());
    signer.SignMessage(
        rng,
        (byte const*) toSign.data(),
        toSign.size(),
        signature);

    //Print string of signature
    HexEncoder encoder;
    string signatureString;
    encoder.Put(signature.data(), signature.size());
    encoder.MessageEnd();
    word64 signatureSize = encoder.MaxRetrievable();
    if (signatureSize) {
        signatureString.resize(signatureSize);
        encoder.Get((byte*) signatureString.data(), signatureString.size());
    }

    cout << signatureString << endl;
}
RSA::PrivateKey CRSAEncryptDecrypt::getPrivateKey(std::string pathToKeyStorage)
{
   LOG4CPLUS_INFO(msLogger, "getPrivate()");
   timeval begin, end;
   double elapsedTime;
   gettimeofday(&begin, NULL);
   if(!privateKeyGenerated)
   {
      //try to read it from file
      std::string filePath = pathToKeyStorage+"/private.k";
      LOG4CPLUS_INFO(msLogger, "getPrivate(): filepath="+filePath);

      ifstream inFile;
      size_t size = 0;

      inFile.open(filePath.c_str(), ios::in|ios::binary|ios::ate );
      if(inFile.good()) // the file is there and is readable
      {
         LOG4CPLUS_INFO(msLogger, "getPrivate(): retrieving previously stored data");
         char* signedData = 0;
         inFile.seekg(0, ios::end); // set the pointer to the end
         size = inFile.tellg() ; // get the length of the file
         inFile.seekg(0, ios::beg); // set the pointer to the beginning

         signedData = new char[size]; 
         inFile.read( signedData, size );
         inFile.close();
         UInt8 * unSignedData = new UInt8[size];
         memcpy(unSignedData, signedData, size);
         CryptoPP::ByteQueue queue;
         queue.Put(unSignedData,  size);
         rsaPrivate.Load(queue);
         delete[] signedData;
         delete[] unSignedData;
      } 
      else // the file is not there
      {
         LOG4CPLUS_INFO(msLogger, "getPrivate(): no key stored, generating");
         AutoSeededRandomPool rnd;
         rsaPrivate.GenerateRandomWithKeySize(rnd, 2048);
         // storing in file
         LOG4CPLUS_INFO(msLogger, "getPrivate(): saving generated file");
         CryptoPP::ByteQueue queue;
         rsaPrivate.Save(queue);
         UInt32 queueSize = queue.CurrentSize();
         UInt8* outgoingData = new UInt8[queueSize];
         queue.Get(outgoingData, queueSize);
         std::ofstream outputBufferHere(filePath.c_str(), std::ios::binary|std::ios::out);
         char * signedOutputData = new char[queueSize];
         memcpy(signedOutputData, outgoingData, queueSize);
         outputBufferHere.write(signedOutputData, queueSize);
         outputBufferHere.close();
         delete[] outgoingData;
         delete[] signedOutputData;
      }
      privateKeyGenerated = true;
   }

   gettimeofday(&end, NULL);
   elapsedTime = (end.tv_sec - begin.tv_sec) * 1000.0;      // sec to ms
   elapsedTime += (end.tv_usec - begin.tv_usec) / 1000.0;   // us to ms
   std::ostringstream s;
   s << "(" << elapsedTime << ") ms";
   LOG4CPLUS_INFO(msLogger, "Time elapsed generating private key: ");
   LOG4CPLUS_INFO(msLogger, s.str());
   return rsaPrivate;
}