Load public RSA key, with work-around for keys using
    incorrect header/footer format.

    Read more about RSA encryption with cryptography:
    https://cryptography.io/latest/hazmat/primitives/asymmetric/rsa/
335691
def load_key(pubkey):
    
    try:
        return load_pem_public_key(pubkey.encode(), default_backend())
    except ValueError:
        # workaround for https://github.com/travis-ci/travis-api/issues/196
        pubkey = pubkey.replace('BEGIN RSA', 'BEGIN').replace('END RSA', 'END')
        return load_pem_public_key(pubkey.encode(), default_backend())
230795
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
    
    if not isinstance(crypto_backend, (Backend, MultiBackend)):
        raise ValueError('backend must be a valid Backend object')

    if isinstance(verifying_key, EllipticCurvePublicKey):
        return verifying_key
    elif isinstance(verifying_key, (str, unicode)):
        try:
            return load_der_public_key(
                verifying_key, backend=crypto_backend)
        except:
            try:
                return load_pem_public_key(
                    verifying_key, backend=crypto_backend)
            except Exception:
                raise ValueError('Invalid verifying key format')
    else:
        raise ValueError('Invalid verification key type')
128146
def import_public_rsa_key_from_file(filename):
    
    with open(filename, "rb") as key_file:
        public_key = serialization.load_pem_public_key(
            key_file.read(),
            backend=default_backend())
    return public_key
455572
public static function encrypt($plaintext, PublicKey $rsaPublicKey)
    {
        // Random encryption key
        $random_key = random_bytes(32);

        // Use RSA to encrypt the random key
        $rsaOut = self::rsaEncrypt($random_key, $rsaPublicKey);

        // Generate a symmetric key from the RSA output and plaintext
        $symmetricKey = hash_hmac(
            'sha256',
            $rsaOut,
            $random_key,
            true
        );
        $ephemeral = self::defuseKey(
            $symmetricKey
        );

        // Now we encrypt the actual message
        $symmetric = Base64::encode(
            Crypto::encrypt($plaintext, $ephemeral, true)
        );

        $packaged = \implode(self::SEPARATOR,
            array(
                self::VERSION_TAG,
                Base64::encode($rsaOut),
                $symmetric
            )
        );

        $checksum = \substr(
            \hash('sha256', $packaged),
            0,
            16
        );

        // Return the ciphertext
        return $packaged . self::SEPARATOR . $checksum;
    }
