get steam RSA key, build and return cipher
769036
def _get_rsa_key(self):
        '''  '''
        url = 'https://steamcommunity.com/mobilelogin/getrsakey/'
        values = {
                'username': self._username,
                'donotcache' : self._get_donotcachetime(),
        }
        req = self.post(url, data=values)
        data = req.json()
        if not data['success']:
            raise SteamWebError('Failed to get RSA key', data)
        # Construct RSA and cipher
        mod = int(str(data['publickey_mod']), 16)
        exp = int(str(data['publickey_exp']), 16)
        rsa = RSA.construct((mod, exp))
        self.rsa_cipher = PKCS1_v1_5.new(rsa)
        self.rsa_timestamp = data['timestamp']
6598
def get_rsa_pub_key(path):
    '''
    
    '''
    log.debug('salt.crypt.get_rsa_pub_key: Loading public key')
    if HAS_M2:
        with salt.utils.files.fopen(path, 'rb') as f:
            data = f.read().replace(b'RSA ', b'')
        bio = BIO.MemoryBuffer(data)
        key = RSA.load_pub_key_bio(bio)
    else:
        with salt.utils.files.fopen(path) as f:
            key = RSA.importKey(f.read())
    return key
773434
def rsa_encrypt(data, pem, b64_encode=True):
    
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding
    encoded_data = to_binary(data)
    pem = to_binary(pem)
    public_key = serialization.load_pem_public_key(pem, backend=default_backend())
    encrypted_data = public_key.encrypt(
        encoded_data,
        padding=padding.OAEP(
            mgf=padding.MGF1(hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        )
    )
    if b64_encode:
        encrypted_data = base64.b64encode(encrypted_data).decode('utf-8')
    return encrypted_data
1075890
def _load_rsa_private_key(pem):
    """"""
    # ADB uses private RSA keys in pkcs#8 format. 'rsa' library doesn't support
    # them natively. Do some ASN unwrapping to extract naked RSA key
    # (in der-encoded form). See https://www.ietf.org/rfc/rfc2313.txt.
    # Also http://superuser.com/a/606266.
    try:
        der = rsa.pem.load_pem(pem, 'PRIVATE KEY')
        keyinfo, _ = decoder.decode(der)
        if keyinfo[1][0] != univ.ObjectIdentifier(
                '1.2.840.113549.1.1.1'):  # pragma: no cover
            raise ValueError('Not a DER-encoded OpenSSL private RSA key')
        private_key_der = keyinfo[2].asOctets()
    except IndexError:  # pragma: no cover
        raise ValueError('Not a DER-encoded OpenSSL private RSA key')
    return rsa.PrivateKey.load_pkcs1(private_key_der, format='DER')
642524
def main_decrypt(A):
    ""
    profile = get_profile(A)
    localKeys = profile.get('local keys', [])
    if not localKeys:
        localKeys = [make_lock_securely(warn_only = A.ignore_entropy)]
    else:
        localKeys = [crypto.UserLock.private_from_b64(k['private_key']) for k in localKeys]
    if not os.path.exists(A.path):
        error_out("File or directory '{}' does not exist.".format(A.path))
    if os.path.isfile(A.path):
        for k in localKeys:
            print("Attempting decryption with:", k.userID)
            try:
                filename, senderID, decrypted = decrypt_file(A.path, k, base64 = A.base64)
                break
            except ValueError as E:
                pass
        else:
            error_out("Failed to decrypt with all available keys.")
    else:
        error_out("Specified path '{}' is not a file.".format(A.path))
    print("Decrypted file from", senderID)
    print("Saving output to", filename)
    with open(filename, "wb") as O:
        O.write(decrypted)
401925
def DecryptPassword(cipher, key):
		
		import base64
		import hmac
		import sha
		from array import array

		H = UcsUtils.GetShaHash

		cipher = cipher + "\n"
		cipher = base64.decodestring(cipher)
		n = len(cipher) - 16 - 8

		uhash = cipher[:16]
		passwordStream = cipher[16:-8] + "0000"[n & 3:]
		auth = cipher[-8:]

		k_enc, k_auth = H('enc' + key + uhash), H('auth' + key + uhash)
		vauth = hmac.new(cipher[-8:], k_auth, sha).digest()[:8]

		passwordStream = array('L', passwordStream)
		xkey = UcsUtils.Expandkey(k_enc, n + 4)

		for i in xrange(len(passwordStream)):
			passwordStream[i] = passwordStream[i] ^ xkey[i]

		decryptedPassword = passwordStream.tostring()[:n]
		return decryptedPassword
8727
function getAction(key) {
    const keyString = key.toString();

    if (keyString.match(/CERTIFICATE\sREQUEST-{5}$/m)) {
        return 'req';
    }
    else if (keyString.match(/(PUBLIC|PRIVATE)\sKEY-{5}$/m)) {
        return 'rsa';
    }

    return 'x509';
}
292374
function getEncryptionKey (key) {
  key = key || process.env.ENCRYPTION_KEY
  if (!key) throw new Error('encryption key not found')

  const cryptoKey = crypto.createHash('sha256').update(key).digest()
  return cryptoKey
}
275414
function extractReadableKeys (dir, options) {
  const pwd = options.input
  prompt.start()
  prompt.get(promptSchema, (err, { password }) => {
    const key = fs.readFileSync(path.join(pwd, dir, 'sign_key'))
    const pubKey = fs.readFileSync(path.join(pwd, dir, 'sign_key.pub'))

    const decrypted = Crypto.decryptPrivateKey(password, key)

    const privateHex = Buffer.from(decrypted).toString('hex')
    const decryptedPub = Crypto.decryptPubKey(password, pubKey)

    console.log(`Private key (hex): ${privateHex}`)
    console.log(`Public key (base check): ak_${Crypto.encodeBase58Check(decryptedPub)}`)
    console.log(`Public key (hex): ${decryptedPub.toString('hex')}`)
  })
}
925167
def _get_private_key_obj(private_key, passphrase=None):
    '''
    
    '''
    private_key = _text_or_file(private_key)
    private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
    rsaprivkey = M2Crypto.RSA.load_key_string(
        private_key, callback=_passphrase_callback(passphrase))
    evpprivkey = M2Crypto.EVP.PKey()
    evpprivkey.assign_rsa(rsaprivkey)
    return evpprivkey
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))
520990
static function unlock($cipher, $key = null) {
        return openssl_decrypt($cipher, self::_getSecMethod(), Utils::spare($key, self::_geteSecKey()), false, self::_getSecIv());
    }
