Exemple #1
0
    unsigned char* CreatePrivateKey(size_t* len, size_t* pubLen) {
        AutoSeededRandomPool rand;

        InvertibleRSAFunction params;
        params.GenerateRandomWithKeySize(rand,4096);
        const Integer& modulus = params.GetModulus();
        const Integer& exponent = params.GetPublicExponent();
        const Integer& private_exponent = params.GetPrivateExponent();
        size_t dlen = 4+modulus.MinEncodedSize()+4+exponent.MinEncodedSize()+4+private_exponent.MinEncodedSize();
        unsigned char* izard = new unsigned char[dlen];
        unsigned char* str = izard;
        uint32_t cval = modulus.MinEncodedSize();
        memcpy(str,&cval,4);
        str+=4;
        modulus.Encode(str,modulus.MinEncodedSize());
        str+=modulus.MinEncodedSize();
        cval = exponent.MinEncodedSize();
        memcpy(str,&cval,4);
        str+=4;
        exponent.Encode(str,exponent.MinEncodedSize());
        str+=exponent.MinEncodedSize();
        cval = private_exponent.MinEncodedSize();
        memcpy(str,&cval,4);
        str+=4;
        *pubLen = ((size_t)str-(size_t)izard);
        private_exponent.Encode(str,private_exponent.MinEncodedSize());
        str+=private_exponent.MinEncodedSize();
        *len = dlen;
        return izard;
    }
Exemple #2
0
int main(int argc, const char *argv[])
{
    
    // monty pythons!
    string text = "Are you suggesting coconuts migrate?";
    AutoSeededRandomPool rng;

    InvertibleRSAFunction keys;
    keys.GenerateRandomWithKeySize(rng, 384);

    RSASS<PKCS1v15, SHA>::Signer signer(keys);

    byte* signature = new byte[signer.MaxSignatureLength()];
    if(NULL == signature) { return -1; }

    // Sign...
    size_t length = signer.SignMessage(rng, (const byte*) text.c_str(),
                                       text.length(), signature);

    RSASS<PKCS1v15, SHA>::Verifier verifier(signer);

    bool result = verifier.VerifyMessage((const byte*)text.c_str(),
                                         text.length(), signature, length);

    return 0;
}
Exemple #3
0
void GenerateKeyPair()
{
	// Generate keys
    AutoSeededRandomPool rng;

    InvertibleRSAFunction parameters;
    parameters.GenerateRandomWithKeySize( rng, 1024 );

    RSA::PrivateKey privateKey( parameters );
    RSA::PublicKey publicKey( parameters );
	
	SaveKey(privateKey, "priv.key");
	SaveKey(publicKey, "pub.key");
}
Exemple #4
0
pair<string /*privKey*/, string /*pubKey*/> GenerateKeys() {
    AutoSeededRandomPool rng;
    InvertibleRSAFunction params;
    params.GenerateRandomWithKeySize(rng, DEFAULT_ASSYMETRICAL_KEY_LENGTH);

    RSA::PrivateKey privateKey(params);
    RSA::PublicKey publicKey(params);


    string privKey;
    string pubKey;
    privateKey.Save(StringSink(privKey).Ref());
    publicKey.Save(StringSink(pubKey).Ref());

    return pair<string, string>(privKey, pubKey);
}
Exemple #5
0
void SharedKey_Init(InvertibleRSAFunction & privkey){
  
  // InvertibleRSAFunction is used directly only because the private key
  // won't actually be used to perform any cryptographic operation;
  // otherwise, an appropriate typedef'ed type from rsa.h would have been used.
  AutoSeededRandomPool rng;
  //InvertibleRSAFunction privkey;
  privkey.Initialize(rng, 1024);
  
  // With the current version of Crypto++, MessageEnd() needs to be called
  // explicitly because Base64Encoder doesn't flush its buffer on destruction.
  /*
  Base64Encoder privkeysink(new FileSink("privkey.txt"));
  privkey.DEREncode(privkeysink);
  privkeysink.MessageEnd();
  */
   
   
  // Suppose we want to store the public key separately,
  // possibly because we will be sending the public key to a third party.
  RSAFunction pubkey(privkey);
  Base64Encoder pubkeysink(new FileSink("pubkey.txt"));
  pubkey.DEREncode(pubkeysink);
  pubkeysink.MessageEnd();
  
}
void BCipher::generateRSAkeys(){
	std::cout<<"Generating RSA keys for receiver..."<<std::endl;
	// Generate keys
	AutoSeededRandomPool rng;

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

	RSA::PrivateKey privateKey(params);
	RSA::PublicKey publicKey(params);
{
        FileSink output("receiver_private.dat");
        privateKey.DEREncode(output);
}
{
        FileSink output("receiver_public.dat");
        publicKey.DEREncode(output);
}
        std::cout<<"Produce receiver_private.dat and receiver_public.dat" <<std::endl;
}
Exemple #7
0
/*
 * Class:     edu_biu_scapi_midLayer_asymmetricCrypto_encryption_CryptoPPRSAOaep
 * Method:    initRSADecryptor
 * Signature: ([B[B[B)J
 */
