Get shared session key using Elliptic Curve Diffie-Hellman.
171322
def ecdh(self, identity, pubkey):
        """"""
        curve_name = identity.get_curve_name(ecdh=True)
        log.debug('"%s" shared session key (%s) for %r from %s',
                  identity.to_string(), curve_name, pubkey, self)
        try:
            result = self._defs.get_ecdh_session_key(
                self.conn,
                identity=self._identity_proto(identity),
                peer_public_key=pubkey,
                ecdsa_curve_name=curve_name)
            log.debug('result: %s', result)
            assert len(result.session_key) in {65, 33}  # NIST256 or Curve25519
            assert result.session_key[:1] == b'\x04'
            return bytes(result.session_key)
        except self._defs.TrezorFailure as e:
            msg = '{} error: {}'.format(self, e)
            log.debug(msg, exc_info=True)
            raise interface.DeviceError(msg)
816995
def compressedpubkey(self):
        
        secret = unhexlify(repr(self._wif))
        order = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1).curve.generator.order()
        p = ecdsa.SigningKey.from_string(
            secret, curve=ecdsa.SECP256k1).verifying_key.pubkey.point
        x_str = ecdsa.util.number_to_string(p.x(), order)
        y_str = ecdsa.util.number_to_string(p.y(), order)
        compressed = hexlify(
            chr(2 + (p.y() & 1)).encode('ascii') + x_str
        ).decode('ascii')
        uncompressed = hexlify(
            chr(4).encode('ascii') + x_str + y_str).decode(
            'ascii')
        return [compressed, uncompressed]
649240
def _get_session(region, key, keyid, profile):
    '''
    
    '''
    if profile:
        if isinstance(profile, six.string_types):
            _profile = __salt__['config.option'](profile)
        elif isinstance(profile, dict):
            _profile = profile
        key = _profile.get('key', None)
        keyid = _profile.get('keyid', None)
        region = _profile.get('region', None)

    if not region and __salt__['config.option']('datapipeline.region'):
        region = __salt__['config.option']('datapipeline.region')

    if not region:
        region = 'us-east-1'

    return boto3.session.Session(
        region_name=region,
        aws_secret_access_key=key,
        aws_access_key_id=keyid,
    )
1159767
def encrypters(self):
        """"""
        return set(m.encrypter for m in self._sessionkeys if isinstance(m, PKESessionKey))
871161
public void deriveSrtcpKeys() {
        // compute the session encryption key
        byte label = 3;
        computeIv(label);

        KeyParameter encryptionKey = new KeyParameter(masterKey);
        cipher.init(true, encryptionKey);
        Arrays.fill(masterKey, (byte)0);

        cipherCtr.getCipherStream(cipher, encKey, policy.getEncKeyLength(), ivStore);

        if (authKey != null) {
            label = 4;
            computeIv(label);
            cipherCtr.getCipherStream(cipher, authKey, policy.getAuthKeyLength(), ivStore);

            switch ((policy.getAuthType())) {
	            case SRTPPolicy.HMACSHA1_AUTHENTICATION:
	                KeyParameter key =  new KeyParameter(authKey);
	                mac.init(key);
	                break;
	
	            default:
	                break;
            }
        }
        Arrays.fill(authKey, (byte)0);

        // compute the session salt
        label = 5;
        computeIv(label);
        cipherCtr.getCipherStream(cipher, saltKey, policy.getSaltKeyLength(), ivStore);
        Arrays.fill(masterSalt, (byte)0);

        // As last step: initialize cipher with derived encryption key.
        if (cipherF8 != null) {
            SRTPCipherF8.deriveForIV(cipherF8, encKey, saltKey);
        }
        encryptionKey = new KeyParameter(encKey);
        cipher.init(true, encryptionKey);
        Arrays.fill(encKey, (byte)0);
    }
575742
def step2(self, pub_key, salt):
        """"""
        self._check_initialized()
        pk_str = binascii.hexlify(pub_key).decode()
        salt = binascii.hexlify(salt).decode()
        self.client_session_key, _, _ = self.session.process(pk_str, salt)
        _LOGGER.debug('Client session key: %s', self.client_session_key)

        # Generate client public and session key proof.
        client_public = self.session.public
        client_session_key_proof = self.session.key_proof
        _LOGGER.debug('Client public: %s, proof: %s',
                      client_public, client_session_key_proof)

        if not self.session.verify_proof(self.session.key_proof_hash):
            raise AuthenticationError('proofs do not match (mitm?)')
        return client_public, client_session_key_proof
870689
public byte[] decryptSharedKey(byte[] sharedKey, Key pKey) throws java.io.IOException {
        byte[] decryptedSharedKey = null;
        if (sharedKey == null) {
            if (tc.isDebugEnabled()) {
                Tr.debug(tc, "ERROR!!! shared key is null!");
            }
            return null;
        }

        if (encryptor == null) {
            byte[] encodedPublicKey = pKey.getEncoded();
            encryptor = new AuditKeyEncryptor(encodedPublicKey);
        }

        byte[] encodedPublicKey = pKey.getEncoded();

        decryptedSharedKey = encryptor.decrypt(sharedKey);

        return decryptedSharedKey;
    }
