Python Crypto.PublicKey.RSA.RsaKey() Examples
The following are 16
code examples of Crypto.PublicKey.RSA.RsaKey().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
Crypto.PublicKey.RSA
, or try the search function
.
Example #1
Source File: protocol.py From federation with BSD 3-Clause "New" or "Revised" License | 6 votes |
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. :returns: dict or string depending on if private or public payload. """ if entity.outbound_doc is not None: # Use pregenerated outbound document xml = entity.outbound_doc else: xml = entity.to_xml() me = MagicEnvelope(etree.tostring(xml), private_key=from_user.rsa_private_key, author_handle=from_user.handle) rendered = me.render() if to_user_key: return EncryptedPayload.encrypt(rendered, to_user_key) return rendered
Example #2
Source File: test_entities.py From federation with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_follow_post_receive__sends_correct_accept_back( self, mock_send, mock_retrieve, activitypubfollow, profile ): mock_retrieve.return_value = profile activitypubfollow.post_receive() args, kwargs = mock_send.call_args_list[0] assert isinstance(args[0], ActivitypubAccept) assert args[0].activity_id.startswith("https://example.com/profile#accept-") assert args[0].actor_id == "https://example.com/profile" assert args[0].target_id == "https://localhost/follow" assert isinstance(args[1], UserType) assert args[1].id == "https://example.com/profile" assert isinstance(args[1].private_key, RsaKey) assert kwargs['recipients'] == [{ "endpoint": "https://example.com/bob/private", "fid": "https://localhost/profile", "protocol": "activitypub", "public": False, }]
Example #3
Source File: connection.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def __init__(self, certificateType: ServerCertificateType, publicKey: RsaKey, signature: bytes): self.type = certificateType self.publicKey = publicKey self.signature = signature
Example #4
Source File: connection.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def __init__(self, signatureAlgorithmID: int, keyAlgorithmID: int, publicKeyType: int, publicKey: RsaKey, signatureType: int, signature: bytes, padding: bytes): ServerCertificate.__init__(self, ServerCertificateType.PROPRIETARY, publicKey, signature) self.signatureAlgorithmID = signatureAlgorithmID self.keyAlgorithmID = keyAlgorithmID self.publicKeyType = publicKeyType self.signatureType = signatureType self.padding = padding
Example #5
Source File: crypto.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def __init__(self, key: RsaKey): self.key = key
Example #6
Source File: settings.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def setServerPublicKey(self, serverPublicKey: RsaKey): """ Set the server's public key. :param serverPublicKey: the server's public key. """ self.serverPublicKey = serverPublicKey
Example #7
Source File: connection.py From pyrdp with GNU General Public License v3.0 | 5 votes |
def parsePublicKey(self, data: bytes) -> RSA.RsaKey: stream = BytesIO(data) _magic = stream.read(4) keyLength = Uint32LE.unpack(stream) _bitLength = Uint32LE.unpack(stream) _dataLength = Uint32LE.unpack(stream) publicExponent = Uint32LE.unpack(stream) modulus = stream.read(keyLength - 8) _padding = stream.read(8) # Modulus must be reversed because bytes_to_long expects it to be in big endian format modulus = bytes_to_long(modulus[:: -1]) publicExponent = int(publicExponent) publicKey = RSA.construct((modulus, publicExponent)) return publicKey
Example #8
Source File: signatures.py From federation with BSD 3-Clause "New" or "Revised" License | 5 votes |
def create_relayable_signature(private_key: RsaKey, doc): sig_hash = _create_signature_hash(doc) cipher = PKCS1_v1_5.new(private_key) return b64encode(cipher.sign(sig_hash)).decode("ascii")
Example #9
Source File: signing.py From federation with BSD 3-Clause "New" or "Revised" License | 5 votes |
def get_http_authentication(private_key: RsaKey, private_key_id: str) -> HTTPSignatureHeaderAuth: """ Get HTTP signature authentication for a request. """ key = private_key.exportKey() return HTTPSignatureHeaderAuth( headers=["(request-target)", "user-agent", "host", "date"], algorithm="rsa-sha256", key=key, key_id=private_key_id, )
Example #10
Source File: protocol.py From federation with BSD 3-Clause "New" or "Revised" License | 5 votes |
def build_send(self, entity: BaseEntity, from_user: UserType, to_user_key: RsaKey = None) -> Union[str, Dict]: """ Build POST data for sending out to remotes. :param entity: The outbound ready entity for this protocol. :param from_user: The user sending this payload. Must have ``private_key`` and ``id`` properties. :param to_user_key: (Optional) Public key of user we're sending a private payload to. :returns: dict or string depending on if private or public payload. """ if hasattr(entity, "outbound_doc") and entity.outbound_doc is not None: # Use pregenerated outbound document rendered = entity.outbound_doc else: rendered = entity.to_as2() return rendered
Example #11
Source File: types.py From federation with BSD 3-Clause "New" or "Revised" License | 5 votes |
def rsa_private_key(self) -> RsaKey: if isinstance(self.private_key, str): return RSA.importKey(self.private_key) return self.private_key
Example #12
Source File: outbound.py From federation with BSD 3-Clause "New" or "Revised" License | 5 votes |
def handle_create_payload( entity: BaseEntity, author_user: UserType, protocol_name: str, to_user_key: RsaKey = None, parent_user: UserType = None, payload_logger: callable = None, ) -> Union[str, dict]: """Create a payload with the given protocol. Any given user arguments must have ``private_key`` and ``handle`` attributes. :arg entity: Entity object to send. Can be a base entity or a protocol specific one. :arg author_user: User authoring the object. :arg protocol_name: Protocol to create payload for. :arg to_user_key: Public key of user private payload is being sent to, required for private payloads. :arg parent_user: (Optional) User object of the parent object, if there is one. This must be given for the Diaspora protocol if a parent object exists, so that a proper ``parent_author_signature`` can be generated. If given, the payload will be sent as this user. :arg payload_logger: (Optional) Function to log the payloads with. :returns: Built payload (str or dict) """ mappers = importlib.import_module(f"federation.entities.{protocol_name}.mappers") protocol = importlib.import_module(f"federation.protocols.{protocol_name}.protocol") protocol = protocol.Protocol() outbound_entity = mappers.get_outbound_entity(entity, author_user.rsa_private_key) if parent_user: outbound_entity.sign_with_parent(parent_user.rsa_private_key) send_as_user = parent_user if parent_user else author_user data = protocol.build_send(entity=outbound_entity, from_user=send_as_user, to_user_key=to_user_key) if payload_logger: try: payload_logger(data, protocol_name, author_user.id) except Exception as ex: logger.warning("handle_create_payload | Failed to log payload: %s" % ex) return data
Example #13
Source File: key.py From little-boxes with ISC License | 5 votes |
def __init__(self, owner: str, id_: Optional[str] = None) -> None: self.owner = owner self.privkey_pem: Optional[str] = None self.pubkey_pem: Optional[str] = None self.privkey: Optional[RSA.RsaKey] = None self.pubkey: Optional[RSA.RsaKey] = None self.id_ = id_
Example #14
Source File: CryptoUtils.py From NSC_BUILDER with MIT License | 5 votes |
def validate_rsa2048_pkcs1_sig(n, e, msg, sig): cipher = PKCS1_v1_5.new(RSA.RsaKey(n=n, e=e)) digest = SHA256.new(msg) # DRM'd to use their impl return cipher.verify(digest, sig)
Example #15
Source File: CryptoUtils.py From NSC_BUILDER with MIT License | 5 votes |
def validate_rsa2048_pss_sig(n, e, msg, sig): cipher = PKCS1_PSS.new(RSA.RsaKey(n=n, e=e)) digest = SHA256.new(msg) return cipher.verify(digest, sig)
Example #16
Source File: mappers.py From federation with BSD 3-Clause "New" or "Revised" License | 4 votes |
def get_outbound_entity(entity: BaseEntity, private_key: RsaKey): """Get the correct outbound entity for this protocol. We might have to look at entity values to decide the correct outbound entity. If we cannot find one, we should raise as conversion cannot be guaranteed to the given protocol. Private key of author is needed to be passed for signing the outbound entity. :arg entity: An entity instance which can be of a base or protocol entity class. :arg private_key: Private key of sender as an RSA object :returns: Protocol specific entity class instance. :raises ValueError: If conversion cannot be done. """ if getattr(entity, "outbound_doc", None): # If the entity already has an outbound doc, just return the entity as is return entity outbound = None cls = entity.__class__ if cls in [DiasporaPost, DiasporaImage, DiasporaComment, DiasporaLike, DiasporaProfile, DiasporaRetraction, DiasporaContact, DiasporaReshare]: # Already fine outbound = entity elif cls == Post: outbound = DiasporaPost.from_base(entity) elif cls == Comment: outbound = DiasporaComment.from_base(entity) elif cls == Reaction: if entity.reaction == "like": outbound = DiasporaLike.from_base(entity) elif cls == Follow: outbound = DiasporaContact.from_base(entity) elif cls == Profile: outbound = DiasporaProfile.from_base(entity) elif cls == Retraction: outbound = DiasporaRetraction.from_base(entity) elif cls == Share: outbound = DiasporaReshare.from_base(entity) if not outbound: raise ValueError("Don't know how to convert this base entity to Diaspora protocol entities.") if isinstance(outbound, DiasporaRelayableMixin) and not outbound.signature: # Sign by author if not signed yet. We don't want to overwrite any existing signature in the case # that this is being sent by the parent author outbound.sign(private_key) # If missing, also add same signature to `parent_author_signature`. This is required at the moment # in all situations but is apparently being removed. # TODO: remove this once Diaspora removes the extra signature outbound.parent_signature = outbound.signature # Validate the entity outbound.validate(direction="outbound") return outbound