536386
public static PublicKey decodePublicKey(String pemEncoded) throws Exception {
        pemEncoded = removeBeginEnd(pemEncoded);
        byte[] encodedBytes = Base64.getDecoder().decode(pemEncoded);

        X509EncodedKeySpec spec = new X509EncodedKeySpec(encodedBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }
422674
public static PublicKey loadPublicKey(byte[] keyBytes) {
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);

        try {
            KeyFactory factory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
            return publicKey;
        } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
178763
function _formatSubjectPublicKey()
    {
        if (!isset($this->publicKey) || !is_object($this->publicKey)) {
            return false;
        }

        switch (strtolower(get_class($this->publicKey))) {
            case 'crypt_rsa':
                // the following two return statements do the same thing. i dunno.. i just prefer the later for some reason.
                // the former is a good example of how to do fuzzing on the public key
                //return new File_ASN1_Element(base64_decode(preg_replace('#-.+-|[\r\n]#', '', $this->publicKey->getPublicKey())));
                return array(
                    'algorithm' => array('algorithm' => 'rsaEncryption'),
                    'subjectPublicKey' => $this->publicKey->getPublicKey(CRYPT_RSA_PUBLIC_FORMAT_PKCS1)
                );
            default:
                return false;
        }
    }
352681
def decrypt(message, hash: nil)
      # 0
      message = Base64.decode64(message)
      hmac = message[0..63] # 64 bits of hmac signature

      case
      when hash && hmac != hash
        raise Error, "Provided hash mismatch for encrypted file!"
      when hmac != hmac_signature(message[64..-1])
        raise Error, "HMAC signature mismatch for encrypted file!"
      end

      # 1
      rsa_encrypted_aes_key = message[64..319]  # next 256 bits
      rsa_encrypted_aes_iv  = message[320..575] # next 256 bits
      aes_encrypted_message = message[576..-1]

      # 2
      aes_key = @rsa.private_decrypt rsa_encrypted_aes_key
      aes_iv  = @rsa.private_decrypt rsa_encrypted_aes_iv

      # 3
      @cipher.reset
      @cipher.decrypt
      @cipher.key = aes_key
      @cipher.iv  = aes_iv
      content = @cipher.update(aes_encrypted_message) + @cipher.final

      { signature: hmac, content: content }
    rescue OpenSSL::OpenSSLError => e
      raise Error.new(e.message)
    end
1316958
def load_keypair(keypair_file):
    '''
    '''
    from Crypto.PublicKey import RSA

    # Load key
    with open(keypair_file, 'rb') as filey:
        key = RSA.import_key(filey.read())

    return quote_plus(key.publickey().exportKey().decode('utf-8'))
1060096
def PrivateToPublicOpenSSH(key, host):
  
  # Create public key from private key.
  ssh_rsa = '00000007' + base64.b16encode('ssh-rsa')
  # Exponent.
  exponent = '%x' % (key.e,)
  if len(exponent) % 2:
      exponent = '0' + exponent
  ssh_rsa += '%08x' % (len(exponent) / 2,)
  ssh_rsa += exponent
  modulus = '%x' % (key.n,)
  if len(modulus) % 2:
      modulus = '0' + modulus
  if modulus[0] in '89abcdef':
      modulus = '00' + modulus
  ssh_rsa += '%08x' % (len(modulus) / 2,)
  ssh_rsa += modulus
  hash_string = base64.b64encode(base64.b16decode(ssh_rsa.upper()))
  public_key = 'ssh-rsa %s %s' % (hash_string, host)
  return public_key
7456
def key=(*args)
      cert, passphrase = args.flatten
      ssl_context.key = OpenSSL::PKey::RSA.new(cert, passphrase)
    end
335814
function _formatSubjectPublicKey()
    {
        if ($this->publicKey instanceof RSA) {
            // the following two return statements do the same thing. i dunno.. i just prefer the later for some reason.
            // the former is a good example of how to do fuzzing on the public key
            //return new Element(base64_decode(preg_replace('#-.+-|[\r\n]#', '', $this->publicKey->getPublicKey())));
            return array(
                'algorithm' => array('algorithm' => 'rsaEncryption'),
                'subjectPublicKey' => $this->publicKey->getPublicKey(RSA::PUBLIC_FORMAT_PKCS1)
            );
        }

        return false;
    }
934252
def load_pem(cls, private_key, password=None):
        
        # TODO(sam): try to break this in tests
        maybe_path = normpath(private_key)
        if os.path.isfile(maybe_path):
            with open(maybe_path, 'rb') as pkf:
                private_key = pkf.read()
        if not isinstance(private_key, six.binary_type):
            private_key = private_key.encode('utf-8')

        pkey = serialization.load_pem_private_key(
            private_key,
            password=password,
            backend=crypto_backends.default_backend())
        return cls(pkey)
1142405
function getFooterItems (privateKey, items) {
  const pkp = generatePKP(
    privateKey,
    items.dicPopl,
    items.idProvoz,
    items.idPokl,
    items.poradCis,
    formatDate(items.datTrzby),
    formatNumber(items.celkTrzba)
  )
  const bkp = generateBKP(pkp)

  return {
    pkp: {
      attributes: {
        digest: 'SHA256',
        cipher: 'RSA2048',
        encoding: 'base64'
      },
      $value: pkp
    },
    bkp: {
      attributes: {
        digest: 'SHA1',
        encoding: 'base16'
      },
      $value: bkp
    }
  }
}
289738
def x509_rsa_load(txt):
    
    pub_key = import_rsa_key(txt)
    if isinstance(pub_key, rsa.RSAPublicKey):
        return [("rsa", pub_key)]
787638
public static PublicKey loadPublicKey(String publicKeyStr) throws Exception {
		try {
			byte[] buffer = base64.decode(publicKeyStr);
			KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
			X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
			return (RSAPublicKey) keyFactory.generatePublic(keySpec);
		} catch (NoSuchAlgorithmException e) {
			throw new Exception("无此算法");
		} catch (InvalidKeySpecException e) {
			throw new Exception("公钥非法");
		} catch (NullPointerException e) {
			throw new Exception("公钥数据为空");
		}
	}
849889
function encryptPQInnerDataWithRSA(context) {
    // Create the data with hash to be encrypt
    var hash = utility.createSHAHash(context.pqInnerData);
    var dataWithHash = Buffer.concat([hash, context.pqInnerData]);
    if (logger.isDebugEnabled()) {
        logger.debug('Data to be encrypted contains: hash(%s), pqInnerData(%s), total length %s',
            hash.length, context.pqInnerData.length, dataWithHash.length);
    }
    // Encrypt data with RSA
    context.encryptedData = security.cipher.rsaEncrypt(dataWithHash, context.publicKey);
    return context;
}