Read a public key off the disk.
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
438909
def FromPublicKey(cls, public_key):
    """"""
    # Our CN will be the first 64 bits of the hash of the public key
    # in MPI format - the length of the key in 4 bytes + the key
    # prefixed with a 0. This weird format is an artifact from the way
    # M2Crypto handled this, we have to live with it for now.
    n = public_key.GetN()
    raw_n = binascii.unhexlify("%x" % n)

    mpi_format = struct.pack(">i", len(raw_n) + 1) + b"\x00" + raw_n

    digest = binascii.hexlify(hashlib.sha256(mpi_format).digest()[:8])
    return cls("C.{}".format(digest.decode("ascii")))
41915
def _get_filekey(self):
        """"""

        if not os.path.exists(self.keyfile):
            raise KPError('Keyfile not exists.')
        try:
            with open(self.keyfile, 'rb') as handler:
                handler.seek(0, os.SEEK_END)
                size = handler.tell()
                handler.seek(0, os.SEEK_SET)

                if size == 32:
                    return handler.read(32)
                elif size == 64:
                    try:
                        return binascii.unhexlify(handler.read(64))
                    except (TypeError, binascii.Error):
                        handler.seek(0, os.SEEK_SET)

                sha = SHA256.new()
                while True:
                    buf = handler.read(2048)
                    sha.update(buf)
                    if len(buf) < 2048:
                        break
                return sha.digest()
        except IOError as e:
            raise KPError('Could not read file: %s' % e)
114813
public byte[] getSecret (PrivateKey key)
    {
        if (_secret == null) {
            _secret = SecureUtil.decryptBytes(key, _encodedSecret, _salt);
        }
        return _secret;
    }
592850
def load_private_key(key_file, key_password=None):
    
    key_file = os.path.expanduser(key_file)
    key_file = os.path.abspath(key_file)

    if not key_password:
        with open(key_file, 'r') as key:
            return key.read()

    with open(key_file, 'rb') as key:
        key_bytes = key.read()
    return decrypt_key(key_bytes, key_password).decode(ENCODING)
623278
def get_pubkey(self):
        '''
        
        '''
        if '__master_opts__' in self.opts and \
                self.opts['__master_opts__'].get('ssh_use_home_key') and \
                os.path.isfile(os.path.expanduser('~/.ssh/id_rsa')):
            priv = os.path.expanduser('~/.ssh/id_rsa')
        else:
            priv = self.opts.get(
                    'ssh_priv',
                    os.path.join(
                        self.opts['pki_dir'],
                        'ssh',
                        'salt-ssh.rsa'
                        )
                    )
        pub = '{0}.pub'.format(priv)
        with salt.utils.files.fopen(pub, 'r') as fp_:
            return '{0} rsa root@master'.format(fp_.read().split()[1])
1145475
def parse_pubkey(blob):
    
    fp = fingerprint(blob)
    s = io.BytesIO(blob)
    key_type = util.read_frame(s)
    log.debug('key type: %s', key_type)
    assert key_type in SUPPORTED_KEY_TYPES, key_type

    result = {'blob': blob, 'type': key_type, 'fingerprint': fp}

    if key_type == SSH_NIST256_KEY_TYPE:
        curve_name = util.read_frame(s)
        log.debug('curve name: %s', curve_name)
        point = util.read_frame(s)
        assert s.read() == b''
        _type, point = point[:1], point[1:]
        assert _type == SSH_NIST256_DER_OCTET
        size = len(point) // 2
        assert len(point) == 2 * size
        coords = (util.bytes2num(point[:size]), util.bytes2num(point[size:]))

        curve = ecdsa.NIST256p
        point = ecdsa.ellipticcurve.Point(curve.curve, *coords)

        def ecdsa_verifier(sig, msg):
            assert len(sig) == 2 * size
            sig_decode = ecdsa.util.sigdecode_string
            vk = ecdsa.VerifyingKey.from_public_point(point, curve, hashfunc)
            vk.verify(signature=sig, data=msg, sigdecode=sig_decode)
            parts = [sig[:size], sig[size:]]
            return b''.join([util.frame(b'\x00' + p) for p in parts])

        result.update(point=coords, curve=CURVE_NIST256,
                      verifier=ecdsa_verifier)

    if key_type == SSH_ED25519_KEY_TYPE:
        pubkey = util.read_frame(s)
        assert s.read() == b''

        def ed25519_verify(sig, msg):
            assert len(sig) == 64
            vk = ed25519.VerifyingKey(pubkey)
            vk.verify(sig, msg)
            return sig

        result.update(curve=CURVE_ED25519, verifier=ed25519_verify)

    return result
