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;
  
}
   static void printPublicKey(RSA::PublicKey key)
   {
      ///////////////////////////////////////
      // Generated Parameters
      const Integer& n = key.GetModulus();
      const Integer& e = key.GetPublicExponent();

      cout << "RSA Parameters:" << endl;
      cout << " n: " << n << endl;
      cout << " e: " << e << endl;
      cout << endl;

   }
Beispiel #3
0
static bool DecodeFromFile(const char* filename, RSA::PublicKey& key)
{
	try {
		ByteQueue queue;
		FileSource file(filename, true);
		file.TransferTo(queue);
		queue.MessageEnd();
		key.BERDecodePublicKey(queue, false, queue.MaxRetrievable());
		return key.Validate(rng, 3);
	} catch (...) {
		return false;
	}
}
void loadRSAPubKey(RSA::PublicKey& key, const char* filename){
  ByteQueue byte;
  FileSource file(filename, true, new Base64Decoder);
  file.TransferTo(byte);
  byte.MessageEnd();
  key.Load(byte);
}
void SaveKey(const RSA::PublicKey& PublicKey, const string& filename)
{
  // DER Encode Key - X.509 key format
  PublicKey.Save(
                 FileSink(filename.c_str(), true /*binary*/).Ref()
                 );
}
void LoadKey(const string& filename, RSA::PublicKey& PublicKey)
{
  // DER Encode Key - X.509 key format
  PublicKey.Load(
                 FileSource(filename.c_str(), true, NULL, true /*binary*/).Ref()
                 );
}
Beispiel #7
0
bool CheckSignature(const std::string& pubKey,
                    const std::string& message,
                    const std::string& signature)
{
    RSA::PublicKey publicKey;
    publicKey.Load(StringSource(pubKey, true).Ref());

    RSASSA_PKCS1v15_SHA_Verifier verifier(publicKey);
    try {
        StringSource(message+signature, true,
                     new SignatureVerificationFilter(
                     verifier, NULL,
                     SignatureVerificationFilter::THROW_EXCEPTION));
        return true;
    } catch (const std::exception&) {
        return false;
    }
}
Beispiel #8
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;
}
void BCipher::verify_signature(std::string content,std::string signature){
        std::cout<<"Receiver verifies signature using sender's publickey"<<std::endl;
        RSA::PublicKey rsaPublickey;
        {
         FileSource input("sender_public.dat", true);
         rsaPublickey.BERDecode(input);
        }
 
	RSASSA_PKCS1v15_SHA_Verifier verifier(rsaPublickey);
        StringSource ss4(content + signature, true,
           new SignatureVerificationFilter(
               verifier, NULL,
               SignatureVerificationFilter::THROW_EXCEPTION
          ) // SignatureVerificationFilter
        ); // StringSource

        std::cout << "Verified signature on message" << std::endl;

}
/*
 * generate the RSA public key and private key in separate file
 */
