示例#1
0
void SPX::Initialize(bool Encryption, const KeyParams &KeyParam)
{
	if (KeyParam.Key().size() != 16 && KeyParam.Key().size() != 24 && KeyParam.Key().size() != 32 && KeyParam.Key().size() != 64)
		throw CryptoSymmetricCipherException("SPX:Initialize", "Invalid key size! Valid sizes are 16, 24, 32 and 64 bytes.");

	_isEncryption = Encryption;
	ExpandKey(KeyParam.Key());
}
示例#2
0
Name
IdentityManager::generateKeyPair
  (const Name& identityName, bool isKsk, const KeyParams& params)
{
  Name keyName = identityStorage_->getNewKeyName(identityName, isKsk);
  privateKeyStorage_->generateKeyPair(keyName, params);
  ptr_lib::shared_ptr<PublicKey> pubKey = privateKeyStorage_->getPublicKey(keyName);
  identityStorage_->addKey(keyName, params.getKeyType(), pubKey->getKeyDer());

  return keyName;
}
示例#3
0
void RHX::Initialize(bool Encryption, const KeyParams &KeyParam)
{
    uint dgtsze = GetIkmSize(m_kdfEngineType);

#if defined(DEBUGASSERT_ENABLED)
    assert(KeyParam.Key().size() >= m_legalKeySizes[0] && KeyParam.Key().size() <= m_legalKeySizes[m_legalKeySizes.size() - 1]);
    if (dgtsze != 0)
        assert(KeyParam.Key().size() % dgtsze == 0);
    assert(KeyParam.Key().size() >= m_ikmSize);
#endif
#if defined(CPPEXCEPTIONS_ENABLED)
    std::string msg = "Invalid key size! Key must be either 16, 24, 32, 64 bytes or, a multiple of the hkdf hash output size.";
    if (KeyParam.Key().size() < m_legalKeySizes[0])
        throw CryptoSymmetricCipherException("RHX:Initialize", msg);
    if (dgtsze != 0 && KeyParam.Key().size() > m_legalKeySizes[3] && (KeyParam.Key().size() % dgtsze) != 0)
        throw CryptoSymmetricCipherException("RHX:Initialize", msg);

    for (size_t i = 0; i < m_legalKeySizes.size(); ++i)
    {
        if (KeyParam.Key().size() == m_legalKeySizes[i])
            break;
        if (i == m_legalKeySizes.size() - 1)
            throw CryptoSymmetricCipherException("RHX:Initialize", msg);
    }
    if (m_kdfEngineType != Digests::None)
    {
        if (KeyParam.Key().size() < m_ikmSize)
            throw CryptoSymmetricCipherException("RHX:Initialize", "Invalid key! HKDF extended mode requires key be at least hash output size.");
    }
#endif

    if (m_kdfEngineType != Digests::None)
        m_kdfEngine = GetDigest(m_kdfEngineType);

    m_isEncryption = Encryption;
    // expand the key
    ExpandKey(Encryption, KeyParam.Key());
    // ready to transform data
    m_isInitialized = true;
}
示例#4
0
void CBC::Initialize(bool Encryption, const KeyParams &KeyParam)
{
#if defined(DEBUGASSERT_ENABLED)
    if (KeyParam.IV().size() == 64)
        assert(HasSSE());
    if (KeyParam.IV().size() == 128)
        assert(HasAVX());
    if (IsParallel())
    {
        assert(ParallelBlockSize() >= ParallelMinimumSize() || ParallelBlockSize() <= ParallelMaximumSize());
        assert(ParallelBlockSize() % ParallelMinimumSize() == 0);
    }
    assert(KeyParam.IV().size() > 15);
    assert(KeyParam.Key().size() > 15);
#endif
#if defined(CPPEXCEPTIONS_ENABLED)
    if (KeyParam.IV().size() == 64 && !HasSSE())
        throw CryptoSymmetricCipherException("CBC:Initialize", "SSE 128bit intrinsics are not available on this system!");
    if (KeyParam.IV().size() == 128 && !HasAVX())
        throw CryptoSymmetricCipherException("CBC:Initialize", "AVX 256bit intrinsics are not available on this system!");
    if (KeyParam.IV().size() < 16)
        throw CryptoSymmetricCipherException("CBC:Initialize", "Requires a minimum 16 bytes of IV!");
    if (KeyParam.Key().size() < 16)
        throw CryptoSymmetricCipherException("CBC:Initialize", "Requires a minimum 16 bytes of Key!");
    if (IsParallel() && ParallelBlockSize() < ParallelMinimumSize() || ParallelBlockSize() > ParallelMaximumSize())
        throw CryptoSymmetricCipherException("CBC:Initialize", "The parallel block size is out of bounds!");
    if (IsParallel() && ParallelBlockSize() % ParallelMinimumSize() != 0)
        throw CryptoSymmetricCipherException("CBC:Initialize", "The parallel block size must be evenly aligned to the ParallelMinimumSize!");
#endif

    m_blockCipher->Initialize(Encryption, KeyParam);
    m_cbcVector = KeyParam.IV();
    m_isEncryption = Encryption;
    m_wideBlock = m_cbcVector.size() == 64 || m_cbcVector.size() == 128;

    if (m_wideBlock)
        m_blockSize = m_cbcVector.size();

    m_isInitialized = true;
}
示例#5
0
void
FilePrivateKeyStorage::generateKeyPair
  (const Name& keyName, const KeyParams& params)
{
  if (doesKeyExist(keyName, KEY_CLASS_PUBLIC))
    throw SecurityException("Public Key already exists");
  if (doesKeyExist(keyName, KEY_CLASS_PRIVATE))
    throw SecurityException("Private Key already exists");

  Blob publicKeyDer;
  Blob privateKeyDer;

  if (params.getKeyType() == KEY_TYPE_RSA) {
    const RsaKeyParams& rsaParams = static_cast<const RsaKeyParams&>(params);

    BIGNUM* exponent = 0;
    RSA* rsa = 0;

    exponent = BN_new();
    if (BN_set_word(exponent, RSA_F4) == 1) {
      rsa = RSA_new();
      if (RSA_generate_key_ex(rsa, rsaParams.getKeySize(), exponent, NULL) == 1) {
        // Encode the public key.
        int length = i2d_RSA_PUBKEY(rsa, NULL);
        publicKeyDer = Blob(ptr_lib::make_shared<vector<uint8_t> >(length), false);
        uint8_t* derPointer = const_cast<uint8_t*>(publicKeyDer.buf());
        i2d_RSA_PUBKEY(rsa, &derPointer);

        // Encode the private key.
        length = i2d_RSAPrivateKey(rsa, NULL);
        vector<uint8_t> pkcs1PrivateKeyDer(length);
        derPointer = &pkcs1PrivateKeyDer[0];
        i2d_RSAPrivateKey(rsa, &derPointer);
        privateKeyDer = encodePkcs8PrivateKey
          (pkcs1PrivateKeyDer, OID(RSA_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerNull>());
      }
    }

    BN_free(exponent);
    RSA_free(rsa);
  }
  else if (params.getKeyType() == KEY_TYPE_ECDSA) {
    const EcdsaKeyParams& ecdsaParams = static_cast<const EcdsaKeyParams&>(params);

    OID parametersOid;
    int curveId = -1;

    // Find the entry in EC_KEY_INFO.
    for (size_t i = 0 ; i < sizeof(EC_KEY_INFO) / sizeof(EC_KEY_INFO[0]); ++i) {
      if (EC_KEY_INFO[i].keySize == ecdsaParams.getKeySize()) {
        curveId = EC_KEY_INFO[i].curveId;
        parametersOid.setIntegerList
          (EC_KEY_INFO[i].oidIntegerList, EC_KEY_INFO[i].oidIntegerListLength);

        break;
      }
    }
    if (curveId == -1)
      throw SecurityException("Unsupported keySize for KEY_TYPE_ECDSA");

    EC_KEY* ecKey = EC_KEY_new_by_curve_name(curveId);
    if (ecKey != NULL) {
      if (EC_KEY_generate_key(ecKey) == 1) {
        // Encode the public key.
        int length = i2d_EC_PUBKEY(ecKey, NULL);
        vector<uint8_t> opensslPublicKeyDer(length);
        uint8_t* derPointer = &opensslPublicKeyDer[0];
        i2d_EC_PUBKEY(ecKey, &derPointer);
        // Convert the openssl style to ndn-cxx which has the simple AlgorithmIdentifier.
        // Find the bit string which is the second child.
        ptr_lib::shared_ptr<DerNode> parsedNode = DerNode::parse
          (&opensslPublicKeyDer[0], 0);
        const std::vector<ptr_lib::shared_ptr<DerNode> >& children =
          parsedNode->getChildren();
        publicKeyDer = encodeSubjectPublicKeyInfo
          (OID(EC_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerOid>(parametersOid), children[1]);

        // Encode the private key.
        EC_KEY_set_enc_flags(ecKey, EC_PKEY_NO_PARAMETERS | EC_PKEY_NO_PUBKEY);
        length = i2d_ECPrivateKey(ecKey, NULL);
        vector<uint8_t> pkcs1PrivateKeyDer(length);
        derPointer = &pkcs1PrivateKeyDer[0];
        i2d_ECPrivateKey(ecKey, &derPointer);
        privateKeyDer = encodePkcs8PrivateKey
          (pkcs1PrivateKeyDer, OID(EC_ENCRYPTION_OID),
           ptr_lib::make_shared<DerNode::DerOid>(parametersOid));
      }
    }

    EC_KEY_free(ecKey);
  }
  else
    throw SecurityException("Unsupported key type");

  string keyUri = keyName.toUri();
  string publicKeyFilePath = nameTransform(keyUri, ".pub");
  string privateKeyFilePath = nameTransform(keyUri, ".pri");

  ofstream publicKeyFile(publicKeyFilePath.c_str());
  publicKeyFile << toBase64(publicKeyDer.buf(), publicKeyDer.size(), true);
  ofstream privateKeyFile(privateKeyFilePath.c_str());
  privateKeyFile << toBase64(privateKeyDer.buf(), privateKeyDer.size(), true);

  ::chmod(publicKeyFilePath.c_str(),  S_IRUSR | S_IRGRP | S_IROTH);
  ::chmod(privateKeyFilePath.c_str(), S_IRUSR);
}
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()));
  }
}
 explicit
 SimplePublicKeyParams(const KeyParams& params)
   : KeyParams(params.getKeyType())
 {
   throw KeyParams::Error("Incorrect key parameters (incompatible key type)");
 }