Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)

The reverse of the above function.
546613
function pemToRsaSSHKey(pem, comment) {
    assert.equal('string', typeof (pem), 'typeof pem');

    var k = sshpk.parseKey(pem, 'pem');
    k.comment = comment;
    return (k.toString('ssh'));
  }
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
775117
def process_pkcs7(self, data, name):
        
        from cryptography.hazmat.backends.openssl.backend import backend
        from cryptography.hazmat.backends.openssl.x509 import _Certificate

        # DER conversion
        is_pem = startswith(data, '-----')
        if self.re_match(r'^[a-zA-Z0-9-\s+=/]+$', data):
            is_pem = True

        try:
            der = data
            if is_pem:
                data = data.decode('utf8')
                data = re.sub(r'\s*-----\s*BEGIN\s+PKCS7\s*-----', '', data)
                data = re.sub(r'\s*-----\s*END\s+PKCS7\s*-----', '', data)
                der = base64.b64decode(data)

            bio = backend._bytes_to_bio(der)
            pkcs7 = backend._lib.d2i_PKCS7_bio(bio.bio, backend._ffi.NULL)
            backend.openssl_assert(pkcs7 != backend._ffi.NULL)
            signers = backend._lib.PKCS7_get0_signers(pkcs7, backend._ffi.NULL, 0)
            backend.openssl_assert(signers != backend._ffi.NULL)
            backend.openssl_assert(backend._lib.sk_X509_num(signers) > 0)
            x509_ptr = backend._lib.sk_X509_value(signers, 0)
            backend.openssl_assert(x509_ptr != backend._ffi.NULL)
            x509_ptr = backend._ffi.gc(x509_ptr, backend._lib.X509_free)
            x509 = _Certificate(backend, x509_ptr)

            self.num_pkcs7_cert += 1

            return [self.process_x509(x509, name=name, pem=False, source='pkcs7-cert', aux='')]

        except Exception as e:
            logger.debug('Error in PKCS7 processing %s: %s' % (name, e))
            self.trace_logger.log(e)
1191541
def process_pem_rsakey(self, data, name, idx):
        
        from cryptography.hazmat.primitives.serialization import load_der_public_key
        from cryptography.hazmat.primitives.serialization import load_der_private_key
        try:
            if startswith(data, '-----BEGIN RSA PUBLIC KEY') or startswith(data, '-----BEGIN PUBLIC KEY'):
                rsa = load_der_public_key(pem_to_der(data), self.get_backend())
                public_numbers = rsa.public_numbers()
            elif startswith(data, '-----BEGIN RSA PRIVATE KEY') or startswith(data, '-----BEGIN PRIVATE KEY'):
                rsa = load_der_private_key(pem_to_der(data), None, self.get_backend())
                public_numbers = rsa.private_numbers().public_numbers
            else:
                return None
            self.num_rsa_keys += 1
            self.num_rsa += 1

            js = collections.OrderedDict()
            js['type'] = 'pem-rsa-key'
            js['fname'] = name
            js['idx'] = idx
            js['pem'] = data
            js['e'] = '0x%x' % public_numbers.e
            js['n'] = '0x%x' % public_numbers.n

            if self.has_fingerprint(public_numbers.n):
                logger.warning('Fingerprint found in PEM RSA key %s ' % name)
                self.mark_and_add_effort(public_numbers.n, js)

                if self.do_print:
                    print(json.dumps(js))

            return TestResult(js)

        except Exception as e:
            logger.debug('Pubkey loading error: %s : %s [%s] : %s' % (name, idx, data[:20], e))
            self.trace_logger.log(e)
161503
def generate_private_key(key_type):
    
    if key_type == u'rsa':
        return rsa.generate_private_key(
            public_exponent=65537, key_size=2048, backend=default_backend())
    raise ValueError(key_type)
1042691
function convertPublicKey(pk) {
    var z = new Uint8Array(32), x = gf(), a = gf(), b = gf();
    unpack25519(x, pk);
    A(a, x, gf1);
    Z(b, x, gf1);
    inv25519(a, a);
    M(a, a, b);
    pack25519(z, a);
    return z;
}
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'))
181025
def create_binary_security_token(key_file):
    
    node = etree.Element(
        ns_id('BinarySecurityToken', ns.wssens),
        nsmap={ns.wssens[0]: ns.wssens[1]})
    node.set(ns_id('Id', ns.wsuns), get_unique_id())
    node.set('EncodingType', ns.wssns[1] + 'Base64Binary')
    node.set('ValueType', BINARY_TOKEN_TYPE)

    with open(key_file) as fh:
        cert = crypto.load_certificate(crypto.FILETYPE_PEM, fh.read())
        node.text = base64.b64encode(
            crypto.dump_certificate(crypto.FILETYPE_ASN1, cert))
    return node
