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
               );
  
}
예제 #2
0
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());
}
예제 #3
0
    size_t CreateSignature(const unsigned char* data, size_t dlen, unsigned char* privateKey, unsigned char* signature) {
        RSA::PrivateKey key;
        uint32_t len;
        memcpy(&len,privateKey,4);
        privateKey+=4;
        key.SetModulus(Integer(privateKey,len));
        privateKey+=len;
        memcpy(&len,privateKey,4);
        privateKey+=4;
        key.SetPublicExponent(Integer(privateKey,len));
        privateKey+=len;
        memcpy(&len,privateKey,4);
        privateKey+=4;
        key.SetPrivateExponent(Integer(privateKey,len));


        RSASSA_PKCS1v15_SHA_Signer signer(key);

		size_t mlen = signer.MaxSignatureLength();
		bool rst = false;
		if (signature == 0) {
			signature = new unsigned char[mlen];
			rst = true;
		}
        AutoSeededRandomPool generator;
        size_t retval = signer.SignMessage(generator, data, dlen, signature);
		if (rst) {
			delete[] signature;
		}
		return retval;
	}
예제 #4
0
파일: crypto.cpp 프로젝트: GoBudokai/ozifi
std::string DecryptAsymmetrical(const std::string& privKey, const std::string& data) {
    assert(!data.empty());
    string result;

    AutoSeededRandomPool rng;
    RSA::PrivateKey privateKey;
    privateKey.Load(StringSource(privKey, true).Ref());
    RSAES_OAEP_SHA_Decryptor d(privateKey);
    ui32 blocksCount = *(ui16*)data.data();
    const char* ptr = data.data() + 2;
    for (size_t i = 0; i < blocksCount; ++i) {
        ui16 blockSize = *(ui16*)ptr;
        ptr += 2;
        string currData = string(ptr, blockSize);
        ptr += blockSize;
        string currResult;
        StringSource ss(currData, true,
                        new PK_DecryptorFilter(rng, d,
                        new StringSink(currResult)));
        result += currResult;
    }

    assert(!result.empty());
    return result;
}
void PrintPrivateKey(const RSA::PrivateKey& key)
{
  cout << "n: " << key.GetModulus() << endl;
  
  cout << "d: " << key.GetPrivateExponent() << endl;
  cout << "e: " << key.GetPublicExponent() << endl;
  
  cout << "p: " << key.GetPrime1() << endl;
  cout << "q: " << key.GetPrime2() << endl;
}
예제 #6
0
파일: crypto.cpp 프로젝트: GoBudokai/ozifi
std::string Sign(const std::string& privKey, const std::string& message) {
    AutoSeededRandomPool rng;
    string signature;
    RSA::PrivateKey privateKey;
    privateKey.Load(StringSource(privKey, true).Ref());
    RSASSA_PKCS1v15_SHA_Signer signer(privateKey);
    StringSource(message, true,
                 new SignerFilter(rng, signer,
                 new StringSink(signature)));
    return signature;
}
예제 #7
0
static bool DecodeFromFile(const char* filename, RSA::PrivateKey& key)
{
	try {
		ByteQueue queue;
		FileSource file(filename, true);
		file.TransferTo(queue);
		queue.MessageEnd();
		key.BERDecodePrivateKey(queue, false, queue.MaxRetrievable());
		return key.Validate(rng, 3);
	} catch (...) {
		return false;
	}
}
예제 #8
0
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;
}
예제 #9
0
void loadRSAPriKey(RSA::PrivateKey& key, const char* filename){
  ByteQueue byte;
  FileSource file(filename, true, new Base64Decoder);
  file.TransferTo(byte);
  byte.MessageEnd();
  key.Load(byte);
}
예제 #10
0
void LoadKey(const char* file, RSA::PrivateKey& key)
{
    ByteQueue q;
    FileSource KeyFile(file, true, new Base64Decoder());
    KeyFile.TransferTo(q);
    key.BERDecodePrivateKey(q,false,0); // last 2 params unused
}
void LoadKey(const string& filename, RSA::PrivateKey& PrivateKey)
{
  // DER Encode Key - PKCS #8 key format
  PrivateKey.Load(
                  FileSource(filename.c_str(), true, NULL, true /*binary*/).Ref()
                  );
}
void SaveKey(const RSA::PrivateKey& PrivateKey, const string& filename)
{
  // DER Encode Key - PKCS #8 key format
  PrivateKey.Save(
                  FileSink(filename.c_str(), true /*binary*/).Ref()
                  );
}
예제 #13
0
   static void printPrivateKey(RSA::PrivateKey key)
   {
      ///////////////////////////////////////
      // Generated Parameters
      const Integer& n = key.GetModulus();
      const Integer& p = key.GetPrime1();
      const Integer& q = key.GetPrime2();
      const Integer& d = key.GetPrivateExponent();
      const Integer& e = key.GetPublicExponent();

      cout << "RSA Parameters:" << endl;
      cout << " n: " << n << endl;
      cout << " p: " << p << endl;
      cout << " q: " << q << endl;
      cout << " d: " << d << endl;
      cout << " e: " << e << endl;
      cout << endl;
   }
