Load public key from the serialized blob.

    Raise ValueError on parsing error.
12183
def decompress_pubkey(pubkey, curve_name):
    
    vk = None
    if len(pubkey) == 33:
        decompress = {
            CURVE_NIST256: _decompress_nist256,
            CURVE_ED25519: _decompress_ed25519,
            ECDH_CURVE25519: _decompress_ed25519,
        }[curve_name]
        vk = decompress(pubkey)

    if not vk:
        msg = 'invalid {!s} public key: {!r}'.format(curve_name, pubkey)
        raise ValueError(msg)

    return vk
1030551
def get_public_key(self):
        
        res = self.get_public_key_info()
        if 'error' in res:
            raise ValueError(res['error'])

        if res['type'] != 'singlesig':
            raise ValueError(res['error'])

        return res['public_keys'][0]
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;
    }
949778
def load(self, record_key, secret_key=''):
        
        '''
            
        '''
        
        title = '%s.load' % self.__class__.__name__
    
    # validate inputs
        input_fields = {
            'record_key': record_key,
            'secret_key': secret_key
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)
    
    # retrieve record data from s3
        record_data, record_metadata = self.s3.read_record(self.bucket_name, record_key)
    
    # validate secret key
        error_msg = '%s(secret_key="...") required to decrypt record "%s"' % (title, record_key)
        if 'encryption' in record_metadata['metadata'].keys():
            if record_metadata['metadata']['encryption'] == 'lab512':
                if not secret_key:
                    raise Exception(error_msg)
            else:
                self.s3.iam.printer('[WARNING]: %s uses unrecognized encryption method. Decryption skipped.' % record_key)
                secret_key = ''
                
    # decrypt (if necessary)
        if secret_key:
            from labpack.encryption import cryptolab
            record_data = cryptolab.decrypt(record_data, secret_key)
    
        return record_data
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);
	}
}
1001227
def load(self, record_key, secret_key=''):

        ''' 
            
        '''

        title = '%s.load' % self.__class__.__name__
    
    # validate inputs
        input_fields = {
            'record_key': record_key,
            'secret_key': secret_key
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)

    # construct file path
        file_path = '/%s' % record_key
    
    # request file data
        try:
            metadata, response = self.dropbox.files_download(file_path)
        except Exception as err:
            if str(err).find("LookupError('not_found'") > -1:
                raise Exception('%s(record_key=%s) does not exist.' % (title, record_key))
            else:
                raise DropboxConnectionError(title)
        record_data = response.content
    
    # decrypt (if necessary)
        if secret_key:
            from labpack.encryption import cryptolab
            record_data = cryptolab.decrypt(record_data, secret_key)
    
        return record_data
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'))
513457
def _load(self, key):
        '''
        
        '''
        # if the key doesn't have a '.' then it isn't valid for this mod dict
        if not isinstance(key, six.string_types):
            raise KeyError('The key must be a string.')
        if '.' not in key:
            raise KeyError('The key \'{0}\' should contain a \'.\''.format(key))
        mod_name, _ = key.split('.', 1)
        with self._lock:
            # It is possible that the key is in the dictionary after
            # acquiring the lock due to another thread loading it.
            if mod_name in self.missing_modules or key in self._dict:
                return True
            # if the modulename isn't in the whitelist, don't bother
            if self.whitelist and mod_name not in self.whitelist:
                log.error(
                    'Failed to load function %s because its module (%s) is '
                    'not in the whitelist: %s', key, mod_name, self.whitelist
                )
                raise KeyError(key)

            def _inner_load(mod_name):
                for name in self._iter_files(mod_name):
                    if name in self.loaded_files:
                        continue
                    # if we got what we wanted, we are done
                    if self._load_module(name) and key in self._dict:
                        return True
                return False

            # try to load the module
            ret = None
            reloaded = False
            # re-scan up to once, IOErrors or a failed load cause re-scans of the
            # filesystem
            while True:
                try:
                    ret = _inner_load(mod_name)
                    if not reloaded and ret is not True:
                        self._refresh_file_mapping()
                        reloaded = True
                        continue
                    break
                except IOError:
                    if not reloaded:
                        self._refresh_file_mapping()
                        reloaded = True
                    continue

        return ret