1077500
private PrivateKey readEcPrivateKey(String fileName) throws InvalidKeySpecException, NoSuchAlgorithmException, IOException, NoSuchProviderException
    {
    	StringBuilder sb = new StringBuilder();
    	BufferedReader br = new BufferedReader(new FileReader(fileName));
    	try {
	    	char[] cbuf = new char[1024];
	    	for (int i=0; i <= 10*1024; i++) {
	    		if (!br.ready())
	    			break;
	    		int len = br.read(cbuf, i*1024, 1024);
	    		sb.append(cbuf, 0, len);
	    	}
	    	if (br.ready()) {
	    		throw new IndexOutOfBoundsException("JWK file larger than 10MB");
	    	}
	    	Type mapType = new TypeToken<Map<String, String>>(){}.getType();
	    	Map<String, String> son = new Gson().fromJson(sb.toString(), mapType);
	    	try {
				@SuppressWarnings({ "unchecked", "rawtypes" })
				EllipticCurveJsonWebKey jwk = new EllipticCurveJsonWebKey((Map<String, Object>)(Map)son);
				Base64Encoder enc = new Base64Encoder();
				ByteArrayOutputStream os = new ByteArrayOutputStream();
	        	enc.encode(jwk.getPrivateKey().getEncoded(), 0, jwk.getPrivateKey().getEncoded().length, os);
				return jwk.getPrivateKey();
			} catch (JoseException e1) {
				e1.printStackTrace();
			}
	        return null;
    	} finally {
    		br.close();
    	}
    }
1177430
def Get(self,key):
		""""""

		for public_ip in self.public_ips:
			if public_ip.id == key:  return(public_ip)
			elif key == public_ip.internal:  return(public_ip)
136314
def read(self, cnt=None):
        """"""
        if cnt > 8 * 1024:
            raise BadRarFile('Bad count to header decrypt - wrong password?')

        # consume old data
        if cnt <= len(self.buf):
            res = self.buf[:cnt]
            self.buf = self.buf[cnt:]
            return res
        res = self.buf
        self.buf = EMPTY
        cnt -= len(res)

        # decrypt new data
        blklen = 16
        while cnt > 0:
            enc = self.f.read(blklen)
            if len(enc) < blklen:
                break
            dec = self.ciph.decrypt(enc)
            if cnt >= len(dec):
                res += dec
                cnt -= len(dec)
            else:
                res += dec[:cnt]
                self.buf = dec[cnt:]
                cnt = 0

        return res
996541
def _read_dict(self, dictionary):
        """"""
        values = dictionary
        self._did = values['id']
        self._created = values.get('created', None)
        if 'publicKey' in values:
            self._public_keys = []
            for value in values['publicKey']:
                if isinstance(value, str):
                    value = json.loads(value)
                self._public_keys.append(DDO.create_public_key_from_json(value))
        if 'authentication' in values:
            self._authentications = []
            for value in values['authentication']:
                if isinstance(value, str):
                    value = json.loads(value)
                self._authentications.append(DDO.create_authentication_from_json(value))
        if 'service' in values:
            self._services = []
            for value in values['service']:
                if isinstance(value, str):
                    value = json.loads(value)
                service = Service.from_json(value)
                service.set_did(self._did)
                self._services.append(service)
        if 'proof' in values:
            self._proof = values['proof']