1132426
def rsa_public_key_pkcs8_to_pkcs1(pkcs8_key):
    """"""
    decoded_values = decoder.decode(pkcs8_key, asn1Spec=PublicKeyInfo())

    try:
        decoded_key = decoded_values[0]
    except IndexError:
        raise ValueError("Invalid public key encoding.")

    return decoded_key["publicKey"].asOctets()
1148748
private static function loadKeyFromPEM($pem, $password = null)
    {
        if (preg_match('#DEK-Info: (.+),(.+)#', $pem, $matches)) {
            $pem = self::decodePem($pem, $matches, $password);
        }

        $res = openssl_pkey_get_private($pem);
        if ($res === false) {
            $res = openssl_pkey_get_public($pem);
        }
        Assertion::false($res === false, 'Unable to load the key');

        $details = openssl_pkey_get_details($res);
        Assertion::isArray($details, 'Unable to get details of the key');
        Assertion::keyExists($details, 'type', 'Unable to get details of the key');

        switch ($details['type']) {
            case OPENSSL_KEYTYPE_EC:
                $ec_key = new ECKey($pem);

                return $ec_key->toArray();
            case OPENSSL_KEYTYPE_RSA:
                 $rsa_key = new RSAKey($pem);

                 return $rsa_key->toArray();
            default:
                throw new \InvalidArgumentException('Unsupported key type');
        }
    }
245569
def make_rsa_keypair(bits):
    
    private_key = rsa.generate_private_key(
        public_exponent=65537,
        key_size=bits,
        backend=default_backend(),
    )
    private_pem = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.TraditionalOpenSSL,
        encryption_algorithm=serialization.NoEncryption(),
    )
    public_pem = private_key.public_key().public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo,
    )
    return private_pem, public_pem
1015389
function generateBKP (pkp) {
  const buffer = new Buffer(pkp, 'base64')
  const hash = crypto.createHash('sha1')
  hash.update(buffer)
  const sha1str = hash.digest('hex').toUpperCase()
  return sha1str.match(/(.{1,8})/g).join('-')
}
1367722
def _convert_public_key(ecdsa_curve_name, result):
    """"""
    if ecdsa_curve_name == 'nist256p1':
        if (result[64] & 1) != 0:
            result = bytearray([0x03]) + result[1:33]
        else:
            result = bytearray([0x02]) + result[1:33]
    else:
        result = result[1:]
        keyX = bytearray(result[0:32])
        keyY = bytearray(result[32:][::-1])
        if (keyX[31] & 1) != 0:
            keyY[31] |= 0x80
        result = b'\x00' + bytes(keyY)
    return bytes(result)
53766
private RSAPrivateKey loadPrivateKeyFromPEMFile(String filename) {
        try {
            String publicKeyFile = FileReader.readFileFromClassPathOrPath(filename);
            byte[] publicKeyBytes = DatatypeConverter.parseBase64Binary(publicKeyFile.replace("-----BEGIN RSA PRIVATE KEY-----", "").replace("-----END RSA PRIVATE KEY-----", ""));
            return (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(publicKeyBytes));
        } catch (Exception e) {
            throw new RuntimeException("Exception reading private key from PEM file", e);
        }
    }
1026649
def generate_ssh_key():
    

    key = rsa.generate_private_key(
        backend=default_backend(),
        public_exponent=65537,
        key_size=4096
        )
    private_key = key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.PKCS8,
        serialization.NoEncryption())
    public_key = key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH
    )

    return private_key, public_key
93892
function rsaPublicKeyPem(modulus_b64, exponent_b64) {
 
    var modulus = new Buffer(modulus_b64, 'base64');
    var exponent = new Buffer(exponent_b64, 'base64');
 
    var modulus_hex = modulus.toString('hex')
    var exponent_hex = exponent.toString('hex')
 
    modulus_hex = prepadSigned(modulus_hex)
    exponent_hex = prepadSigned(exponent_hex)
 
    var modlen = modulus_hex.length/2
    var explen = exponent_hex.length/2
 
    var encoded_modlen = encodeLengthHex(modlen)
    var encoded_explen = encodeLengthHex(explen)
    var encoded_pubkey = '30' + 
        encodeLengthHex(
            modlen + 
            explen + 
            encoded_modlen.length/2 + 
            encoded_explen.length/2 + 2
        ) + 
        '02' + encoded_modlen + modulus_hex +
        '02' + encoded_explen + exponent_hex;

    var der_b64 = new Buffer(encoded_pubkey, 'hex').toString('base64');

    var pem = '-----BEGIN RSA PUBLIC KEY-----\n' 
        + der_b64.match(/.{1,64}/g).join('\n') 
        + '\n-----END RSA PUBLIC KEY-----\n';
 
    return pem
}
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key