Convert a public key in sec binary format to a public pair.
764227
def sec_to_public_pair(pubkey):
    """"""
    x = string_to_number(pubkey[1:33])
    sec0 = pubkey[:1]
    if sec0 not in (b'\2', b'\3'):
        raise Exception("Compressed pubkey expected")

    def public_pair_for_x(generator, x, is_even):
        curve = generator.curve()
        p = curve.p()
        alpha = (pow(x, 3, p) + curve.a() * x + curve.b()) % p
        beta = ecdsa.numbertheory.square_root_mod_prime(alpha, p)
        if is_even == bool(beta & 1):
            return (x, p - beta)
        return (x, beta)

    return public_pair_for_x(ecdsa.ecdsa.generator_secp256k1, x, is_even=(sec0 == b'\2'))
48121
def ed25519_generate_key_pair_from_secret(secret):
    

    # if you want to do this correctly, use a key derivation function!
    if not isinstance(secret, bytes):
        secret = secret.encode()

    hash_bytes = sha3.keccak_256(secret).digest()
    sk = Ed25519SigningKeyFromHash.generate(hash_bytes=hash_bytes)
    # Private key
    private_value_base58 = sk.encode(encoding='base58')

    # Public key
    public_value_compressed_base58 = sk.get_verifying_key().encode(encoding='base58')

    return private_value_base58, public_value_compressed_base58
669745
def ecdh(self, identity, pubkey):
        """"""
        assert pubkey[:1] == b'\x04'
        peer = ecdsa.VerifyingKey.from_string(
            pubkey[1:],
            curve=ecdsa.curves.NIST256p,
            hashfunc=hashlib.sha256)
        shared = ecdsa.VerifyingKey.from_public_point(
            point=(peer.pubkey.point * self.secexp),
            curve=ecdsa.curves.NIST256p,
            hashfunc=hashlib.sha256)
        return shared.to_string()
710131
def customPRF512(key, amac, smac, anonce, snonce):
    """"""
    A = b"Pairwise key expansion"
    B = b"".join(sorted([amac, smac]) + sorted([anonce, snonce]))

    blen = 64
    i = 0
    R = b''
    while i <= ((blen * 8 + 159) / 160):
        hmacsha1 = hmac.new(key, A + chb(0x00) + B + chb(i), hashlib.sha1)
        i += 1
        R = R + hmacsha1.digest()
    return R[:blen]
130324
def key_pair_paths(key_name):
    """"""
    public_key_path = os.path.expanduser("~/.ssh/{}.pub".format(key_name))
    private_key_path = os.path.expanduser("~/.ssh/{}.pem".format(key_name))
    return public_key_path, private_key_path
630461
def public_pairs_for_script(self, tx, tx_in_idx, generator):
        
        public_pairs = []
        for sec in self.extract_secs(tx, tx_in_idx):
            try:
                public_pairs.append(sec_to_public_pair(sec, generator))
            except EncodingError:
                pass
        return public_pairs
176284
static byte []
fromPublicKey(PublicKey key, int alg) throws DNSSECException
{
	byte [] data = null;

	switch (alg) {
	case Algorithm.RSAMD5:
	case Algorithm.RSASHA1:
	case Algorithm.RSA_NSEC3_SHA1:
	case Algorithm.RSASHA256:
	case Algorithm.RSASHA512:
		if (! (key instanceof RSAPublicKey))
			throw new IncompatibleKeyException();
		return fromRSAPublicKey((RSAPublicKey) key);
	case Algorithm.DSA:
	case Algorithm.DSA_NSEC3_SHA1:
		if (! (key instanceof DSAPublicKey))
			throw new IncompatibleKeyException();
		return fromDSAPublicKey((DSAPublicKey) key);
	default:
		throw new UnsupportedAlgorithmException(alg);
	}
}
15610
public SshKeyPair toKeyPair(String passphrase) throws IOException,
			InvalidPassphraseException {

		ByteArrayReader bar = new ByteArrayReader(decryptKey(passphrase));

		try {
			// Process the actual key and return the key pair

			String algorithm = bar.readString();

			if (algorithm.equals("ssh-dss")) {
				BigInteger p = bar.readBigInteger();
				BigInteger q = bar.readBigInteger();
				BigInteger g = bar.readBigInteger();
				BigInteger x = bar.readBigInteger();

				SshDsaPrivateKey prv = ComponentManager.getInstance()
						.createDsaPrivateKey(p, q, g, x, g.modPow(x, p));
				SshKeyPair pair = new SshKeyPair();

				pair.setPublicKey(prv.getPublicKey());
				pair.setPrivateKey(ComponentManager.getInstance()
						.createDsaPrivateKey(p, q, g, x, g.modPow(x, p)));

				return pair;

			} else if (algorithm.equals("ssh-rsa")) {

				BigInteger publicExponent = bar.readBigInteger();
				BigInteger modulus = bar.readBigInteger();

				// Read the private key
				BigInteger privateExponent = bar.readBigInteger();

				SshKeyPair pair = new SshKeyPair();
				pair.setPublicKey(ComponentManager.getInstance()
						.createRsaPublicKey(modulus, publicExponent));
				pair.setPrivateKey(ComponentManager.getInstance()
						.createRsaPrivateKey(modulus, privateExponent));

				return pair;

			} else {
				throw new IOException("Unsupported private key algorithm type "
						+ algorithm);
			}
		} catch (SshException e) {
			throw new SshIOException(e);
		} finally {
			try {
				bar.close();
			} catch (IOException e) {
			}
		}

	}
