Derives shared key (DH,ECDH,VKO 34.10). Requires
        private key available

        @param peerkey - other key (may be public only)

        Keyword parameters are algorithm-specific
761313
def derive(self, peerkey, **kwargs):
        
        if not self.cansign:
            raise ValueError("No private key available")
        ctx = libcrypto.EVP_PKEY_CTX_new(self.key, None)
        if ctx is None:
            raise PKeyError("Initailizing derive context")
        if libcrypto.EVP_PKEY_derive_init(ctx) < 1:
            raise PKeyError("derive_init")

        # This is workaround around missing functionality in GOST engine
        # it provides only numeric control command to set UKM, not
        # string one.
        self._configure_context(ctx, kwargs, ["ukm"])
        if libcrypto.EVP_PKEY_derive_set_peer(ctx, peerkey.key) <= 0:
            raise PKeyError("Cannot set peer key")
        if "ukm" in kwargs:
            # We just hardcode numeric command to set UKM here
            if libcrypto.EVP_PKEY_CTX_ctrl(ctx, -1, 1 << 10, 8, 8,
                                           kwargs["ukm"]) <= 0:
                raise PKeyError("Cannot set UKM")
        keylen = c_long(0)
        if libcrypto.EVP_PKEY_derive(ctx, None, byref(keylen)) <= 0:
            raise PKeyError("computing shared key length")
        buf = create_string_buffer(keylen.value)
        if libcrypto.EVP_PKEY_derive(ctx, buf, byref(keylen)) <= 0:
            raise PKeyError("computing actual shared key")
        libcrypto.EVP_PKEY_CTX_free(ctx)
        return buf.raw[:int(keylen.value)]
386578
public boolean checkKeyBelongsToNode(byte[] key, int nodeId) {
        List<Integer> nodePartitions = cluster.getNodeById(nodeId).getPartitionIds();
        List<Integer> replicatingPartitions = getReplicatingPartitionList(key);
        // remove all partitions from the list, except those that belong to the
        // node
        replicatingPartitions.retainAll(nodePartitions);
        return replicatingPartitions.size() > 0;
    }
1038724
function generatePskSecret(ecdhForLocalDevice, remotePeerPublicKey,
                                  pskIdentityField) {
  var sxy = ecdhForLocalDevice.computeSecret(remotePeerPublicKey);
  return HKDF(module.exports.SHA256, sxy, pskIdentityField)
    .derive('', module.exports.AES_256_KEY_SIZE);
}
781047
public static PrivateKey generatePrivateKey(BigInteger modulus, BigInteger privateExponent) {
		return SecureUtil.generatePrivateKey(ALGORITHM_RSA.getValue(), new RSAPrivateKeySpec(modulus, privateExponent));
	}
796439
func DeriveSharedSecret(private PrivateKey, public PublicKey) ([]byte, error) {
	// Create context for the shared secret derivation
	dhCtx := C.EVP_PKEY_CTX_new(private.evpPKey(), nil)
	if dhCtx == nil {
		return nil, errors.New("failed creating shared secret derivation context")
	}
	defer C.EVP_PKEY_CTX_free(dhCtx)

	// Initialize the context
	if int(C.EVP_PKEY_derive_init(dhCtx)) != 1 {
		return nil, errors.New("failed initializing shared secret derivation context")
	}

	// Provide the peer's public key
	if int(C.EVP_PKEY_derive_set_peer(dhCtx, public.evpPKey())) != 1 {
		return nil, errors.New("failed adding peer public key to context")
	}

	// Determine how large of a buffer we need for the shared secret
	var buffLen C.size_t
	if int(C.EVP_PKEY_derive(dhCtx, nil, &buffLen)) != 1 {
		return nil, errors.New("failed determining shared secret length")
	}

	// Allocate a buffer
	buffer := C.X_OPENSSL_malloc(buffLen)
	if buffer == nil {
		return nil, errors.New("failed allocating buffer for shared secret")
	}
	defer C.X_OPENSSL_free(buffer)

	// Derive the shared secret
	if int(C.EVP_PKEY_derive(dhCtx, (*C.uchar)(buffer), &buffLen)) != 1 {
		return nil, errors.New("failed deriving the shared secret")
	}

	secret := C.GoBytes(unsafe.Pointer(buffer), C.int(buffLen))
	return secret, nil
}
452509
private KeyScope cascadeChildKeys(final KeyScope rootScope) {
        final Map<String, KeyDef> res = new HashMap<>(rootScope.keyDefinition);
        cascadeChildKeys(rootScope, res, "");
        return new KeyScope(rootScope.id, rootScope.name, res, new ArrayList<>(rootScope.childScopes));
    }
384520
def shared_secret(other_jwk)
      other_jwk = from(other_jwk) if not other_jwk.is_a?(JOSE::JWK)
      raise ArgumentError, "key types must match" if other_jwk.kty.class != kty.class
      raise ArgumentError, "key type does not support shared secret computations" if not kty.respond_to?(:derive_key)
      return kty.derive_key(other_jwk)
    end
