예제 #1
0
    def from_string(cls, jwt_string):
        # type: (str) -> Jwt
        """
        Initializes a new instance of the Jwt class using its string representation.
        Args:
            jwt_string: String representation of signed jwt. It must be equal to:
                        base64UrlEncode(JWT Header) + "." + base64UrlEncode(JWT Body) "." + base64UrlEncode(Jwt Signature).
        Returns:
            Initialized instance of Jwt.
        Raises:
            ValueError: Wrong jwt format.
        """
        parts = jwt_string.split(".")
        if len(parts) is not 3:
            raise ValueError("Wrong JWT format.")

        try:
            jwt = cls.__new__(cls)
            jwt._header_content = JwtHeaderContent.from_json(
                Utils.json_loads(Utils.b64_decode(parts[0])))
            jwt._body_content = JwtBodyContent.from_json(
                Utils.json_loads(Utils.b64_decode(parts[1])))
            jwt._signature_data = bytearray(Utils.b64_decode(parts[2]))
        except Exception as e:
            raise ValueError("Wrong JWT format.")

        jwt._body_content._app_id = jwt._body_content.issuer.replace(
            jwt._body_content.subject_prefix, "")
        jwt._body_content._identity = jwt._body_content.subject.replace(
            jwt._body_content.identity_prefix, "")
        jwt._unsigned_data = bytearray(parts[0] + "." + parts[1], "utf-8")
        jwt._string_representation = jwt_string
        return jwt
예제 #2
0
    def __init__(self):
        self.crypto = VirgilCrypto()
        self.api_key_base64 = "MC4CAQAwBQYDK2VwBCIEIF+gQkN4StqMMFJGWE1tKXcitkLqHqmrBz+OaQZKGZFR"
        self.app_id = "6af75f0dd9be50ebb77facad0f71eaf3"
        self.app_key_id = "3def16346c7b43bbaed5b4b9acb9ac8affa4"
        self.api_key = self.crypto.import_private_key(Utils.b64_decode(self.api_key_base64))
        self.ttl = datetime.timedelta(hours=1).seconds
        self.access_token_signer = AccessTokenSigner()
        self.key_pair = self.crypto.generate_keys()

        self.server_crypto = VirgilCrypto()
        self.server_key_pair = self.server_crypto.generate_keys()

        self.server_private_key_data = self.server_crypto.export_private_key(self.server_key_pair.private_key, "test password")
        self.server_public_key_data = self.server_crypto.export_public_key(self.server_key_pair.public_key)
        self.server_private_key_str = Utils.b64encode(self.server_private_key_data)
        self.server_for_client_public = Utils.b64encode(self.server_public_key_data)


        self.server_exporter = PrivateKeyExporter(self.server_crypto)
        self.server_private_key_storage = PrivateKeyStorage(self.server_exporter)
        self.server_public_key_str = self.server_key_pair.public_key
        self.server_card_crypto = CardCrypto()
        self.server_your_backend_white_list = WhiteList()
        self.server_your_backend_white_list = VerifierCredentials(signer="Jonathan",public_key_base64 = self.server_public_key_str)
        self.verifier = VirgilCardVerifier(self.server_card_crypto, white_lists = [self.server_your_backend_white_list])
        self.access_token_provider = CallbackJwtProvider(self.get_token_from_server("Alice"))
        self.card_manager = CardManager(
            self.server_card_crypto,
            self.access_token_provider,
            self.verifier
        )
예제 #3
0
    def __validate_signer_signature(self, card, signer_public_key,
                                    signer_type):
        signature = None
        for sign in card.signatures:
            if sign.signer == signer_type:
                signature = sign
                break

        if signature:
            if signature.snapshot:
                extended_snapshot = bytearray(Utils.b64_decode(card.content_snapshot))\
                                    + bytearray(Utils.b64_decode(signature.snapshot))
            else:
                extended_snapshot = bytearray(
                    Utils.b64_decode(card.content_snapshot))

            if self._crypto.verify_signature(
                    bytearray(Utils.b64_decode(signature.signature)),
                    extended_snapshot, signer_public_key):
                return True
        return False
예제 #4
0
    def from_signed_model(cls,
                          card_crypto,
                          raw_singed_model,
                          is_outdated=False):
        # type: (Any, RawSignedModel, bool) -> Card
        """
        Creates card from SignedModel snapshot and signatures.
        Args:
            card_crypto: Users CardCrypto witch provides cryptographic operations.
            raw_singed_model: Card RawSignedModel
            is_outdated: State of obsolescence

        Returns:
            Card created from RawSignedModel.
        """
        card = cls.from_snapshot(raw_singed_model.content_snapshot)
        card.previous_card = None
        card.is_outdated = is_outdated

        card._id = cls.__generate_card_id(
            card_crypto, Utils.b64_decode(raw_singed_model.content_snapshot))
        card._public_key = card_crypto.import_public_key(
            bytearray(Utils.b64_decode(card._public_key)))
        signatures = list()
        if raw_singed_model.signatures:
            for sign in raw_singed_model.signatures:
                if isinstance(sign, dict):
                    card_signature = CardSignature(**sign)
                    signatures.append(card_signature)
                if isinstance(sign, CardSignature):
                    card_signature = sign
                    signatures.append(card_signature)
                if isinstance(sign, RawSignature):
                    card_signature = CardSignature(sign.signer, sign.signature,
                                                   sign.snapshot)
                    signatures.append(card_signature)
        card.__signatures = signatures
        card._is_outdated = is_outdated
        return card