1168912
def serialize(self, private=False):
        
        if not self.priv_key and not self.pub_key:
            raise SerializationNotPossible()

        res = self.common()

        public_longs = list(set(self.public_members) & set(self.longs))
        for param in public_longs:
            item = getattr(self, param)
            if item:
                res[param] = item

        if private:
            for param in self.longs:
                if not private and param in ["d", "p", "q", "dp", "dq", "di",
                                             "qi"]:
                    continue
                item = getattr(self, param)
                if item:
                    res[param] = item
        if self.x5c:
            res['x5c'] = [x.decode('utf-8') for x in self.x5c]

        return res
1028167
def load(self, record_key, secret_key=''):

        ''' 
            
        '''

        title = '%s.load' % self.__class__.__name__
    
    # validate inputs
        input_fields = {
            'record_key': record_key,
            'secret_key': secret_key
        }
        for key, value in input_fields.items():
            if value:
                object_title = '%s(%s=%s)' % (title, key, str(value))
                self.fields.validate(value, '.%s' % key, object_title)

    # verify permissions
        if not self.permissions_content:
            raise Exception('%s requires an access_token with file content permissions.' % title)
            
    # retrieve file id
        file_id, parent_id = self._get_id(record_key)
        if not file_id:
            raise Exception('%s(record_key=%s) does not exist.' % (title, record_key))
    
    # request file data
        try:
            record_data = self.drive.get_media(fileId=file_id).execute()
        except:
            raise DriveConnectionError(title)
    
    # retrieve data from response
    #     import io
    #     from googleapiclient.http import MediaIoBaseDownload
    #     file_header = io.BytesIO
    #     record_data = MediaIoBaseDownload(file_header, response)
    #     done = False
    #     while not done:
    #         status, done = record_data.next_chunk()
    
    # TODO export google document to other format
            
    # decrypt (if necessary)
        if secret_key:
            from labpack.encryption import cryptolab
            record_data = cryptolab.decrypt(record_data, secret_key)
    
        return record_data
362230
def export_public_key(self):
		
		if self.__public_key is None:
			raise ValueError('Unable to call this method. Public key must be set')

		return self.__public_key.public_bytes(
			encoding=serialization.Encoding.PEM,
			format=serialization.PublicFormat.SubjectPublicKeyInfo
		)
415663
async def get_encryption_aes_key(self) -> Tuple[bytes, Dict[str, str], str]:
        
        if self.public_key is None:
            raise ValueError('Public key not provided during initialisation, cannot encrypt key encrypting key')

        random_bytes = os.urandom(32)

        ciphertext = await self._loop.run_in_executor(
            None, lambda: (self.public_key.encrypt(random_bytes, padding.PKCS1v15())))

        return random_bytes, {}, base64.b64encode(ciphertext).decode()
304196
def from_pubkey(cls: Type[CRCPubkeyType], pubkey: str) -> CRCPubkeyType:
        
        hash_root = hashlib.sha256()
        hash_root.update(base58.b58decode(pubkey))
        hash_squared = hashlib.sha256()
        hash_squared.update(hash_root.digest())
        b58_checksum = ensure_str(base58.b58encode(hash_squared.digest()))

        crc = b58_checksum[:3]
        return cls(pubkey, crc)
489677
def from_json(cls, json):
    
    return cls(json[cls.BLOB_KEY_PARAM],
               json[cls.START_INDEX_PARAM],
               json[cls.END_INDEX_PARAM])
624004
def decrypt(ciphertext_blob, encryption_context=None, grant_tokens=None,
            region=None, key=None, keyid=None, profile=None):
    '''
    
    '''
    conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile)

    r = {}
    try:
        plaintext = conn.decrypt(
            ciphertext_blob,
            encryption_context=encryption_context,
            grant_tokens=grant_tokens
        )
        r['plaintext'] = plaintext['Plaintext']
    except boto.exception.BotoServerError as e:
        r['error'] = __utils__['boto.get_error'](e)
    return r
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)
540710
def get_decode_value(self):
        """"""
        if self._store_type == PUBLIC_KEY_STORE_TYPE_HEX:
            value = bytes.fromhex(self._value)
        elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
            value = b64decode(self._value)
        elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE85:
            value = b85decode(self._value)
        elif self._store_type == PUBLIC_KEY_STORE_TYPE_JWK:
            # TODO: need to decide on which jwk library to import?
            raise NotImplementedError
        else:
            value = self._value
        return value