542841
def encrypt(pubkey, password):
    
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password)
300189
static byte []
fromPublicKey(PublicKey key, int alg) throws DNSSECException
{
	switch (alg) {
	case Algorithm.RSAMD5:
	case Algorithm.RSASHA1:
	case Algorithm.RSA_NSEC3_SHA1:
	case Algorithm.RSASHA256:
	case Algorithm.RSASHA512:
		if (! (key instanceof RSAPublicKey))
			throw new IncompatibleKeyException();
		return fromRSAPublicKey((RSAPublicKey) key);
	case Algorithm.DSA:
	case Algorithm.DSA_NSEC3_SHA1:
		if (! (key instanceof DSAPublicKey))
			throw new IncompatibleKeyException();
		return fromDSAPublicKey((DSAPublicKey) key);
	case Algorithm.ECC_GOST:
		if (! (key instanceof ECPublicKey))
			throw new IncompatibleKeyException();
		return fromECGOSTPublicKey((ECPublicKey) key, GOST);
	case Algorithm.ECDSAP256SHA256:
		if (! (key instanceof ECPublicKey))
			throw new IncompatibleKeyException();
		return fromECDSAPublicKey((ECPublicKey) key, ECDSA_P256);
	case Algorithm.ECDSAP384SHA384:
		if (! (key instanceof ECPublicKey))
			throw new IncompatibleKeyException();
		return fromECDSAPublicKey((ECPublicKey) key, ECDSA_P384);
	default:
		throw new UnsupportedAlgorithmException(alg);
	}
}
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
748893
def serialize(self, as_private=None):
        
        if as_private is None:
            as_private = self.secret_exponent() is not None
        if self.secret_exponent() is None and as_private:
            raise PublicPrivateMismatchError("public key has no private parts")

        ba = bytearray()
        ba.extend([self._depth])
        ba.extend(self._parent_fingerprint + struct.pack(">L", self._child_index) + self._chain_code)
        if as_private:
            ba += b'\0' + self._secret_exponent_bytes
        else:
            ba += self.sec(is_compressed=True)
        return bytes(ba)
662883
def public_pair_to_sec(public_pair, compressed=True):
    """"""
    x_str = to_bytes_32(public_pair[0])
    if compressed:
        return int2byte((2 + (public_pair[1] & 1))) + x_str
    y_str = to_bytes_32(public_pair[1])
    return b'\4' + x_str + y_str
629570
def to_sec

      KEYS.inject(0) { |s, (k, a)| v = @h[k]; next s unless v; s += v * a[:s] }
    end