1080196
function loadKeyPair (pub, prv, use) {
  var pubPEM, prvPEM, pubJWK

  try {
    pubPEM = fs.readFileSync(pub).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the public key from ' + pub)
  }

  try {
    prvPEM = fs.readFileSync(prv).toString('ascii')
  } catch (e) {
    throw new Error('Unable to read the private key from ' + pub)
  }

  try {
    pubJWK = pemjwk.pem2jwk(pubPEM)
  } catch (e) {
    throw new Error('Unable to convert the public key ' + pub + ' to a JWK')
  }

  return {
    pem: {
      pub: pubPEM,
      prv: prvPEM
    },
    jwk: {
      pub: {
        kty: pubJWK.kty,
        use: use,
        alg: 'RS256',
        n: pubJWK.n,
        e: pubJWK.e
      }
    }
  }
}
690124
function readKeys(onDone){
	console.log('-----------------------');
	fs.readFile(KEYS_FILENAME, 'utf8', function(err, data){
		var rl = readline.createInterface({
			input: process.stdin,
			output: process.stdout,
			//terminal: true
		});
		if (err){ // first start
			console.log('failed to read keys, will gen');
			var suggestedDeviceName = require('os').hostname() || 'Headless';
			// rl.question("Please name this device ["+suggestedDeviceName+"]: ", function(deviceName){
			var deviceName = suggestedDeviceName;
			var userConfFile = appDataDir + '/conf.json';
			fs.writeFile(userConfFile, JSON.stringify({deviceName: deviceName, admin_email: "admin@example.com", from_email: "noreply@example.com"}, null, '\t'), 'utf8', function(err){
				if (err)
					throw Error('failed to write conf.json: '+err);
				// rl.question(
				console.log('Device name saved to '+userConfFile+', you can edit it later if you like.\n\nPassphrase for your private keys: ')
					// function(passphrase){
				// rl.close();
				var passphrase = ""
				if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1);
				if (process.stdout.clearLine)  process.stdout.clearLine();
				var deviceTempPrivKey = crypto.randomBytes(32);
				var devicePrevTempPrivKey = crypto.randomBytes(32);

				var mnemonic = new Mnemonic(); // generates new mnemonic
				while (!Mnemonic.isValid(mnemonic.toString()))
					mnemonic = new Mnemonic();

				writeKeys(mnemonic.phrase, deviceTempPrivKey, devicePrevTempPrivKey, function(){
					console.log('keys created');
					xPrivKey = mnemonic.toHDPrivateKey(passphrase);
					createWallet(xPrivKey, function(){
						onDone(mnemonic.phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey);
					});
				});
					// }
				// );
			});
			// });
		}
		else{ // 2nd or later start
			// rl.question("Passphrase: ", function(passphrase){
			var passphrase = "";
			// rl.close();
			if (process.stdout.moveCursor) process.stdout.moveCursor(0, -1);
			if (process.stdout.clearLine)  process.stdout.clearLine();
			var keys = JSON.parse(data);
			var deviceTempPrivKey = Buffer(keys.temp_priv_key, 'base64');
			var devicePrevTempPrivKey = Buffer(keys.prev_temp_priv_key, 'base64');
			determineIfWalletExists(function(bWalletExists){
				if(!Mnemonic.isValid(keys.mnemonic_phrase)) throw Error('Invalid mnemonic_phrase in ' + KEYS_FILENAME)
				var mnemonic = new Mnemonic(keys.mnemonic_phrase);
				xPrivKey = mnemonic.toHDPrivateKey(passphrase);
				if (bWalletExists)
					onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey);
				else{
					createWallet(xPrivKey, function(){
						onDone(keys.mnemonic_phrase, passphrase, deviceTempPrivKey, devicePrevTempPrivKey);
					});
				}
			});
			// });
		}
	});
}
211413
def get_privatekey(keydata):
    """"""
    key = serialization.load_pem_private_key(
        keydata,
        password=None,
        backend=default_backend(),
    )
    return key
548467
def key_from_keybase(username, fingerprint=None):
    """"""
    url = keybase_lookup_url(username)
    resp = requests.get(url)
    if resp.status_code == 200:
        j_resp = json.loads(polite_string(resp.content))
        if 'them' in j_resp and len(j_resp['them']) == 1:
            kb_obj = j_resp['them'][0]
            if fingerprint:
                return fingerprint_from_keybase(fingerprint, kb_obj)
            else:
                if 'public_keys' in kb_obj \
                   and 'pgp_public_keys' in kb_obj['public_keys']:
                    key = kb_obj['public_keys']['primary']
                    return massage_key(key)

    return None
1320618
def privatekey_to_publickey(private_key_bin: bytes) -> bytes:
    
    if not ishash(private_key_bin):
        raise ValueError('private_key_bin format mismatch. maybe hex encoded?')
    return keys.PrivateKey(private_key_bin).public_key.to_bytes()
212074
def decrypt_file(path, password=None):
    '''
    
    '''
    global PASSWORD_FILE
    if not password:
        password = PASSWORD_FILE
    if path and not os.path.isfile(path):
        raise SystemExit(_error_codes.get(106))
    query = 'openssl aes-128-cbc -d -salt -in {0} -out {1} -k {2}'
    with hide('output'):
        local(query.format(path, path + '.tar.gz', PASSWORD_FILE))