Ejemplo 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());
}
Ejemplo n.º 2
0
std::string Converter::SecByteBlockToString(SecByteBlock data){
	Integer a;
	a.Decode(data.BytePtr(), data.SizeInBytes());
	//cout<< "ze secbyteblock do integera: "<<a<<endl;
	std::ostrstream oss;
	oss << std::hex << a;
	std::string s(oss.str());
	s = s.substr(0, 2*data.SizeInBytes()+1); //Do zapamiêtania. d³ugoœæ stringa z s wynosi 2*d³ugoœæ w bytach plus 1.
	return s;
}
Ejemplo n.º 3
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;
}
Ejemplo n.º 4
0
int main()
{
    string key;
    unsigned int limit;
    int flag;

    cout << "Input key(32Byte from [0-9a-f]):";
    cin >> key;
    cout << "Input upper limit:";
    cin >> limit;

    StringSource ss(key, true, new HexDecoder);
    SecByteBlock bkey((size_t)ss.MaxRetrievable());
    ss.Get(bkey, bkey.size());

    ECB_Mode<AES>::Encryption aes(bkey, bkey.size());
    ECB_Mode<AES>::Encryption aes1(bkey, bkey.size());

    SecByteBlock *outputsbb;
    for(unsigned int i = 0; i < limit; i ++)
    {
        const byte *pi = (const byte *)&i;

        flag = 0;

        StreamTransformationFilter *stf = new StreamTransformationFilter(aes);
        StringSource outputss(pi, (size_t)sizeof(int)/sizeof(byte), true, stf);
        outputsbb = new SecByteBlock((size_t)outputss.MaxRetrievable());
        outputss.Get(*outputsbb, outputsbb->size());

        if(*((unsigned int *)(outputsbb->BytePtr())) < limit &&
                *((unsigned int *)(outputsbb->BytePtr()) + 4) == 0 &&
                *((unsigned int *)(outputsbb->BytePtr()) + 8) == 0 &&
                *((unsigned int *)(outputsbb->BytePtr()) + 12) == 0)
        {
            flag = 1;
        }


        while(!flag)
        {
            StreamTransformationFilter *stf1 = new StreamTransformationFilter(aes1);
            StringSource outputss1(*outputsbb, outputsbb->size(), true, stf1);
            delete outputsbb;
            outputsbb = new SecByteBlock((size_t)outputss1.MaxRetrievable());
            outputss1.Get(*outputsbb, outputsbb->size());

            if(*((unsigned int *)(outputsbb->BytePtr())) < limit &&
                    *((unsigned int *)(outputsbb->BytePtr()) + 4) == 0 &&
                    *((unsigned int *)(outputsbb->BytePtr()) + 8) == 0 &&
                    *((unsigned int *)(outputsbb->BytePtr()) + 12) == 0)
            {
                flag = 1;
                cout << i << ": " << *((unsigned int *)(outputsbb->BytePtr())) << endl;
            }
        }
        delete outputsbb;
    }

    return 0;
}
Ejemplo n.º 5
0
//********************************************************************************************************
Integer Converter::decodeSecByteBlock(SecByteBlock key)
{
    Integer x;
    x.Decode(key.BytePtr(), key.SizeInBytes());
    return x;
}
Ejemplo n.º 6
0
int main()
{
    using namespace CryptoPP;

    AutoSeededRandomPool rng;

    DH                dhA;         //< Diffie-Hellman structure
    DH2               dh2A(dhA);   //< Diffie-Hellman structure
    SecByteBlock      sprivA;      //< static private key
    SecByteBlock      spubA;       //< static public key
    SecByteBlock      eprivA;      //< ephemeral private key
    SecByteBlock      epubA;       //< ephemeral public key
    SecByteBlock      sharedA;     //< shared key

    DH                dhB;         //< Diffie-Hellman structure
    DH2               dh2B(dhA);   //< Diffie-Hellman structure
    SecByteBlock      sprivB;      //< static private key
    SecByteBlock      spubB;       //< static public key
    SecByteBlock      eprivB;      //< ephemeral private key
    SecByteBlock      epubB;       //< ephemeral public key
    SecByteBlock      sharedB;     //< shared key

    std::cout << "Initializing DH parameters" << std::endl;;
    dhA.AccessCryptoParameters().GenerateRandomWithKeySize(rng,1024);
    dhB.AccessCryptoParameters().GenerateRandomWithKeySize(rng,1024);

    std::cout << "Generating Keys" << std::endl;;
    sprivA = SecByteBlock( dh2A.StaticPrivateKeyLength() );
    spubA  = SecByteBlock( dh2A.StaticPublicKeyLength() );
    eprivA = SecByteBlock( dh2A.EphemeralPrivateKeyLength() );
    epubA  = SecByteBlock( dh2A.EphemeralPublicKeyLength() );

    dh2A.GenerateStaticKeyPair(rng,sprivA,spubA);
    dh2A.GenerateEphemeralKeyPair(rng,eprivA, epubA);
    sharedA= SecByteBlock( dh2A.AgreedValueLength() );

    sprivB = SecByteBlock( dh2B.StaticPrivateKeyLength() );
    spubB  = SecByteBlock( dh2B.StaticPublicKeyLength() );
    eprivB = SecByteBlock( dh2B.EphemeralPrivateKeyLength() );
    epubB  = SecByteBlock( dh2B.EphemeralPublicKeyLength() );

    dh2B.GenerateStaticKeyPair(rng,sprivB,spubB);
    dh2B.GenerateEphemeralKeyPair(rng,eprivB, epubB);
    sharedB= SecByteBlock( dh2B.AgreedValueLength() );

    if(!dh2A.Agree(sharedA, sprivA, eprivA, spubB, epubB) )
        std::cerr << "A failed to agree " << std::endl;

    if(!dh2B.Agree(sharedB, sprivB, eprivB, spubA, epubA) )
        std::cerr << "B failed to agree " << std::endl;

    Integer sharedAOut, sharedBOut;
    sharedAOut.Decode(sharedA.BytePtr(), sharedA.SizeInBytes());
    sharedBOut.Decode(sharedB.BytePtr(), sharedB.SizeInBytes());

    std::cout << "shared secret:"
              << "\n A: " << std::hex << sharedAOut
              << "\n B: " << std::hex << sharedBOut
              << std::endl;

}