894165
function getKeys (secret) {
	var hash = crypto.createHash('sha256').update(secret, 'utf8').digest();
	var keypair = naclInstance.crypto_sign_keypair_from_seed(hash);

	return {
		publicKey : Buffer.from(keypair.signPk).toString('hex'),
		privateKey : Buffer.from(keypair.signSk).toString('hex')
	};
}
755032
def sha2_rsa_encrypt(password, salt, public_key):
    
    if not _have_cryptography:
        raise RuntimeError("'cryptography' package is required for sha256_password or caching_sha2_password auth methods")
    message = _xor_password(password + b'\0', salt)
    rsa_key = serialization.load_pem_public_key(public_key, default_backend())
    return rsa_key.encrypt(
        message,
        padding.OAEP(
            mgf=padding.MGF1(algorithm=hashes.SHA1()),
            algorithm=hashes.SHA1(),
            label=None,
        ),
    )
557411
def GenerateKeys(config, overwrite_keys=False):
  """"""
  if not hasattr(key_utils, "MakeCACert"):
    raise OpenSourceKeyUtilsRequiredError(
        "Generate keys can only run with open source key_utils.")
  if (config.Get("PrivateKeys.server_key", default=None) and
      not overwrite_keys):
    print(config.Get("PrivateKeys.server_key"))
    raise KeysAlreadyExistError(
        "Config %s already has keys, use --overwrite_keys to "
        "override." % config.parser)

  length = grr_config.CONFIG["Server.rsa_key_length"]
  print("All keys will have a bit length of %d." % length)
  print("Generating executable signing key")
  executable_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  config.Set("PrivateKeys.executable_signing_private_key",
             executable_key.AsPEM())
  config.Set("Client.executable_signing_public_key",
             executable_key.GetPublicKey().AsPEM())

  print("Generating CA keys")
  ca_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  ca_cert = key_utils.MakeCACert(ca_key)
  config.Set("CA.certificate", ca_cert.AsPEM())
  config.Set("PrivateKeys.ca_key", ca_key.AsPEM())

  print("Generating Server keys")
  server_key = rdf_crypto.RSAPrivateKey.GenerateKey(bits=length)
  server_cert = key_utils.MakeCASignedCert(u"grr", server_key, ca_cert, ca_key)
  config.Set("Frontend.certificate", server_cert.AsPEM())
  config.Set("PrivateKeys.server_key", server_key.AsPEM())

  print("Generating secret key for csrf protection.")
  _GenerateCSRFKey(config)
15626
def cipher(rkey, pt, Nk=4):
    """"""
    assert Nk in {4, 6, 8}
    Nr = Nk + 6

    rkey = rkey.reshape(4*(Nr+1), 32)
    pt = pt.reshape(128)

    # first round
    state = add_round_key(pt, rkey[0:4])

    for i in range(1, Nr):
        state = sub_bytes(state)
        state = shift_rows(state)
        state = mix_columns(state)
        state = add_round_key(state, rkey[4*i:4*(i+1)])

    # final round
    state = sub_bytes(state)
    state = shift_rows(state)
    state = add_round_key(state, rkey[4*Nr:4*(Nr+1)])

    return state
458639
function(algo) {
    switch (algo) {
      //   Algorithm-Specific Fields for RSA secret keys:
      //       - multiprecision integer (MPI) of RSA secret exponent d.
      //       - MPI of RSA secret prime value p.
      //       - MPI of RSA secret prime value q (p < q).
      //       - MPI of u, the multiplicative inverse of p, mod q.
      case enums.publicKey.rsa_encrypt:
      case enums.publicKey.rsa_encrypt_sign:
      case enums.publicKey.rsa_sign:
        return [type_mpi, type_mpi, type_mpi, type_mpi];
      //   Algorithm-Specific Fields for Elgamal secret keys:
      //        - MPI of Elgamal secret exponent x.
      case enums.publicKey.elgamal:
        return [type_mpi];
      //   Algorithm-Specific Fields for DSA secret keys:
      //      - MPI of DSA secret exponent x.
      case enums.publicKey.dsa:
        return [type_mpi];
      //   Algorithm-Specific Fields for ECDSA or ECDH secret keys:
      //       - MPI of an integer representing the secret key.
      case enums.publicKey.ecdh:
      case enums.publicKey.ecdsa:
      case enums.publicKey.eddsa:
        return [type_mpi];
      default:
        throw new Error('Invalid public key encryption algorithm.');
    }
  }