763217
def setup_key_pair
      public_key, private_key = generate_key
      key_name = "foreman-#{id}#{Foreman.uuid}"
      client.create_ssh_key key_name, public_key
      KeyPair.create! :name => key_name, :compute_resource_id => id, :secret => private_key
    rescue StandardError => e
      logger.warn 'failed to generate key pair'
      logger.error e.message
      logger.error e.backtrace.join("\n")
      destroy_key_pair
      raise
    end
213880
def generate_ec_key
      OpenSSL::PKey::EC.new.tap do |ec|
        ec.group = OpenSSL::PKey::EC::Group.new(CURVE_NAME)
        ec.generate_key
        # https://bugs.ruby-lang.org/issues/8177
        ec.define_singleton_method(:private?) { private_key? }
        ec.define_singleton_method(:public?) { public_key? }
      end
    end
1259909
function WalletKey(options, network) {
  if (!(this instanceof WalletKey))
    return new WalletKey(options, network);

  KeyRing.call(this, options, network);

  this.keyType = Path.types.HD;

  this.id = null;
  this.wid = -1;
  this.name = null;
  this.account = -1;
  this.branch = -1;
  this.index = -1;
}
314573
public KeyPair toEC(boolean includePrivateParameters, Provider provider) {

        if (provider == null) {
            // Our default provider for this class
            provider = Security.getProvider("SunEC");
        }

        if (!JsonWebKeyType.EC.equals(kty) && !JsonWebKeyType.EC_HSM.equals(kty)) {
            throw new IllegalArgumentException("Not an EC key.");
        }

        try {
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", provider);

            ECGenParameterSpec gps = new ECGenParameterSpec(CURVE_TO_SPEC_NAME.get(crv));
            kpg.initialize(gps);

            // Generate dummy keypair to get parameter spec.
            KeyPair apair = kpg.generateKeyPair();
            ECPublicKey apub = (ECPublicKey) apair.getPublic();
            ECParameterSpec aspec = apub.getParams();

            ECPoint ecPoint = new ECPoint(new BigInteger(1, x), new BigInteger(1, y));

            KeyPair realKeyPair;

            if (includePrivateParameters) {
                realKeyPair = new KeyPair(getECPublicKey(ecPoint, aspec, provider),
                        getECPrivateKey(d, aspec, provider));
            } else {
                realKeyPair = new KeyPair(getECPublicKey(ecPoint, aspec, provider), null);
            }

            return realKeyPair;
        } catch (GeneralSecurityException e) {
            throw new IllegalStateException(e);
        }
    }
55632
def derive_key(seed_key, seed_rand, rounds, password=None, keyfile=None):
    
    if password == '': password = None
    if keyfile == '': keyfile = None
    if password is None and keyfile is None:
        raise ValueError("Password and/or keyfile is required.")
        
    if password is None:
        masterkey = key_from_keyfile(keyfile)
    elif password and keyfile:
        passwordkey = key_from_password(password)
        filekey = key_from_keyfile(keyfile)
        sha = SHA256.new()
        sha.update(passwordkey + filekey)
        masterkey = sha.digest()
    else:
        masterkey = key_from_password(password)

    # Create the key that is needed to...
    final_key = transform_key(masterkey, seed_key=seed_key, seed_rand=seed_rand, rounds=rounds)
    
    return final_key
958929
public void addPrivateKey(PrivateKey key, NetworkParameters network) {
      _privateKeys.put(key.getPublicKey(), key);
      addPublicKey(key.getPublicKey(), network);
   }
396951
public Key generateSharedKey() throws KeyException {
        javax.crypto.spec.SecretKeySpec sharedKey = null;
        try {
            if (crypto != null) {
                sharedKey = new javax.crypto.spec.SecretKeySpec(crypto.generate3DESKey(), 0, 24, "3DES");
            }

            if (sharedKey != null) {
                return sharedKey;
            } else {
                throw new com.ibm.websphere.crypto.KeyException("Key could not be generated.");
            }

        } catch (Exception e) {
            com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.security.audit.AuditEncryptionImpl.generateKey", "98", this);
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Error generating key.", new Object[] { e });

            if (e instanceof KeyException)
                throw (KeyException) e;
            else
                throw new KeyException(e.getMessage(), e);
        }
    }
932047
public static PrivateKey createPrivateKey(byte[] privateKey) {
    if (privateKey == null) {
      return null;
    }

    try {
      KeyFactory fac = KeyFactory.getInstance("RSA");
      EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
      return fac.generatePrivate(spec);
    }
    catch (NoSuchAlgorithmException e) {
      throw new IllegalStateException(e);
    }
    catch (InvalidKeySpecException e) {
      throw new IllegalStateException(e);
    }
  }
1111621
public byte[] encryptSharedKey(Key sharedKey, Key publicKey) throws java.io.IOException {
        byte[] encryptedSharedKey = null;
        if (sharedKey == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "ERROR!!! shared key is null!");
            }
            return null;
        }
        byte[] encodedPublicKey = publicKey.getEncoded();
        encryptor = new AuditKeyEncryptor(encodedPublicKey);
        byte[] encodedSharedKey = sharedKey.getEncoded();
        encryptedSharedKey = encryptor.encrypt(encodedSharedKey);
        return encryptedSharedKey;
    }
816465
private static PrivateKey getPrivateKey(final String algorithm, final File privateKeyFile) {
		return getPrivateKeyFromBytes(algorithm, readBytes(privateKeyFile));
	}