예제 #5
0
    def sign(self,
             model,
             signer,
             signer_private_key,
             signature_snapshot=None,
             extra_fields=None):
        # type: (RawSignedModel, str, PrivateKey, Union[bytearray, bytes], dict) -> None
        """
        Adds signature to the specified RawSignedModel using specified signer.
        Args:
            model: The instance of RawSignedModel to be signed.
            signer:
            signer_private_key: The instance of PrivateKey to sign with.
            signature_snapshot: Some additional raw bytes to be signed with model.
            extra_fields: Dictionary with additional data to be signed with model.
        """
        if model.signatures:
            if any(list(filter(lambda x: x.signer == signer,
                               model.signatures))):
                raise ValueError("The model already has this signature")

        if extra_fields and not signature_snapshot:
            signature_snapshot = bytearray(
                Utils.json_dumps(extra_fields).encode())

        if signature_snapshot:
            extended_snapshot = Utils.b64encode(
                bytearray(Utils.b64_decode(model.content_snapshot)) +
                bytearray(signature_snapshot))
        else:
            extended_snapshot = model.content_snapshot

        signature_bytes = self.__card_crypto.generate_signature(
            bytearray(Utils.b64_decode(extended_snapshot)), signer_private_key)

        signature = RawSignature(signer, bytearray(signature_bytes),
                                 signature_snapshot)
        model.add_signature(signature)
예제 #6
0
 def from_signed_model(cls, card_crypto, raw_singed_model):
     # type: (Any, RawSignedModel) -> RawCardContent
     """
     RawCardContent deserializer from RawSignedModel representation.
     Args:
         card_crypto: CardCrypto witch provides crypto operations.
         raw_singed_model: Card raw signed model.
     Returns:
         Loaded RawCardContent instance.
     """
     card = cls.from_snapshot(raw_singed_model.content_snapshot)
     card._public_key = card_crypto.import_public_key(
         bytearray(Utils.b64_decode(card._public_key)))
     return card
예제 #7
0
 def from_snapshot(cls, content_snapshot):
     # type: (dict) -> RawCardContent
     """
     RawCardContent deserializer from snapshot representation.
     Args:
         content_snapshot: RawCardContent serialized snapshot.
     Returns:
         Loaded RawCardContent instance.
     """
     card_content = cls.__new__(cls)
     loaded_snapshot = Utils.json_loads(Utils.b64_decode(content_snapshot))
     card_content._identity = loaded_snapshot["identity"]
     card_content._public_key = loaded_snapshot["public_key"]
     card_content._version = loaded_snapshot["version"]
     card_content._created_at = loaded_snapshot["created_at"]
     if "previous_card_id" in loaded_snapshot.keys():
         card_content._previous_card_id = loaded_snapshot[
             "previous_card_id"]
     else:
         card_content._previous_card_id = None
     card_content._content_snapshot = None
     return card_content
예제 #8
0
    def from_snapshot(cls, content_snapshot):
        # type: (str) -> Card
        """
        Creates card from content snapshot.
        Args:
            content_snapshot: Model content snapshot.

        Returns:
            Card created from model content snapshot.
        """
        card_content = cls.__new__(cls)
        loaded_snapshot = Utils.json_loads(Utils.b64_decode(content_snapshot))
        card_content._identity = loaded_snapshot["identity"]
        card_content._public_key = loaded_snapshot["public_key"]
        card_content._version = loaded_snapshot["version"]
        card_content._created_at = loaded_snapshot["created_at"]
        if "previous_card_id" in loaded_snapshot.keys():
            card_content._previous_card_id = loaded_snapshot[
                "previous_card_id"]
        else:
            card_content._previous_card_id = None
        card_content._content_snapshot = None
        return card_content
예제 #9
0
 def from_string(cls, raw_signed_model_string):
     # type: (str) -> RawSignedModel
     """Deserialize RawSignedModel from base64 encoded string."""
     return cls.from_json(
         Utils.b64_decode(raw_signed_model_string).decode())
예제 #10
0
 def __get_public_key(self, signer_public_key_base64):
     public_key_bytes = Utils.b64_decode(signer_public_key_base64)
     return self._crypto.import_public_key(bytearray(public_key_bytes))