void MyRSA::GenerateRSAKey(unsigned int keyLength, const char *privFilename,
                           const char *pubFilename)
{   AutoSeededRandomPool rng;
    RSA::PrivateKey priv;
    priv.GenerateRandomWithKeySize(rng, 1024);
    if (!priv.Validate(rng, 3))
    {
        throw("RSA key generation failed");
    }
	HexEncoder privFile(new FileSink(privFilename));
	priv.DEREncode(privFile);
	privFile.MessageEnd();
    
    
    RSA::PublicKey pub;
    pub.AssignFrom(priv);
	HexEncoder pubFile(new FileSink(pubFilename));
	pub.DEREncode(pubFile);
	pubFile.MessageEnd();
}
Beispiel #11
0
void CAuthenticationProfileImpl::sendPublicKey(RSA::PublicKey publicKey)
{
   LOG4CPLUS_TRACE_METHOD(msLogger, __PRETTY_FUNCTION__ );
   ByteQueue queue;
   publicKey.Save(queue);
   UInt32 queueSize = queue.CurrentSize();
   UInt8* outgoingData = new UInt8[queueSize + 1];
   outgoingData[0] = static_cast<UInt8>(SEND_PUBLIC_KEY);
   queue.Get(outgoingData + 1, queueSize);
   LOG4CPLUS_INFO(msLogger, "***** " + convertIntegerToString(queueSize + 1) + " bytes sent");
   iviLink::Channel::sendBuffer(mChannelID, outgoingData, queueSize + 1);
   delete[] outgoingData;
}
int
main(int argc, char ** argv)
{
	if (argc != 2) {
		cout << "Usage: keygen <outputname>" << endl;
		return -1;
	}
	AutoSeededRandomPool rng;
	InvertibleRSAFunction params;
	params.GenerateRandomWithKeySize(rng, 3072);
	RSA::PublicKey pubkey(params);
	RSA::PrivateKey privkey(params);

	Integer m = params.GetModulus();
	Integer p = params.GetModulus();
	Integer q = params.GetModulus();
	Integer priv = params.GetPrivateExponent();
	Integer pub = params.GetPublicExponent();

	string privname = string(argv[1]).append(".priv");
	string pubname = string(argv[1]).append(".pub");

	CryptoEngine::pubkeyToFile(pubkey, pubname);
	CryptoEngine::privkeyToFile(privkey, privname);

	cout << "Loading and verifying..." << endl;

	RSA::PrivateKey newpriv = CryptoEngine::privkeyFromFile(privname);
	RSA::PublicKey newpub = CryptoEngine::pubkeyFromFile(pubname);

	cout << (m == newpriv.GetModulus() ? "TRUE" : "FALSE") << endl;
	cout << (priv == newpriv.GetPrivateExponent() ? "TRUE" : "FALSE") << endl;
	cout << (pub == newpriv.GetPublicExponent() ? "TRUE" : "FALSE") << endl;

	cout << (m == newpub.GetModulus() ? "TRUE" : "FALSE") << endl;
	cout << (pub == newpub.GetPublicExponent() ? "TRUE" : "FALSE") << endl;

	return 0;
}
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;
}
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;
	}

}
Beispiel #15
0
std::string EncryptAsymmetrical(const std::string& pubKey, const std::string& data) {
    assert(!data.empty());
    string result;

    AutoSeededRandomPool rng;
    RSA::PublicKey publicKey;
    publicKey.Load(StringSource(pubKey, true).Ref());
    RSAES_OAEP_SHA_Encryptor e(publicKey);
    result.resize(2);
    *(ui16*)result.data() = 0;
    for (size_t i = 0; i <= (data.size() - 1) / MAX_DATA_SIZE; ++i) {
        string currData = data.substr(i * MAX_DATA_SIZE, MAX_DATA_SIZE);
        string currResult;
        StringSource ss(currData, true,
                        new PK_EncryptorFilter(rng, e,
                        new StringSink(currResult)));
        result.resize(result.size() + 2);
        (*(ui16*)(result.data() + result.size() - 2)) = currResult.size();
        (*(ui16*)(result.data()))++;
        result += currResult;
    }
    assert(!result.empty());
    return result;
}
void PrintPublicKey(const RSA::PublicKey& key)
{
  cout << "n: " << key.GetModulus() << endl;
  cout << "e: " << key.GetPublicExponent() << endl;
}
void saveRSAPubKey(RSA::PublicKey& key, const char* filename){
  Base64Encoder publicKey(new FileSink(filename));
  key.DEREncode(publicKey);
  publicKey.MessageEnd();
}
void BCipher::decrypt(std::string fkfile,std::string filename,std::string encryptedfile,std::string decryptedfile,std::string content,std::string signature){
	AutoSeededRandomPool rng;
        RSA::PrivateKey privateKey;
        {
         FileSource input("receiver_private.dat", true);
         privateKey.BERDecode(input);
        }

        RSA::PublicKey publicKey;
        {
         FileSource input("receiver_public.dat", true);
         publicKey.BERDecode(input);
        }

	//InvertibleRSAFunction params;
	//params.GenerateRandomWithKeySize(rng, 3072);

	//RSA::PrivateKey privateKey(params);
	//RSA::PublicKey publicKey(params);
	std::cout<<"Sending public key to sender..."<<std::endl;
	std::string plain, cipher, recovered, cipher1,hmaccontents;
	std::stringstream ss;
        //read key file
	std::ifstream infk(fkfile.c_str());
	ss << infk.rdbuf();
	std::string fk = ss.str();
	ss.str("");
	infk.close();
	plain=fk;
        
        //read HMAC file
	std::ifstream inmd5(("hmac_"+encryptedfile).c_str());
	ss << inmd5.rdbuf();
	//std::string hmaccontents = ss.str();
        std::string hmac = ss.str();
	ss.str("");
	inmd5.close();

	// Encryption
	std::cout<<"User encrypting key and HMAC of uploaded file with public key..."<<std::endl;
	RSAES_OAEP_SHA_Encryptor e(publicKey);

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

	StringSource ss3(hmac, true,
	    new PK_EncryptorFilter(rng, e,
	        new StringSink(cipher1)
	   ) // PK_EncryptorFilter
	); // StringSource
        
	std::cout<<"Encryption Complete.\nSender now sharing the encrypted key and HMAC of uploaded file over unsecure channel..."<<std::endl;

        std::ofstream encrtptedkey("ekey.txt");
	encrtptedkey << cipher;
        encrtptedkey.close();

        std::ofstream encrtptedhmac("ehmac_efile.txt");
	encrtptedhmac << cipher1;
        encrtptedhmac.close();

	std::cout<<"Peer receives the encrypted files."<<std::endl;
	std::cout<<"Decrypting the files using his private key..."<<std::endl;

	// Decryption
	RSAES_OAEP_SHA_Decryptor d(privateKey);

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

	StringSource ss4(cipher1, true,
	    new PK_DecryptorFilter(rng, d,
	        new StringSink(hmaccontents)
	   ) // PK_DecryptorFilter
	); // StringSource

	fk=recovered;

        std::cout<<"====================================================================="<<std::endl;
        //check if file is what I want.
        authorize(filename);
        std::cout<<"====================================================================="<<std::endl;
        // verify digital signature.     
        verify_signature(content,signature);
        std::cout<<"====================================================================="<<std::endl;

	Hexa b;
	std::string hmackey = fk.substr(AES::MAX_KEYLENGTH*2 + AES::BLOCKSIZE*2,HMAC_KEYLENGTH*2);
	std::string skey = fk.substr(0,AES::MAX_KEYLENGTH*2);
	std::string siv = fk.substr(AES::MAX_KEYLENGTH*2,AES::BLOCKSIZE*2);
        //std::cout<<hmackey<<std::endl;
        //std::cout<<skey<<std::endl;
        //std::cout<<siv<<std::endl;

	// Get key in byte form from hex
	byte *key=b.hex_to_byte_decoder(skey);

	// Get iv in byte form from hex
	byte *iv=b.hex_to_byte_decoder(siv);

	// Get cipher text from file
	std::ifstream in(encryptedfile.c_str());
	ss << in.rdbuf();
	std::string input=ss.str();
	size_t len = input.length();
	int ctlen = len/2;
	ss.str("");
	in.close();



	std::cout<<"Checking HMAC of downloaded file ..."<<std::endl;
	HashMac h;
	if(h.verify_hmac(hmackey,input,hmaccontents)){
		std::cout<<"File authenticated and integrity maintained!"<<std::endl;
	}
	else{
		std::cout<<"File could not be authenticated!"<<std::endl;
                return;
	}

	// Convert ciphertext to bytes from hex
	byte *ciphertext=b.hex_to_byte_decoder(input);

	unsigned char *plaintext = new unsigned char[ctlen+1];
	plaintext[ctlen]='\0';

        std::cout<<"====================================================================="<<std::endl;

	// Decrypt the file and store contents to file
	CFB_Mode<AES>::Decryption cfbDecryption(key, AES::MAX_KEYLENGTH, iv);
	cfbDecryption.ProcessData(plaintext, ciphertext, ctlen+1);
	std::string x = b.byte_to_hex_encoder(plaintext,ctlen);
	std::ofstream outfinal(decryptedfile.c_str());
	outfinal << x;
	outfinal.close();
        std::cout<<"Succeed! You can check file_recovered.txt"<<std::endl;
}
Integer Node::RSAencrypt(std::string message, RSA::PublicKey pubKey){
	Integer raw((const byte*)message.data(), message.size());
	raw=pubKey.ApplyFunction(raw);
	return raw;
}
Beispiel #20
0
bool
Validator::verifySignature(const uint8_t* buf,
                           const size_t size,
                           const Signature& sig,
                           const v1::PublicKey& key)
{
  try {
    using namespace CryptoPP;

    switch (sig.getType()) {
      case tlv::SignatureSha256WithRsa: {
        if (key.getKeyType() != KeyType::RSA)
          return false;

        RSA::PublicKey publicKey;
        ByteQueue queue;

        queue.Put(reinterpret_cast<const byte*>(key.get().buf()), key.get().size());
        publicKey.Load(queue);

        RSASS<PKCS1v15, SHA256>::Verifier verifier(publicKey);
        return verifier.VerifyMessage(buf, size,
                                      sig.getValue().value(), sig.getValue().value_size());
      }

      case tlv::SignatureSha256WithEcdsa: {
        if (key.getKeyType() != KeyType::EC)
          return false;

        ECDSA<ECP, SHA256>::PublicKey publicKey;
        ByteQueue queue;

        queue.Put(reinterpret_cast<const byte*>(key.get().buf()), key.get().size());
        publicKey.Load(queue);

        ECDSA<ECP, SHA256>::Verifier verifier(publicKey);

        uint32_t length = 0;
        StringSource src(key.get().buf(), key.get().size(), true);
        BERSequenceDecoder subjectPublicKeyInfo(src);
        {
          BERSequenceDecoder algorithmInfo(subjectPublicKeyInfo);
          {
            Oid algorithm;
            algorithm.decode(algorithmInfo);

            Oid curveId;
            curveId.decode(algorithmInfo);

            if (curveId == SECP256R1)
              length = 256;
            else if (curveId == SECP384R1)
              length = 384;
            else
              return false;
          }
        }

        switch (length) {
          case 256: {
            uint8_t buffer[64];
            size_t usedSize = DSAConvertSignatureFormat(buffer, sizeof(buffer), DSA_P1363,
                                                        sig.getValue().value(),
                                                        sig.getValue().value_size(),
                                                        DSA_DER);
            return verifier.VerifyMessage(buf, size, buffer, usedSize);
          }

          case 384: {
            uint8_t buffer[96];
            size_t usedSize = DSAConvertSignatureFormat(buffer, sizeof(buffer), DSA_P1363,
                                                        sig.getValue().value(),
                                                        sig.getValue().value_size(),
                                                        DSA_DER);
            return verifier.VerifyMessage(buf, size, buffer, usedSize);
          }

          default:
            return false;
        }
      }

      default:
        // Unsupported sig type
        return false;
    }
  }
  catch (const CryptoPP::Exception& e) {
    return false;
  }
}