JNIEXPORT void JNICALL Java_edu_biu_scapi_midLayer_asymmetricCrypto_encryption_CryptoPPRSAOaep_initRSADecryptor
  (JNIEnv *env, jobject, jlong decryptor, jbyteArray modulus, jbyteArray pubExp, jbyteArray privExp) {
	  
	  Integer n, e, d;
	  Utils utils;

	  // get the Integers values for the RSA permutation 
	  n = utils.jbyteArrayToCryptoPPInteger(env, modulus);
	  e = utils.jbyteArrayToCryptoPPInteger(env, pubExp);
	  d = utils.jbyteArrayToCryptoPPInteger(env, privExp);

	  //create pointer to InvertibleRSAFunction object
	  InvertibleRSAFunction* invRsaFunc = new InvertibleRSAFunction;

	  //initialize the trapdoor object with the RSA values
	  invRsaFunc->Initialize(n, e, d);

	  RSA::PrivateKey privateKey(*invRsaFunc);
	  
	  ((RSAES_OAEP_SHA_Decryptor * ) decryptor)->AccessKey().AssignFrom(privateKey);
}
Exemple #8
0
void cKeysStorage::GenerateRSAKey(unsigned int keyLength, std::string fileName)
{
	using namespace CryptoPP;
	AutoSeededRandomPool rng;
	// Generate Parameters
	InvertibleRSAFunction params;
	params.GenerateRandomWithKeySize(rng, keyLength);
	
	// Create Keys
	CryptoPP::RSA::PrivateKey privateKey(params);
	CryptoPP::RSA::PublicKey publicKey(params);
	
	//mPrvKeys.push_back(privateKey);
	mPrvKeys[mCurrentKey] = privateKey;
	std::cout << "start saving pub file" << std::endl;
	std::cout << "generated file: " << fileName << std::endl;
	savePubFile(mCurrentKey, publicKey, fileName);
	
	mCurrentKey++;
	
	std::cout << "end of GenerateRSAKey" << std::endl;
}
Exemple #9
0
void GenerateKeyPair(std::string& public_key, std::string & private_key)
{
    std::string strprivkey, strpubkey;    
    AutoSeededRandomPool rng;
    InvertibleRSAFunction privkey;
    
    privkey.Initialize(rng, 1024);
    
    Base64Encoder privkeysink(new StringSink(strprivkey), false);
    privkey.DEREncode(privkeysink);
    privkeysink.MessageEnd();
        
    RSAFunction pubkey(privkey);
    
    Base64Encoder pubkeysink(new StringSink(strpubkey), false);
    pubkey.DEREncode(pubkeysink);
    pubkeysink.MessageEnd();
    
    public_key = strpubkey;
    
    private_key = strprivkey;	
}
RSAKeys genRSAKeys(){
  AutoSeededRandomPool rnd;
  InvertibleRSAFunction params;
  params.GenerateRandomWithKeySize(rnd, 16000);

  RSAKeys keys;
  keys.privateKey = new RSA::PrivateKey(params);
  keys.publicKey = new RSA::PublicKey(params);

  /*
  //Test code
  saveRSAPriKey(*(keys.privateKey), "private");
  saveRSAPubKey(*(keys.publicKey), "public");

  
  ifstream ipub("private");
  string pubKey;
  getline(ipub, pubKey, (char)ipub.eof());
  ipub.close();
  ofstream opub("private1");
  opub << pubKey;
  opub.close();

  RSA::PublicKey pubK;
  RSA::PrivateKey privK;
  loadRSAPubKey(pubK, "public");
  loadRSAPriKey(privK, "private1");

  string plain = "RSA Encryption";

  string cipher = RSAEncrypt(pubK, plain);
  cout << cipher << endl;
  string recovered = RSADecrypt(privK, cipher);
  cout << recovered << endl;
  */

  return keys;
}
bool CClientCreditsList::CreateKeyPair()
{
	try{
		AutoSeededRandomPool rng;
		InvertibleRSAFunction privkey;
		privkey.Initialize(rng,RSAKEYSIZE);

		Base64Encoder privkeysink(new FileSink(CStringA(thePrefs.GetConfigDir() + _T("cryptkey.dat"))));
		privkey.DEREncode(privkeysink);
		privkeysink.MessageEnd();

		if (thePrefs.GetLogSecureIdent())
			AddDebugLogLine(false, _T("Created new RSA keypair"));
	}
	catch(...)
	{
		if (thePrefs.GetVerbose())
			AddDebugLogLine(false, _T("Failed to create new RSA keypair"));
		ASSERT ( false );
		return false;
	}
	return true;
}
Exemple #12
0
int main(int argc, char** argv) {
  using namespace CryptoPP;
  namespace po = boost::program_options;

  std::string publicKeyName, privateKeyName;
  size_t keyLength;


  po::options_description desc("Allowed Options");
  desc.add_options()
    ("help", "produce help message")
    ("length,l", po::value<size_t>(&keyLength)->default_value(1024), "set key length")
    ("pubKey,r", po::value<std::string>(&publicKeyName)->default_value("key.pub"), "set public key name")
    ("privKey,u", po::value<std::string>(&privateKeyName)->default_value("key.pem"), "set private key name")
    ;

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);
  po::notify(vm);    
  
  if (vm.count("help")) {
    std::cout << desc << "\n";
    return 1;
  }
  
  AutoSeededRandomPool prng;

  InvertibleRSAFunction parameters;
  parameters.GenerateRandomWithKeySize(prng, keyLength);

  RSA::PrivateKey privateKey(parameters);
  RSA::PublicKey publicKey(parameters);

  SaveKey(publicKeyName, publicKey);
  SaveKey(privateKeyName, privateKey);
}
Exemple #13
0
void GenKeyPair(string s, int size)
{
	// InvertibleRSAFunction is used directly only because the private key
	// won't actually be used to perform any cryptographic operation;
	// otherwise, an appropriate typedef'ed type from rsa.h would have been used.
	AutoSeededRandomPool rng;
	InvertibleRSAFunction privkey;
	privkey.Initialize(rng, size);

	// With the current version of Crypto++, MessageEnd() needs to be called
	// explicitly because Base64Encoder doesn't flush its buffer on destruction.
	Base64Encoder privkeysink(new FileSink((s+".pri").c_str()));
	privkey.DEREncode(privkeysink);
	privkeysink.MessageEnd();
	 
	// Suppose we want to store the public key separately,
	// possibly because we will be sending the public key to a third party.
	RSAFunction pubkey(privkey);
	
	Base64Encoder pubkeysink(new FileSink((s+".pub").c_str()));
	pubkey.DEREncode(pubkeysink);
	pubkeysink.MessageEnd();
	cout << size << endl;
}
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;
}
void CCollectionCreateDialog::OnBnClickedOk()
{
	//Some users have noted that the collection can at times
	//save a collection with a invalid name...
	OnEnKillFocusCollectionName();

	CString sFileName;
	m_CollectionNameEdit.GetWindowText(sFileName);
	if (!sFileName.IsEmpty())
	{
		m_pCollection->m_sCollectionAuthorName.Empty();
		m_pCollection->SetCollectionAuthorKey(NULL, 0);
		m_pCollection->m_sCollectionName = sFileName;
		m_pCollection->m_bTextFormat = (m_CollectionCreateFormatCheck.GetCheck() == BST_CHECKED);

		CString sFilePath;
		sFilePath.Format(_T("%s\\%s.emulecollection"), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR), m_pCollection->m_sCollectionName);

		using namespace CryptoPP;
		RSASSA_PKCS1v15_SHA_Signer* pSignkey = NULL;
		if (m_CollectionCreateSignNameKeyCheck.GetCheck())
		{
			bool bCreateNewKey = false;
			HANDLE hKeyFile = ::CreateFile(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat"), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
			if (hKeyFile != INVALID_HANDLE_VALUE)
			{
				if (::GetFileSize(hKeyFile, NULL) == 0)
					bCreateNewKey = true;
				::CloseHandle(hKeyFile);
			}
			else
				bCreateNewKey = true;

			if (bCreateNewKey)
			{
				try
				{
					AutoSeededRandomPool rng;
					InvertibleRSAFunction privkey;
					privkey.Initialize(rng, 1024);
					Base64Encoder privkeysink(new FileSink(CStringA(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat"))));
					privkey.DEREncode(privkeysink);
					privkeysink.MessageEnd();
				}
				catch(...)
				{
					ASSERT(0);
				}
			}

			try
			{
				FileSource filesource(CStringA(thePrefs.GetMuleDirectory(EMULE_CONFIGDIR) + _T("collectioncryptkey.dat")), true,new Base64Decoder);
				pSignkey = new RSASSA_PKCS1v15_SHA_Signer(filesource);
				RSASSA_PKCS1v15_SHA_Verifier pubkey(*pSignkey);
				byte abyMyPublicKey[1000];
				ArraySink asink(abyMyPublicKey, 1000);
				pubkey.DEREncode(asink);
				int nLen = asink.TotalPutLength();
				asink.MessageEnd();
				m_pCollection->SetCollectionAuthorKey(abyMyPublicKey, nLen);
			}
			catch(...)
			{
				ASSERT(0);
			}

			m_pCollection->m_sCollectionAuthorName = thePrefs.GetUserNick();
		}

		if (!PathFileExists(sFilePath))
		{
			m_pCollection->WriteToFileAddShared(pSignkey);
		}
		else
		{
			if (AfxMessageBox(GetResString(IDS_COLL_REPLACEEXISTING), MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO) == IDNO)
				return;

			bool bDeleteSuccessful = ShellDeleteFile(sFilePath);
			if (bDeleteSuccessful)
			{
				CKnownFile* pKnownFile = theApp.knownfiles->FindKnownFileByPath(sFilePath);
				if (pKnownFile)
				{
					theApp.sharedfiles->RemoveFile(pKnownFile, true);
					if (pKnownFile->IsKindOf(RUNTIME_CLASS(CPartFile)))
						theApp.emuledlg->transferwnd->GetDownloadList()->ClearCompleted(static_cast<CPartFile*>(pKnownFile));
				}
				m_pCollection->WriteToFileAddShared(pSignkey);
			}
			else
			{
				AfxMessageBox(GetResString(IDS_COLL_ERR_DELETING),MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO);
			}
		}
		
		delete pSignkey;
		pSignkey = NULL;

		OnOK();
	}
}
void
SecTpmFile::generateKeyPairInTpm(const Name& keyName, const KeyParams& params)
{
  string keyURI = keyName.toUri();

  if (doesKeyExistInTpm(keyName, KeyClass::PUBLIC))
    BOOST_THROW_EXCEPTION(Error("public key exists"));
  if (doesKeyExistInTpm(keyName, KeyClass::PRIVATE))
    BOOST_THROW_EXCEPTION(Error("private key exists"));

  string keyFileName = m_impl->maintainMapping(keyURI);

  try {
    switch (params.getKeyType()) {
      case KeyType::RSA: {
        using namespace CryptoPP;

        const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);
        AutoSeededRandomPool rng;
        InvertibleRSAFunction privateKey;
        privateKey.Initialize(rng, rsaParams.getKeySize());

        string privateKeyFileName = keyFileName + ".pri";
        Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
        privateKey.DEREncode(privateKeySink);
        privateKeySink.MessageEnd();

        RSAFunction publicKey(privateKey);
        string publicKeyFileName = keyFileName + ".pub";
        Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
        publicKey.DEREncode(publicKeySink);
        publicKeySink.MessageEnd();

        // set file permission
        chmod(privateKeyFileName.c_str(), 0000400);
        chmod(publicKeyFileName.c_str(), 0000444);
        return;
      }

      case KeyType::EC: {
        using namespace CryptoPP;

        const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);

        CryptoPP::OID curveName;
        switch (ecdsaParams.getKeySize()) {
        case 256:
          curveName = ASN1::secp256r1();
          break;
        case 384:
          curveName = ASN1::secp384r1();
          break;
        default:
          curveName = ASN1::secp256r1();
          break;
        }

        AutoSeededRandomPool rng;

        ECDSA<ECP, SHA256>::PrivateKey privateKey;
        DL_GroupParameters_EC<ECP> cryptoParams(curveName);
        cryptoParams.SetEncodeAsOID(true);
        privateKey.Initialize(rng, cryptoParams);

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

        string privateKeyFileName = keyFileName + ".pri";
        Base64Encoder privateKeySink(new FileSink(privateKeyFileName.c_str()));
        privateKey.DEREncode(privateKeySink);
        privateKeySink.MessageEnd();

        string publicKeyFileName = keyFileName + ".pub";
        Base64Encoder publicKeySink(new FileSink(publicKeyFileName.c_str()));
        publicKey.Save(publicKeySink);
        publicKeySink.MessageEnd();

        // set file permission
        chmod(privateKeyFileName.c_str(), 0000400);
        chmod(publicKeyFileName.c_str(), 0000444);
        return;
      }

      default:
        BOOST_THROW_EXCEPTION(Error("Unsupported key type"));
    }
  }
  catch (const KeyParams::Error& e) {
    BOOST_THROW_EXCEPTION(Error(e.what()));
  }
  catch (const CryptoPP::Exception& e) {
    BOOST_THROW_EXCEPTION(Error(e.what()));
  }
}