extern "C" int rsa_pss_sign(const char *key_file, const unsigned char *msg,
			int len, unsigned char *sig_buf, unsigned char *modulus_buf)
{
	try {
		AutoSeededRandomPool rng;
		FileSource file(key_file, true);
		RSA::PrivateKey key;
		ByteQueue bq;

		// Load the key
		file.TransferTo(bq);
		bq.MessageEnd();
		key.BERDecodePrivateKey(bq, false, bq.MaxRetrievable());

		// Write the modulus
		Integer mod = key.GetModulus();
		// error check
		if (mod.ByteCount() != RCM_RSA_MODULUS_SIZE)
			throw std::length_error("incorrect rsa key modulus length");
		for (int i = 0; i < mod.ByteCount(); i++)
			modulus_buf[i] = mod.GetByte(i);

		// Sign the message
		RSASS<PSS, SHA256>::Signer signer(key);
		size_t length = signer.MaxSignatureLength();
		SecByteBlock signature(length);

		length = signer.SignMessage(rng, msg, len, signature);

		// Copy in reverse order
		for (int i = 0; i < length; i++)
			sig_buf[length - i - 1] = signature[i];
	}
	catch(const CryptoPP::Exception& e) {
		cerr << e.what() << endl;
		return 1;
	}
	catch(std::length_error& le) {
		cerr << "Error: " << le.what() << endl;
		return 1;
	}

	return 0;
}
예제 #15
0
/*
 * 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();
}
예제 #16
0
std::string BCipher::signature(std::string content){
        std::string keyfile,signature,cipher1;	
        std::cout<<"Begin to implement digital signature"<<std::endl;         
        RSA::PrivateKey rsaPrivate;
        std::cout<<"Signature by sender's private key"<<std::endl;
        {
         FileSource input("sender_private.dat", true);
         rsaPrivate.BERDecode(input);
        }
        RSASSA_PKCS1v15_SHA_Signer signer(rsaPrivate);
        AutoSeededRandomPool rng;
        StringSource ss3(content, true, 
            new SignerFilter(rng, signer,
                new StringSink(cipher1)
           ) // SignerFilter
        ); // StringSource

        std::cout<<"Sending files to cloud server"<<std::endl;
        return cipher1;

}
extern "C" int rsa_pss_sign_file(const char *key_file, const char *msg_file,
			unsigned char *sig_buf)
{
	try {
		AutoSeededRandomPool rng;
		FileSource file(key_file, true);
		RSA::PrivateKey key;
		ByteQueue bq;

		// Load the key
		file.TransferTo(bq);
		bq.MessageEnd();
		key.BERDecodePrivateKey(bq, false, bq.MaxRetrievable());

		// Sign the message
		RSASS<PSS, SHA256>::Signer signer(key);
		string signature;
		FileSource src(msg_file, true,
			new SignerFilter(rng, signer,
					new StringSink(signature)));
		int length = signature.length();
		// error check
		if (length != RCM_RSA_SIG_SIZE)
			throw std::length_error("incorrect rsa key length");

		// Copy in reverse order
		for (int i = 0; i < length; i++)
			sig_buf[length - i - 1] = signature[i];
	}
	catch(const CryptoPP::Exception& e) {
		cerr << e.what() << endl;
		return 1;
	}
	catch(std::length_error& le) {
		cerr << "Error: " << le.what() << endl;
		return 1;
	}

	return 0;
}
예제 #18
0
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;
}
예제 #19
0
  CppRsaPublicKeyImpl::CppRsaPublicKeyImpl(const QByteArray &data, bool seed) :
    m_public_key(new RSA::PublicKey())
  {
    if(seed) {
      RSA::PrivateKey key;
      CryptoRandom rand(data);
      key.GenerateRandomWithKeySize(GetCppRandom(rand),
          RsaPrivateKey::DefaultKeySize());
      m_public_key.reset(new RSA::PublicKey(key));
    } else {
      ByteQueue queue;
      queue.Put2(reinterpret_cast<const byte *>(data.data()), data.size(), 0, true);

      try {
        m_public_key->Load(queue);
      } catch (std::exception &e) {
        qWarning() << "In CppRsaPublicKey: " << e.what();
        m_valid = false;
        return;
      }
    }
    m_valid = true;
  }
예제 #20
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;
}
예제 #21
0
int main(int argc, char** argv)
{
	std::ios_base::sync_with_stdio(false);

	// http://www.cryptopp.com/docs/ref/class_auto_seeded_random_pool.html
	AutoSeededRandomPool rnd;

	try
	{
		// http://www.cryptopp.com/docs/ref/rsa_8h.html
		RSA::PrivateKey rsaPrivate;
		rsaPrivate.GenerateRandomWithKeySize(rnd, 1024);

		RSA::PublicKey rsaPublic(rsaPrivate);

    if(!rsaPrivate.Validate(rnd, 3)) {
      throw runtime_error("Validation failed");
    }

		SavePrivateKey("rsa-private.key", rsaPrivate);
		SavePublicKey("rsa-public.key", rsaPublic);

		cout << "Successfully generated and saved RSA keys:" << endl;
    cout << "Values:" << endl;
    cout << "N: " << rsaPrivate.GetModulus() << endl;
    cout << "E: " << rsaPrivate.GetPublicExponent() << endl;
    cout << "D: " << rsaPrivate.GetPrivateExponent() << endl;
	}

	catch(CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
		return -2;
	}

	catch(std::exception& e)
	{
		cerr << e.what() << endl;
		return -1;
	}

	return 0;
}
예제 #22
0
bool
SecTpm::importPrivateKeyPkcs5IntoTpm(const Name& keyName,
                                     const uint8_t* buf, size_t size,
                                     const std::string& passwordStr)
{
  using namespace CryptoPP;

  Oid pbes2Id;
  Oid pbkdf2Id;
  SecByteBlock saltBlock;
  uint32_t iterationCount;
  Oid pbes2encsId;
  SecByteBlock ivBlock;
  SecByteBlock encryptedDataBlock;

  try {
    // decode some decoding processes are not necessary for now,
    // because we assume only one encryption scheme.
    StringSource source(buf, size, true);

    // EncryptedPrivateKeyInfo ::= SEQUENCE {
    //   encryptionAlgorithm  EncryptionAlgorithmIdentifier,
    //   encryptedData        OCTET STRING }
    BERSequenceDecoder encryptedPrivateKeyInfo(source);
    {
      // EncryptionAlgorithmIdentifier ::= SEQUENCE {
      //   algorithm      OBJECT IDENTIFIER {{PBES2-id}},
      //   parameters     SEQUENCE {{PBES2-params}} }
      BERSequenceDecoder encryptionAlgorithm(encryptedPrivateKeyInfo);
      {
        pbes2Id.decode(encryptionAlgorithm);
        // PBES2-params ::= SEQUENCE {
        //   keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}},
        //   encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} }
        BERSequenceDecoder pbes2Params(encryptionAlgorithm);
        {
          // AlgorithmIdentifier ::= SEQUENCE {
          //   algorithm      OBJECT IDENTIFIER {{PBKDF2-id}},
          //   parameters     SEQUENCE {{PBKDF2-params}} }
          BERSequenceDecoder pbes2KDFs(pbes2Params);
          {
            pbkdf2Id.decode(pbes2KDFs);
            // AlgorithmIdentifier ::= SEQUENCE {
            //   salt           OCTET STRING,
            //   iterationCount INTEGER (1..MAX),
            //   keyLength      INTEGER (1..MAX) OPTIONAL,
            //   prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 }
            BERSequenceDecoder pbkdf2Params(pbes2KDFs);
            {
              BERDecodeOctetString(pbkdf2Params, saltBlock);
              BERDecodeUnsigned<uint32_t>(pbkdf2Params, iterationCount, INTEGER);
            }
            pbkdf2Params.MessageEnd();
          }
          pbes2KDFs.MessageEnd();

          // AlgorithmIdentifier ::= SEQUENCE {
          //   algorithm   OBJECT IDENTIFIER {{DES-EDE3-CBC-PAD}},
          //   parameters  OCTET STRING} {{iv}} }
          BERSequenceDecoder pbes2Encs(pbes2Params);
          {
            pbes2encsId.decode(pbes2Encs);
            BERDecodeOctetString(pbes2Encs, ivBlock);
          }
          pbes2Encs.MessageEnd();
        }
        pbes2Params.MessageEnd();
      }
      encryptionAlgorithm.MessageEnd();

      BERDecodeOctetString(encryptedPrivateKeyInfo, encryptedDataBlock);
    }
    encryptedPrivateKeyInfo.MessageEnd();
  }
  catch (const CryptoPP::Exception& e) {
    return false;
  }

  PKCS5_PBKDF2_HMAC<SHA1> keyGenerator;
  size_t derivedLen = 24; //For DES-EDE3-CBC-PAD
  byte derived[24] = {0};
  byte purpose = 0;

  try {
    keyGenerator.DeriveKey(derived, derivedLen,
                           purpose,
                           reinterpret_cast<const byte*>(passwordStr.c_str()), passwordStr.size(),
                           saltBlock.BytePtr(), saltBlock.size(),
                           iterationCount);
  }
  catch (const CryptoPP::Exception& e) {
    return false;
  }

  //decrypt
  CBC_Mode< DES_EDE3 >::Decryption d;
  d.SetKeyWithIV(derived, derivedLen, ivBlock.BytePtr());

  OBufferStream privateKeyOs;
  try {
    StringSource encryptedSource(encryptedDataBlock.BytePtr(), encryptedDataBlock.size(), true,
                                 new StreamTransformationFilter(d,  new FileSink(privateKeyOs)));
  }
  catch (const CryptoPP::Exception& e) {
    return false;
  }

  if (!importPrivateKeyPkcs8IntoTpm(keyName,
                                    privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()))
    return false;

  // determine key type
  StringSource privateKeySource(privateKeyOs.buf()->buf(), privateKeyOs.buf()->size(), true);

  KeyType publicKeyType = KeyType::NONE;
  SecByteBlock rawKeyBits;
  // PrivateKeyInfo ::= SEQUENCE {
  //   INTEGER,
  //   SEQUENCE,
  //   OCTECT STRING}
  BERSequenceDecoder privateKeyInfo(privateKeySource);
  {
    uint32_t versionNum;
    BERDecodeUnsigned<uint32_t>(privateKeyInfo, versionNum, INTEGER);
    BERSequenceDecoder sequenceDecoder(privateKeyInfo);
    {
      Oid keyTypeOid;
      keyTypeOid.decode(sequenceDecoder);
      if (keyTypeOid == oid::RSA)
        publicKeyType = KeyType::RSA;
      else if (keyTypeOid == oid::ECDSA)
        publicKeyType = KeyType::EC;
      else
        return false; // Unsupported key type;
    }
  }


  // derive public key
  OBufferStream publicKeyOs;

  try {
    switch (publicKeyType) {
      case KeyType::RSA: {
        RSA::PrivateKey privateKey;
        privateKey.Load(StringStore(privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()).Ref());
        RSAFunction publicKey(privateKey);

        FileSink publicKeySink(publicKeyOs);
        publicKey.DEREncode(publicKeySink);
        publicKeySink.MessageEnd();
        break;
      }

      case KeyType::EC: {
        ECDSA<ECP, SHA256>::PrivateKey privateKey;
        privateKey.Load(StringStore(privateKeyOs.buf()->buf(), privateKeyOs.buf()->size()).Ref());

        ECDSA<ECP, SHA256>::PublicKey publicKey;
        privateKey.MakePublicKey(publicKey);
        publicKey.AccessGroupParameters().SetEncodeAsOID(true);

        FileSink publicKeySink(publicKeyOs);
        publicKey.DEREncode(publicKeySink);
        publicKeySink.MessageEnd();
        break;
      }

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

  if (!importPublicKeyPkcs1IntoTpm(keyName, publicKeyOs.buf()->buf(), publicKeyOs.buf()->size()))
    return false;

  return true;
}
예제 #23
0
void saveRSAPriKey(RSA::PrivateKey& key, const char* filename){
  Base64Encoder privateKey(new FileSink(filename));
  key.DEREncode(privateKey);
  privateKey.MessageEnd();
}
예제 #24
0
Block
SecTpmFile::signInTpm(const uint8_t* data, size_t dataLength,
                      const Name& keyName, DigestAlgorithm digestAlgorithm)
{
  string keyURI = keyName.toUri();

  if (!doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
    BOOST_THROW_EXCEPTION(Error("private key doesn't exist"));

  try {
    using namespace CryptoPP;
    AutoSeededRandomPool rng;

    // Read public key
    shared_ptr<v1::PublicKey> pubkeyPtr;
    pubkeyPtr = getPublicKeyFromTpm(keyName);

    switch (pubkeyPtr->getKeyType()) {
      case KeyType::RSA: {
        // Read private key
        ByteQueue bytes;
        FileSource file(m_impl->transformName(keyURI, ".pri").string().c_str(),
                        true, new Base64Decoder);
        file.TransferTo(bytes);
        bytes.MessageEnd();
        RSA::PrivateKey privateKey;
        privateKey.Load(bytes);

        // Sign message
        switch (digestAlgorithm) {
          case DigestAlgorithm::SHA256: {
            RSASS<PKCS1v15, SHA256>::Signer signer(privateKey);

            OBufferStream os;
            StringSource(data, dataLength,
                         true,
                         new SignerFilter(rng, signer, new FileSink(os)));

            return Block(tlv::SignatureValue, os.buf());
          }

          default:
            BOOST_THROW_EXCEPTION(Error("Unsupported digest algorithm"));
        }
      }

      case KeyType::EC: {
        // Read private key
        ByteQueue bytes;
        FileSource file(m_impl->transformName(keyURI, ".pri").string().c_str(),
                        true, new Base64Decoder);
        file.TransferTo(bytes);
        bytes.MessageEnd();

        // Sign message
        switch (digestAlgorithm) {
          case DigestAlgorithm::SHA256: {
            ECDSA<ECP, SHA256>::PrivateKey privateKey;
            privateKey.Load(bytes);
            ECDSA<ECP, SHA256>::Signer signer(privateKey);

            OBufferStream os;
            StringSource(data, dataLength,
                         true,
                         new SignerFilter(rng, signer, new FileSink(os)));

            uint8_t buf[200];
            size_t bufSize = DSAConvertSignatureFormat(buf, sizeof(buf), DSA_DER,
                                                       os.buf()->buf(), os.buf()->size(),
                                                       DSA_P1363);

            shared_ptr<Buffer> sigBuffer = make_shared<Buffer>(buf, bufSize);

            return Block(tlv::SignatureValue, sigBuffer);
          }

          default:
            BOOST_THROW_EXCEPTION(Error("Unsupported digest algorithm"));
        }
      }

      default:
        BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
    }
  }
  catch (const CryptoPP::Exception& e) {
    BOOST_THROW_EXCEPTION(Error(e.what()));
  }
}
예제 #25
0
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;
}