本文整理匯總了Python中Crypto.PublicKey.RSA.RsaKey方法的典型用法代碼示例。如果您正苦於以下問題:Python RSA.RsaKey方法的具體用法?Python RSA.RsaKey怎麽用?Python RSA.RsaKey使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類Crypto.PublicKey.RSA
的用法示例。
在下文中一共展示了RSA.RsaKey方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: build_send
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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
示例2: test_follow_post_receive__sends_correct_accept_back
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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,
}]
示例3: __init__
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
def __init__(self, certificateType: ServerCertificateType, publicKey: RsaKey, signature: bytes):
self.type = certificateType
self.publicKey = publicKey
self.signature = signature
示例4: __init__
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
def __init__(self, key: RsaKey):
self.key = key
示例5: setServerPublicKey
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
def setServerPublicKey(self, serverPublicKey: RsaKey):
"""
Set the server's public key.
:param serverPublicKey: the server's public key.
"""
self.serverPublicKey = serverPublicKey
示例6: parsePublicKey
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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
示例7: create_relayable_signature
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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")
示例8: get_http_authentication
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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,
)
示例9: build_send
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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
示例10: rsa_private_key
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
def rsa_private_key(self) -> RsaKey:
if isinstance(self.private_key, str):
return RSA.importKey(self.private_key)
return self.private_key
示例11: handle_create_payload
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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
示例12: __init__
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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_
示例13: validate_rsa2048_pkcs1_sig
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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)
示例14: validate_rsa2048_pss_sig
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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)
示例15: get_outbound_entity
# 需要導入模塊: from Crypto.PublicKey import RSA [as 別名]
# 或者: from Crypto.PublicKey.RSA import RsaKey [as 別名]
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