831684
def _get_private_key(cls, private_key_path, private_key_passphrase):
        """"""
        if private_key_path is None or private_key_passphrase is None:
            return None

        with open(private_key_path, 'rb') as key:
            p_key = serialization.load_pem_private_key(
                key.read(),
                password=private_key_passphrase.encode(),
                backend=default_backend())

        return p_key.private_bytes(
            encoding=serialization.Encoding.DER,
            format=serialization.PrivateFormat.PKCS8,
            encryption_algorithm=serialization.NoEncryption())
954958
def _compute_key(self, id, nbytes):
        """"""
        m = Message()
        m.add_mpint(self.K)
        m.add_bytes(self.H)
        m.add_byte(b(id))
        m.add_bytes(self.session_id)
        out = sofar = sha1(m.asbytes()).digest()
        while len(out) < nbytes:
            m = Message()
            m.add_mpint(self.K)
            m.add_bytes(self.H)
            m.add_bytes(sofar)
            digest = sha1(m.asbytes()).digest()
            out += digest
            sofar += digest
        return out[:nbytes]
716027
def generate_session_id(self):
        """"""
        secret_key = self._config.secret_key
        while True:
            rand = os.urandom(16)
            now = time.time()
            session_id = sha1(utf8("%s%s%s%s" % (
                rand, now, self.handler.request.remote_ip, secret_key)))
            session_id = session_id.hexdigest()
            if session_id not in self.store:
                break

        return session_id
407217
def get_common_secret(self, server_public, client_public):
        
        return self.hash(self.pad(client_public), self.pad(server_public))
77850
function getKey() {
      let paramString =
        width + 'x' + height + '-'
        + path
        + (is2x ? '-@2x' : '')
        + (bg ? `_${bg}` : '')
        + (crop ? '_crop' : '')
        + (mode ? `_${mode}` : '')
        + (trim ? '_trim' : '');

      return paramString + '-' + crypto.createHash('sha1').update(paramString).digest('hex');
    }
382419
def get_session_data(ctx, username, password, salt, server_public, private, preset):
    """"""
    session = SRPClientSession(
        SRPContext(username, password, prime=preset[0], generator=preset[1]),
        private=private)

    session.process(server_public, salt, base64=True)

    click.secho('Client session key: %s' % session.key_b64)
    click.secho('Client session key proof: %s' % session.key_proof_b64)
    click.secho('Client session key hash: %s' % session.key_proof_hash_b64)
569299
def _compute_public_key(self):
        

        if self.algorithm == 'dsa':
            params = self['private_key_algorithm']['parameters']
            return Integer(pow(
                params['g'].native,
                self['private_key'].parsed.native,
                params['p'].native
            ))

        if self.algorithm == 'rsa':
            key = self['private_key'].parsed
            return RSAPublicKey({
                'modulus': key['modulus'],
                'public_exponent': key['public_exponent'],
            })

        if self.algorithm == 'ec':
            curve_type, details = self.curve

            if curve_type == 'implicit_ca':
                raise ValueError(unwrap(
                    '''
                    Unable to compute public key for EC key using Implicit CA
                    parameters
                    '''
                ))

            if curve_type == 'specified':
                if details['field_id']['field_type'] == 'characteristic_two_field':
                    raise ValueError(unwrap(
                        '''
                        Unable to compute public key for EC key over a
                        characteristic two field
                        '''
                    ))

                curve = PrimeCurve(
                    details['field_id']['parameters'],
                    int_from_bytes(details['curve']['a']),
                    int_from_bytes(details['curve']['b'])
                )
                base_x, base_y = self['private_key_algorithm']['parameters'].chosen['base'].to_coords()
                base_point = PrimePoint(curve, base_x, base_y)

            elif curve_type == 'named':
                if details not in ('secp192r1', 'secp224r1', 'secp256r1', 'secp384r1', 'secp521r1'):
                    raise ValueError(unwrap(
                        '''
                        Unable to compute public key for EC named curve %s,
                        parameters not currently included
                        ''',
                        details
                    ))

                base_point = {
                    'secp192r1': SECP192R1_BASE_POINT,
                    'secp224r1': SECP224R1_BASE_POINT,
                    'secp256r1': SECP256R1_BASE_POINT,
                    'secp384r1': SECP384R1_BASE_POINT,
                    'secp521r1': SECP521R1_BASE_POINT,
                }[details]

            public_point = base_point * self['private_key'].parsed['private_key'].native
            return ECPointBitString.from_coords(public_point.x, public_point.y)
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
393801
def pkdecrypt(self, conn):
        """"""
        for msg in [b'S INQUIRE_MAXLEN 4096', b'INQUIRE CIPHERTEXT']:
            keyring.sendline(conn, msg)

        line = keyring.recvline(conn)
        assert keyring.recvline(conn) == b'END'
        remote_pubkey = parse_ecdh(line)

        identity = self.get_identity(keygrip=self.keygrip)
        ec_point = self.client.ecdh(identity=identity, pubkey=remote_pubkey)
        keyring.sendline(conn, b'D ' + _serialize_point(ec_point))
782399
def get_real_stored_key(self, session_key):
        
        prefix = settings.SESSION_REDIS_PREFIX
        if not prefix:
            return session_key
        return ':'.join([prefix, session_key])