11276
def export_public_key(device_type, args):
    """"""
    log.warning('NOTE: in order to re-generate the exact same GPG key later, '
                'run this command with "--time=%d" commandline flag (to set '
                'the timestamp of the GPG key manually).', args.time)
    c = client.Client(device=device_type())
    identity = client.create_identity(user_id=args.user_id,
                                      curve_name=args.ecdsa_curve)
    verifying_key = c.pubkey(identity=identity, ecdh=False)
    decryption_key = c.pubkey(identity=identity, ecdh=True)
    signer_func = functools.partial(c.sign, identity=identity)

    if args.subkey:  # add as subkey
        log.info('adding %s GPG subkey for "%s" to existing key',
                 args.ecdsa_curve, args.user_id)
        # subkey for signing
        signing_key = protocol.PublicKey(
            curve_name=args.ecdsa_curve, created=args.time,
            verifying_key=verifying_key, ecdh=False)
        # subkey for encryption
        encryption_key = protocol.PublicKey(
            curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
            created=args.time, verifying_key=decryption_key, ecdh=True)
        primary_bytes = keyring.export_public_key(args.user_id)
        result = encode.create_subkey(primary_bytes=primary_bytes,
                                      subkey=signing_key,
                                      signer_func=signer_func)
        result = encode.create_subkey(primary_bytes=result,
                                      subkey=encryption_key,
                                      signer_func=signer_func)
    else:  # add as primary
        log.info('creating new %s GPG primary key for "%s"',
                 args.ecdsa_curve, args.user_id)
        # primary key for signing
        primary = protocol.PublicKey(
            curve_name=args.ecdsa_curve, created=args.time,
            verifying_key=verifying_key, ecdh=False)
        # subkey for encryption
        subkey = protocol.PublicKey(
            curve_name=formats.get_ecdh_curve_name(args.ecdsa_curve),
            created=args.time, verifying_key=decryption_key, ecdh=True)

        result = encode.create_primary(user_id=args.user_id,
                                       pubkey=primary,
                                       signer_func=signer_func)
        result = encode.create_subkey(primary_bytes=result,
                                      subkey=subkey,
                                      signer_func=signer_func)

    return protocol.armor(result, 'PUBLIC KEY BLOCK')
510545
function _convertPublicKey($n, $e)
    {
        $signed = $this->publicKeyFormat != CRYPT_RSA_PUBLIC_FORMAT_XML;

        $modulus = $n->toBytes($signed);
        $publicExponent = $e->toBytes($signed);

        switch ($this->publicKeyFormat) {
            case CRYPT_RSA_PUBLIC_FORMAT_RAW:
                return array('e' => $e->copy(), 'n' => $n->copy());
            case CRYPT_RSA_PUBLIC_FORMAT_XML:
                return "<RSAKeyValue>\r\n" .
                       '  <Modulus>' . base64_encode($modulus) . "</Modulus>\r\n" .
                       '  <Exponent>' . base64_encode($publicExponent) . "</Exponent>\r\n" .
                       '</RSAKeyValue>';
                break;
            case CRYPT_RSA_PUBLIC_FORMAT_OPENSSH:
                // from <http://tools.ietf.org/html/rfc4253#page-15>:
                // string    "ssh-rsa"
                // mpint     e
                // mpint     n
                $RSAPublicKey = pack('Na*Na*Na*', strlen('ssh-rsa'), 'ssh-rsa', strlen($publicExponent), $publicExponent, strlen($modulus), $modulus);
                $RSAPublicKey = 'ssh-rsa ' . base64_encode($RSAPublicKey) . ' ' . $this->comment;

                return $RSAPublicKey;
            default: // eg. CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW or CRYPT_RSA_PUBLIC_FORMAT_PKCS1
                // from <http://tools.ietf.org/html/rfc3447#appendix-A.1.1>:
                // RSAPublicKey ::= SEQUENCE {
                //     modulus           INTEGER,  -- n
                //     publicExponent    INTEGER   -- e
                // }
                $components = array(
                    'modulus' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($modulus)), $modulus),
                    'publicExponent' => pack('Ca*a*', CRYPT_RSA_ASN1_INTEGER, $this->_encodeLength(strlen($publicExponent)), $publicExponent)
                );

                $RSAPublicKey = pack(
                    'Ca*a*a*',
                    CRYPT_RSA_ASN1_SEQUENCE,
                    $this->_encodeLength(strlen($components['modulus']) + strlen($components['publicExponent'])),
                    $components['modulus'],
                    $components['publicExponent']
                );

                if ($this->publicKeyFormat == CRYPT_RSA_PUBLIC_FORMAT_PKCS1_RAW) {
                    $RSAPublicKey = "-----BEGIN RSA PUBLIC KEY-----\r\n" .
                                    chunk_split(base64_encode($RSAPublicKey), 64) .
                                    '-----END RSA PUBLIC KEY-----';
                } else {
                    // sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
                    $rsaOID = pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
                    $RSAPublicKey = chr(0) . $RSAPublicKey;
                    $RSAPublicKey = chr(3) . $this->_encodeLength(strlen($RSAPublicKey)) . $RSAPublicKey;

                    $RSAPublicKey = pack(
                        'Ca*a*',
                        CRYPT_RSA_ASN1_SEQUENCE,
                        $this->_encodeLength(strlen($rsaOID . $RSAPublicKey)),
                        $rsaOID . $RSAPublicKey
                    );

                    $RSAPublicKey = "-----BEGIN PUBLIC KEY-----\r\n" .
                                     chunk_split(base64_encode($RSAPublicKey), 64) .
                                     '-----END PUBLIC KEY-----';
                }

                return $RSAPublicKey;
        }
    }
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;
}