Esempio n. 1
0
    def __init__(self, keyDer = None):
        # TODO: Implementation of managed properties?

        if keyDer == None:
            self._keyDer = Blob()
            self._keyType = None
            return

        self._keyDer = keyDer

        # Get the public key OID.
        oidString = ""
        try:
            parsedNode = DerNode.parse(keyDer.buf(), 0)
            rootChildren = parsedNode.getChildren()
            algorithmIdChildren = DerNode.getSequence(
              rootChildren, 0).getChildren()
            oidString = algorithmIdChildren[0].toVal()
        except DerDecodingException as ex:
          raise UnrecognizedKeyFormatException(
            "PublicKey.decodeKeyType: Error decoding the public key: " + str(ex))

        # Verify that the we can decode.
        if oidString == self.RSA_ENCRYPTION_OID:
            self._keyType = KeyType.RSA
            serialization.load_der_public_key(
              keyDer.toBytes(), backend = default_backend())
        elif oidString == self.EC_ENCRYPTION_OID:
            self._keyType = KeyType.ECDSA
            # TODO: Check EC decoding.
        else:
            raise UnrecognizedKeyFormatException(
              "PublicKey.decodeKeyType: Unrecognized OID " + oidString)
Esempio n. 2
0
    def encrypt(self, plainData, algorithmType):
        """
        Encrypt the plainData using the keyBits according the encrypt algorithm
        type.

        :param plainData: The data to encrypt.
        :type plainData: Blob or an object which is the same as the bytes() operator
        :param int algorithmType: The algorithm type from EncryptAlgorithmType.
          This encrypts according to the algorithm type, e.g., RsaOaep.
        :return: The encrypted data.
        :rtype: Blob
        """
        if isinstance(plainData, Blob):
            plainData = plainData.toBytes()

        publicKey = serialization.load_der_public_key(
          self._keyDer.toBytes(), backend = default_backend())

        if algorithmType == EncryptAlgorithmType.RsaOaep:
            if self._keyType != KeyType.RSA:
                raise RuntimeError("The key type must be RSA")

            paddingObject = padding.OAEP(
              mgf = padding.MGF1(algorithm = hashes.SHA1()),
              algorithm = hashes.SHA1(), label = None)
        elif algorithmType == EncryptAlgorithmType.RsaPkcs:
            if self._keyType != KeyType.RSA:
                raise RuntimeError("The key type must be RSA")

            paddingObject = padding.PKCS1v15()
        else:
            raise RuntimeError("unsupported encryption mode")

        result = publicKey.encrypt(plainData, paddingObject)
        return Blob(result, False)
Esempio n. 3
0
    def travis_encrypt(self, token_to_encrypt):
        """
        return encrypted version of token_to_encrypt 
        """
        
        # token_to_encrypt has to be string
        # if's not, assume it's unicode and enconde in utf-8
        
        if isinstance(token_to_encrypt, unicode):
            token_string = token_to_encrypt.encode('utf-8')
        else:
            token_string = token_to_encrypt
        
        repo_public_key_text = self.public_key_for_travis_repo()

        pubkey = repo_public_key_text.encode('utf-8')

        if 'BEGIN PUBLIC KEY' in pubkey:
            repo_public_key = serialization.load_pem_public_key(pubkey,
                backend=default_backend())
        elif 'BEGIN RSA PUBLIC KEY' in pubkey:
            # http://stackoverflow.com/a/32804289
            b64data = '\n'.join(pubkey.splitlines()[1:-1])
            derdata = base64.b64decode(b64data)
            repo_public_key = serialization.load_der_public_key(derdata,
                default_backend())
        else:
            raise Exception ('cannot parse repo public key')

        ciphertext = repo_public_key.encrypt(
         token_string,
         padding.PKCS1v15()
        )

        return base64.b64encode(ciphertext)
Esempio n. 4
0
def test_ecdh(backend, wycheproof):
    curve = _CURVES[wycheproof.testcase["curve"]]
    if curve is None:
        pytest.skip(
            "Unsupported curve ({})".format(wycheproof.testcase["curve"])
        )
    _skip_exchange_algorithm_unsupported(backend, ec.ECDH(), curve)

    private_key = ec.derive_private_key(
        int(wycheproof.testcase["private"], 16), curve, backend
    )

    try:
        public_key = serialization.load_der_public_key(
            binascii.unhexlify(wycheproof.testcase["public"]), backend
        )
    except NotImplementedError:
        assert wycheproof.has_flag("UnnamedCurve")
        return
    except ValueError:
        assert wycheproof.invalid or wycheproof.acceptable
        return
    except UnsupportedAlgorithm:
        return

    if wycheproof.valid or wycheproof.acceptable:
        computed_shared = private_key.exchange(ec.ECDH(), public_key)
        expected_shared = binascii.unhexlify(wycheproof.testcase["shared"])
        assert computed_shared == expected_shared
    else:
        with pytest.raises(ValueError):
            private_key.exchange(ec.ECDH(), public_key)
Esempio n. 5
0
    def encrypt(keyBits, plainData, params):
        """
        Encrypt the plainData using the keyBits according the encrypt params.

        :param Blob keyBits: The key value (DER-encoded public key).
        :param Blob plainData: The data to encrypt.
        :param EncryptParams params: This encrypts according to
          params.getAlgorithmType().
        :return: The encrypted data.
        :rtype: Blob
        """
        publicKey = serialization.load_der_public_key(
          keyBits.toBytes(), backend = default_backend())

        if params.getAlgorithmType() == EncryptAlgorithmType.RsaOaep:
            paddingObject = padding.OAEP(
              mgf = padding.MGF1(algorithm = hashes.SHA1()),
              algorithm = hashes.SHA1(), label = None)
        elif params.getAlgorithmType() == EncryptAlgorithmType.RsaPkcs:
            paddingObject = padding.PKCS1v15()
        else:
            raise RuntimeError("unsupported encryption mode")

        result = publicKey.encrypt(plainData.toBytes(), paddingObject)
        return Blob(result, False)
Esempio n. 6
0
def test_ecdsa_signature(backend, wycheproof):
    try:
        key = serialization.load_der_public_key(
            binascii.unhexlify(wycheproof.testgroup["keyDer"]), backend
        )
    except (UnsupportedAlgorithm, ValueError):
        # In OpenSSL 1.0.1, some keys fail to load with ValueError, instead of
        # Unsupported Algorithm. We can remove handling for that exception
        # when we drop support.
        pytest.skip(
            "unable to load key (curve {})".format(
                wycheproof.testgroup["key"]["curve"]
            )
        )
    digest = _DIGESTS[wycheproof.testgroup["sha"]]

    if (
        wycheproof.valid or
        (wycheproof.acceptable and not wycheproof.has_flag("MissingZero"))
    ):
        key.verify(
            binascii.unhexlify(wycheproof.testcase["sig"]),
            binascii.unhexlify(wycheproof.testcase["msg"]),
            ec.ECDSA(digest),
        )
    else:
        with pytest.raises(InvalidSignature):
            key.verify(
                binascii.unhexlify(wycheproof.testcase["sig"]),
                binascii.unhexlify(wycheproof.testcase["msg"]),
                ec.ECDSA(digest),
            )
Esempio n. 7
0
def getPublicKey(registry=None):
    ''' Return the user's public key (generating and saving a new key pair if necessary) '''
    registry = registry or Registry_Base_URL
    pubkey_pem = None
    if _isPublicRegistry(registry):
        pubkey_pem = settings.getProperty('keys', 'public')
    else:
        for s in _getSources():
            if _sourceMatches(s, registry):
                if 'keys' in s and s['keys'] and 'public' in s['keys']:
                    pubkey_pem = s['keys']['public']
                    break
    if not pubkey_pem:
        pubkey_pem, privatekey_pem = _generateAndSaveKeys()
    else:
        # settings are unicode, we should be able to safely decode to ascii for
        # the key though, as it will either be hex or PEM encoded:
        pubkey_pem = pubkey_pem.encode('ascii')
    # if the key doesn't look like PEM, it might be hex-encided-DER (which we
    # used historically), so try loading that:
    if b'-----BEGIN PUBLIC KEY-----' in pubkey_pem:
        pubkey = serialization.load_pem_public_key(pubkey_pem, default_backend())
    else:
        pubkey_der = binascii.unhexlify(pubkey_pem)
        pubkey = serialization.load_der_public_key(pubkey_der, default_backend())
    return _pubkeyWireFormat(pubkey)
Esempio n. 8
0
    def _verifySha256WithEcdsaSignature(signature, signedBlob, publicKeyDer):
        """
        Verify the ECDSA signature on the SignedBlob using the given public key.

        :param Blob signature: The signature bits.
        :param SignedBlob signedBlob: the SignedBlob with the signed portion to
          verify.
        :param Blob publicKeyDer: The DER-encoded public key used to verify the
          signature.
        :return: True if the signature verifies, False if not.
        :rtype: bool
        """
        # Get the public key.
        publicKeyDerBytes = publicKeyDer.toBytes()
        try:
            publicKey = load_der_public_key(
              publicKeyDerBytes, backend = default_backend())
        except:
            raise SecurityException("Cannot decode the ECDSA public key")

        # Verify.
        verifier = publicKey.verifier(
          signature.toBytes(), ec.ECDSA(hashes.SHA256()))
        verifier.update(signedBlob.toSignedBytes())
        try:
            verifier.verify()
            return True
        except InvalidSignature:
            return False
Esempio n. 9
0
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
    """ Optional: crypto backend object from the "cryptography" python library
    """
    if isinstance(verifying_key, EllipticCurvePublicKey):
        return verifying_key

    elif isinstance(verifying_key, (str, unicode)):
        if is_hex(verifying_key):
            try:
                public_key_pem = ECPublicKey(verifying_key).to_pem()
            except:
                pass
            else:
                try:
                    return load_pem_public_key(
                        public_key_pem, backend=crypto_backend)
                except Exception as e:
                    traceback.print_exc()
                    raise InvalidPublicKeyError()

            try:
                return load_der_public_key(
                    verifying_key, backend=crypto_backend)
            except:
                raise InvalidPublicKeyError()
        else:
            try:
                return load_pem_public_key(
                    verifying_key, backend=crypto_backend)
            except Exception as e:
                raise InvalidPublicKeyError()
    else:
        raise ValueError('Verifying key must be in string or unicode format.')
Esempio n. 10
0
def test_rsa_pss_signature(backend, wycheproof):
    key = serialization.load_der_public_key(
        binascii.unhexlify(wycheproof.testgroup["keyDer"]), backend
    )
    digest = _DIGESTS[wycheproof.testgroup["sha"]]
    mgf_digest = _DIGESTS[wycheproof.testgroup["mgfSha"]]

    if wycheproof.valid or wycheproof.acceptable:
        key.verify(
            binascii.unhexlify(wycheproof.testcase["sig"]),
            binascii.unhexlify(wycheproof.testcase["msg"]),
            padding.PSS(
                mgf=padding.MGF1(mgf_digest),
                salt_length=wycheproof.testgroup["sLen"]
            ),
            digest
        )
    else:
        with pytest.raises(InvalidSignature):
            key.verify(
                binascii.unhexlify(wycheproof.testcase["sig"]),
                binascii.unhexlify(wycheproof.testcase["msg"]),
                padding.PSS(
                    mgf=padding.MGF1(mgf_digest),
                    salt_length=wycheproof.testgroup["sLen"]
                ),
                digest
            )
Esempio n. 11
0
def load_pubkey(bs: bytes) -> rsa.RSAPublicKey:
    """
    Parse a DER-encoded RSA public key from a byte string.
    """
    key = serialization.load_der_public_key(bs, default_backend())
    if not isinstance(key, rsa.RSAPublicKey):
        raise Exception('Not an RSA public key')
    return key
Esempio n. 12
0
def read_public_key(key_fn):
    try:
        key_file = open(key_fn, "rb")
        pub_key = serialization.load_der_public_key(key_file.read(), backend=default_backend())
        # print("Pub key size: {}".format(pub_key.key_size))
        return pub_key
    except IOError as err_msg:
        print("Open key file failed. Please check the key file name. " + str(err_msg))
        raise IOError(err_msg)
Esempio n. 13
0
 def test_load_der_dsa_public_key(self, key_file, backend):
     key = load_vectors_from_file(
         key_file,
         lambda derfile: load_der_public_key(
             derfile.read(), backend
         ),
         mode="rb"
     )
     assert key
     assert isinstance(key, dsa.DSAPublicKey)
Esempio n. 14
0
 def handle_encrypt_request(self, name, packet):
     pubkey_raw = packet.data['public_key']
     if self.auth.online_mode:
         self.auth.send_session_auth(pubkey_raw, packet.data['server_id'])
     pubkey = serialization.load_der_public_key(pubkey_raw, backend)
     encrypt = lambda data: pubkey.encrypt(data, padding.PKCS1v15())  # flake8: noqa
     self.net.push_packet('LOGIN>Encryption Response', {
         'shared_secret': encrypt(self.auth.shared_secret),
         'verify_token': encrypt(packet.data['verify_token']),
     })
     self.net.enable_crypto(self.auth.shared_secret)
Esempio n. 15
0
 def verify_with_pub_key(pubkey, data, signature, hash_algo):
     '''Verify the given digest using ECDSA. r and s are the ECDSA signature parameters.
        if verified, return 1.
     '''
     pubkey = load_der_public_key(pubkey, backend=default_backend())
     verifier = pubkey.verifier(signature, ec.ECDSA(getattr(hashes, hash_algo)()))
     verifier.update(data)
     try:
         verifier.verify()
         return 1
     except Exception:
         return 0
Esempio n. 16
0
 def test_load_der_rsa_public_key(self, key_file, backend):
     key = load_vectors_from_file(
         key_file,
         lambda derfile: load_der_public_key(
             derfile.read(), backend
         ),
         mode="rb"
     )
     assert key
     assert isinstance(key, rsa.RSAPublicKey)
     numbers = key.public_numbers()
     assert numbers.e == 65537
Esempio n. 17
0
 def verify(self, app_param, chal_param, der_pubkey):
     pubkey = load_der_public_key(PUB_KEY_DER_PREFIX + der_pubkey,
                                  default_backend())
     verifier = pubkey.verifier(self.signature, ec.ECDSA(hashes.SHA256()))
     verifier.update(app_param +
                     six.int2byte(self.user_presence) +
                     struct.pack('>I', self.counter) +
                     chal_param)
     try:
         verifier.verify()
     except InvalidSignature:
         raise ValueError('U2F signature is invalid')
Esempio n. 18
0
    def test_encryption_using_generated_key(self):
        """Tests functionality of a generated asymmetric key pair."""
        test_model = order_models.OrderModel(**self.asymmetric_data)
        create_resp, order_ref = self.behaviors.create_order(test_model)
        self.assertEqual(create_resp.status_code, 202)

        order_resp = self.behaviors.get_order(order_ref)
        self.assertEqual(order_resp.status_code, 200)

        container_resp = self.container_behaviors.get_container(
            order_resp.model.container_ref)
        self.assertEqual(container_resp.status_code, 200)

        secret_dict = {}
        for secret in container_resp.model.secret_refs:
            self.assertIsNotNone(secret.secret_ref)
            secret_resp = self.secret_behaviors.get_secret(
                secret.secret_ref, "application/octet-stream")
            self.assertIsNotNone(secret_resp)
            secret_dict[secret.name] = secret_resp.content

        private_key = serialization.load_der_private_key(
            secret_dict['private_key'],
            password=None,
            backend=backends.default_backend()
        )
        public_key = serialization.load_der_public_key(
            secret_dict['public_key'],
            backend=backends.default_backend()
        )

        self.assertIsNotNone(private_key)
        self.assertIsNotNone(public_key)

        message = b'plaintext message'
        ciphertext = public_key.encrypt(
            message,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )
        plaintext = private_key.decrypt(
            ciphertext,
            padding.OAEP(
                mgf=padding.MGF1(algorithm=hashes.SHA1()),
                algorithm=hashes.SHA1(),
                label=None
            )
        )
        self.assertEqual(message, plaintext)
Esempio n. 19
0
    def from_public_der(cls, public_key):
        """
        Given a DER-format public key, convert it into a token to
        validate signatures
        :param public_key: der formatted key
        :return: :class:`~oneid.keychain.Keypair` instance
        """
        pub = load_der_public_key(public_key, default_backend())

        new_token = cls()
        new_token._public_key = pub

        return new_token
Esempio n. 20
0
    def load(byts):
        '''
        Create a PubKey instance from DER/PKCS8 encoded bytes.

        Args:
            byts (bytes): Bytes to load

        Returns:
            PubKey: A new PubKey instance.
        '''
        return PubKey(c_ser.load_der_public_key(
                byts,
                backend=default_backend()))
 def _load_verifying_key(self, verifying_key):
     if isinstance(verifying_key, EllipticCurvePublicKey):
         return verifying_key
     elif isinstance(verifying_key, (str, unicode)):
         try:
             return load_der_public_key(verifying_key, backend=backend)
         except:
             try:
                 return load_pem_public_key(verifying_key, backend=backend)
             except Exception as e:
                 traceback.print_exc()
                 raise ValueError("Invalid verifying key format")
     else:
         raise ValueError("Invalid verification key type")
Esempio n. 22
0
    def __call__(self, parser, namespace, values, option_string):

        if namespace.key_type == 'raw':
            setattr(namespace, self.dest, raw_loader(values))
        elif namespace.key_type == 'pem':
            setattr(namespace,
                    self.dest,
                    serialization.load_pem_public_key(raw_loader(values),
                                                      backend))
        elif namespace.key_type == 'der':
            setattr(namespace,
                    self.dest,
                    serialization.load_der_public_key(raw_loader(values),
                                                      backend))
Esempio n. 23
0
def encrypt_token_and_secret(pubkey, verification_token, shared_secret):
    """Encrypts the verification token and shared secret
    with the server's public key.

    :param pubkey: The RSA public key provided by the server
    :param verification_token: The verification token provided by the server
    :param shared_secret: The generated shared secret
    :return: A tuple containing (encrypted token, encrypted secret)
    """
    pubkey = load_der_public_key(pubkey, default_backend())

    encrypted_token = pubkey.encrypt(verification_token, PKCS1v15())
    encrypted_secret = pubkey.encrypt(shared_secret, PKCS1v15())
    return encrypted_token, encrypted_secret
Esempio n. 24
0
def rsa_encrypt(data, rsa_pub_key_bytes):
    """
    `rsa_pub_key_bytes` is a byte sequence with the public key
    """
    if isinstance(data, text_type):
        data = data.encode('utf-8')
    if isinstance(rsa_pub_key_bytes, text_type):
        rsa_pub_key_bytes = rsa_pub_key_bytes.encode('utf-8')
    if rsa_pub_key_bytes.startswith(b'-----'):
        key = serialization.load_pem_public_key(rsa_pub_key_bytes, backend=default_backend())
    elif rsa_pub_key_bytes.startswith(b'ssh-rsa '):
        key = serialization.load_ssh_public_key(rsa_pub_key_bytes, backend=default_backend())
    else:
        key = serialization.load_der_public_key(rsa_pub_key_bytes, backend=default_backend())
    return key.encrypt(data, OAEP(MGF1(SHA1()), SHA1(), label=None))
Esempio n. 25
0
 def test_load_ec_public_key(self, backend):
     _skip_curve_unsupported(backend, ec.SECP256R1())
     key = load_vectors_from_file(
         os.path.join(
             "asymmetric", "DER_Serialization",
             "ec_public_key.der"),
         lambda derfile: load_der_public_key(
             derfile.read(), backend
         ),
         mode="rb"
     )
     assert key
     assert isinstance(key, ec.EllipticCurvePublicKey)
     assert key.curve.name == "secp256r1"
     assert key.curve.key_size == 256
    def __init__(self, data: _STR_TYPE):
        """
        Creates a new ``PublicKey`` representing the given public bytes.

        Changing the produced object will NOT change the underlying
        bytes. The new object must first be exported.

        :param data: The public key byte-data.
        :raises ValueError: If the given key data bytes cannot be loaded,
         and thus may not represent a valid private key.
        """

        if isinstance(data, str):
            data = data.encode()

        if not isinstance(data, bytes):
            raise TypeError("Value of 'data' must be bytes")

        args = (data, default_backend())
        # (1)   Try loading public key as DER
        try:
            super().__init__(key=serialization.load_der_public_key(*args))
            self.encoding = EncodingType.DER
            return
        except ValueError:
            pass

        # (2)   Try loading public key as PEM
        try:
            super().__init__(key=serialization.load_pem_public_key(*args))
            self.encoding = EncodingType.PEM
            return
        except ValueError:
            pass

        # (3)   Try loading public key as OpenSSH
        try:
            super().__init__(key=serialization.load_ssh_public_key(*args))
            self.encoding = EncodingType.OpenSSH
            return
        except (ValueError, serialization.UnsupportedAlgorithm):
            pass

        raise ValueError("Could not find a suitable encoding for 'data' "
                         "bytes, the data may not be a valid public key")
Esempio n. 27
0
def load_verifying_key(verifying_key, crypto_backend=default_backend()):
    """ Optional: crypto backend object from the "cryptography" python library
    """
    if not isinstance(crypto_backend, (Backend, MultiBackend)):
        raise ValueError('backend must be a valid Backend object')

    if isinstance(verifying_key, EllipticCurvePublicKey):
        return verifying_key
    elif isinstance(verifying_key, (str, unicode)):
        try:
            return load_der_public_key(
                verifying_key, backend=crypto_backend)
        except:
            try:
                return load_pem_public_key(
                    verifying_key, backend=crypto_backend)
            except Exception as e:
                raise ValueError('Invalid verifying key format')
    else:
        raise ValueError('Invalid verification key type')
Esempio n. 28
0
    def handle_encryption_request(self, name, packet):
        pubkey_raw = packet.data['public_key']
        if self.authenticated:
            serverid = java_hex_digest(hashlib.sha1(
                packet.data['server_id'].encode('ascii') +
                self.auth.shared_secret +
                pubkey_raw
            ))
            logger.info(
                "AUTHPLUGIN: Attempting to authenticate session with "
                "sessionserver.mojang.com")
            url = "https://sessionserver.mojang.com/session/minecraft/join"
            data = json.dumps({
                'accessToken': self.auth.ygg.access_token,
                'selectedProfile': self.auth.selected_profile,
                'serverId': serverid,
            }).encode('utf-8')
            headers = {'Content-Type': 'application/json'}
            req = request.Request(url, data, headers)
            try:
                rep = request.urlopen(req).read().decode('ascii')
            except URLError:
                rep = 'Couldn\'t connect to sessionserver.mojang.com'
            if rep != "":
                logger.warning("AUTHPLUGIN: %s", rep)
                self.event.emit('SESS_ERR')
            else:
                logger.info("AUTHPLUGIN: Session authentication successful")
        pubkey = serialization.load_der_public_key(pubkey_raw, backend)

        def encrypt(data):
            return pubkey.encrypt(data, padding.PKCS1v15())

        self.net.push_packet(
            'LOGIN>Encryption Response',
            {
                'shared_secret': encrypt(self.auth.shared_secret),
                'verify_token': encrypt(packet.data['verify_token']),
            }
        )
        self.net.enable_crypto(self.auth.shared_secret)
Esempio n. 29
0
def test_rsa_signature(backend, wycheproof):
    key = serialization.load_der_public_key(
        binascii.unhexlify(wycheproof.testgroup["keyDer"]), backend
    )
    digest = _DIGESTS[wycheproof.testgroup["sha"]]

    if should_verify(backend, wycheproof):
        key.verify(
            binascii.unhexlify(wycheproof.testcase["sig"]),
            binascii.unhexlify(wycheproof.testcase["msg"]),
            padding.PKCS1v15(),
            digest,
        )
    else:
        with pytest.raises(InvalidSignature):
            key.verify(
                binascii.unhexlify(wycheproof.testcase["sig"]),
                binascii.unhexlify(wycheproof.testcase["msg"]),
                padding.PKCS1v15(),
                digest,
            )
Esempio n. 30
0
 def _parse_public_key(self, ipa_public_key):
     public_key = serialization.load_der_public_key(ipa_public_key,
                                                    default_backend())
     num = public_key.public_numbers()
     if isinstance(num, rsa.RSAPublicNumbers):
         return {'kty': 'RSA',
                 'e': self._encode_int(num.e),
                 'n': self._encode_int(num.n)}
     elif isinstance(num, ec.EllipticCurvePublicNumbers):
         if num.curve.name == 'secp256r1':
             curve = 'P-256'
         elif num.curve.name == 'secp384r1':
             curve = 'P-384'
         elif num.curve.name == 'secp521r1':
             curve = 'P-521'
         else:
             raise TypeError('Unsupported Elliptic Curve')
         return {'kty': 'EC',
                 'crv': curve,
                 'x': self._encode_int(num.x),
                 'y': self._encode_int(num.y)}
     else:
         raise TypeError('Unknown Public Key type')
Esempio n. 31
0
    def process(self, msg=b""):

        if (self.msg_cnt == 0):

            new_msg = bytes("Hello".encode('utf-8'))
            self.msg_cnt += 1

        elif (self.msg_cnt == 1):

            msg = msg.decode()
            msg_dict = ast.literal_eval(msg)

            pub_key = msg_dict['pubKey']

            server_public_key = load_der_public_key(pub_key,
                                                    backend=default_backend())

            self.client_private_key = ec.generate_private_key(
                ec.SECP256K1(), default_backend())
            self.client_public_key = self.client_private_key.public_key()
            self.shared_key = self.client_private_key.exchange(
                ec.ECDH(), server_public_key)

            key = os.urandom(32)
            nounce = os.urandom(12)

            cip = ChaCha20Poly1305(key)

            print('Input message to send (empty to finish)')
            data = input()
            message = data.encode('utf-8')

            ciphertext = cip.encrypt(nounce, message, None)

            signature = self.client_private_key.sign(ciphertext,
                                                     ec.ECDSA(hashes.SHA256()))

            new_msg = {
                "nounce":
                nounce,
                "key":
                key,
                "ct":
                ciphertext,
                "sign":
                signature,
                "pub_key":
                self.client_public_key.public_bytes(
                    Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
            }

            self.msg_cnt += 1
        else:
            key = os.urandom(32)
            nounce = os.urandom(12)

            cip = ChaCha20Poly1305(key)

            print('Input message to send (empty to finish)')
            data = input()
            message = data.encode('utf-8')

            ciphertext = cip.encrypt(nounce, message, None)

            signature = self.client_private_key.sign(ciphertext,
                                                     ec.ECDSA(hashes.SHA256()))

            new_msg = {
                "nounce": nounce,
                "key": key,
                "ct": ciphertext,
                "sign": signature
            }

            self.msg_cnt += 1

        print("Mensagem enviada!\n")

        return new_msg if len(new_msg) > 0 else None
Esempio n. 32
0
def load_public_key(der_public_key):
    return serialization.load_der_public_key(b64decode(der_public_key),
                                             default_backend())
Esempio n. 33
0
 def verify_with_pub_key(pubkey, data, signature, hash_algo):
     '''Verify the given digest using ECDSA.
        raise Exception if NOT verified.
     '''
     pubkey = load_der_public_key(pubkey, backend=default_backend())
     pubkey.verify(signature, data, ec.ECDSA(getattr(hashes, hash_algo)()))
Esempio n. 34
0
    def generate_shared_secret(self, private_key, ephemeral_public_key):
        ephemeral_public_key = base64.b64decode(ephemeral_public_key)
        ephemeral_public_key = load_der_public_key(ephemeral_public_key, self.backend)
        shared_secret = private_key.exchange(ec.ECDH(), ephemeral_public_key)

        return shared_secret
Esempio n. 35
0
def unpack_public_key(data):
    return serialization.load_der_public_key(data=data,
                                             backend=default_backend())
Esempio n. 36
0
    # Check for correct number of arguments
    if len(sys.argv) != 4:
        sys.exit(
            '\n---ERROR---\nInvalid number of arguments. Please use the following format:\n\n  python dsaverify.py <PUBLIC KEY FILEPATH> <INITIAL FILE FILEPATH> <SIGNATURE FILEPATH>\n\n'
        )

    # Parse command line arguments
    keyfile = sys.argv[1]
    messagefile = sys.argv[2]
    sigfile = sys.argv[3]

    # Read in binary data from keyfile
    with open(keyfile, "rb") as f:
        raw = f.read()
    # Parse keyfile data
    key = load_der_public_key(raw, backend=default_backend())
    key_parts = key.public_numbers()
    # Break out components of DSA Public Key
    beta = key_parts.y
    p = key_parts.parameter_numbers.p
    q = key_parts.parameter_numbers.q
    g = key_parts.parameter_numbers.g

    # Instantiate sha256 hash object
    M = hashlib.sha256()
    # Read in 1024 byte chunks from signed file
    with open(messagefile, "rb") as f:
        chunk = f.read(1024)
        # Update hash object state
        while chunk:
            M.update(chunk)
Esempio n. 37
0
slots = pkcs11.getSlotList()

for s in slots:
    if 'CARTAO DE CIDADAO' in pkcs11.getTokenInfo(s).label:
        data = bytes('data to be signed', 'utf-8')

        session = pkcs11.openSession(s)

        privKey = session.findObjects([(CKA_CLASS, CKO_PRIVATE_KEY),
                                       (CKA_LABEL,
                                        'CITIZEN AUTHENTICATION KEY')])[0]
        signature = bytes(
            session.sign(privKey, data, Mechanism(CKM_SHA1_RSA_PKCS)))

        pubKeyHandle = session.findObjects([(CKA_CLASS, CKO_PUBLIC_KEY),
                                            (CKA_LABEL,
                                             'CITIZEN AUTHENTICATION KEY')])[0]

        pubKeyDer = session.getAttributeValue(pubKeyHandle, [CKA_VALUE],
                                              TRUE)[0]

        session.closeSession()

        pubKey = load_der_public_key(bytes(pubKeyDer), default_backend())

        try:
            pubKey.verify(signature, data, padding.PKCS1v15(), hashes.SHA1())
            print('Verification succeeded')
        except:
            print('Verification failed')
Esempio n. 38
0
 def import_from_der(self, pubkey):
     # No lib support for explicit curves nor compressed points.
     self.pubkey = serialization.load_der_public_key(
         pubkey, backend=default_backend())
Esempio n. 39
0
from base64 import b64decode

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

public_key_string = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3CPXhKOGh6UXbcMD4tJceGVAeNZkdCvwn8ZhVol9+S5zkaEFXxu1nMQQqoHisKhdGowFMqwBbTU7a1yibSEeaiRpSAtLrf9ggedAZHq7UbohaRXaLaqF2xub4WogJMDjts+y+NbgyE31JbNlF0AXjuBc2cQzjeEI8PvbpfE3SGH68jZcKNl9xr0LgIEp0XExtTqBA/NUL1IFfTH7RWr/SZJfMwaB+YL4rDHG0RMQBg6mDwY0Z6NSkdyfxwwEmINJv6oeesAFeomhgsk0iUzbIrqtYwT3zskU+S6hCX65jp/JoxaNXfgn3r7C7wOsExqxq/Bm2nrldDfQ/E9U+mm6OQIDAQAB'

# The data between -----BEGIN RSA PUBLIC KEY----- and -----END RSA PUBLIC KEY----- is actually just base-64 encoded DER data.
der_data = b64decode(public_key_string)

# Return RSAPublicKey object from public key string
# Deserialize a public key from DER encoded data to one of the supported asymmetric public key types.
# https://cryptography.io/en/latest/hazmat/primitives/asymmetric/serialization/#cryptography.hazmat.primitives.serialization.load_der_public_key
public_key_obj = serialization.load_der_public_key(der_data,
                                                   backend=default_backend())

print(
    public_key_obj
)  # <cryptography.hazmat.backends.openssl.rsa._RSAPublicKey object at 0x000001D107C3A160>
print(type(public_key_obj)
      )  # <class 'cryptography.hazmat.backends.openssl.rsa._RSAPublicKey'>
Esempio n. 40
0
def Bytes_ToPublicKey(bytes):
    return serialization.load_der_public_key(bytes, default_backend())
Esempio n. 41
0
def _get_pubkey_from_der_public_key(filedata, backend):
    """ Load the filedata as a DER public key """
    try:
        return serialization.load_der_public_key(filedata, backend=backend)
    except Exception:
        return None
Esempio n. 42
0
def get_cryptography_public_key(public_key):
    crypto_public_key = serialization.load_der_public_key(
        bytes(public_key.get_encoded()), backend=backends.default_backend())
    return crypto_public_key
Esempio n. 43
0
 def encrypt(self, public_key, clear_text):
     public_key = serialization.load_der_public_key(
         self.key_pair.public_key, backend=default_backend())
     return public_key.encrypt(clear_text, self._padding)
Esempio n. 44
0
File: ecc.py Progetto: vinerr/fwlite
 def get_dh_key(self, otherKey):
     peer_public_key = load_der_public_key(otherKey, backend=default_backend())
     return self.ec_private.exchange(ec.ECDH(), peer_public_key)
Esempio n. 45
0
    def prepare(self):
        my_key_dir = os.path.join(base_dir, 'private')
        my_private_key_file_path = os.path.join(my_key_dir, 'my_pri_key')
        my_public_key_file_path = os.path.join(my_key_dir, 'my_pub_key')
        friend_keys_dir_path = os.path.join(base_dir, 'friends')
        if not os.path.exists(my_key_dir):
            os.makedirs(my_key_dir)
        if not os.path.exists(friend_keys_dir_path):
            os.makedirs(friend_keys_dir_path)
        if not os.path.exists(my_private_key_file_path) or not os.path.exists(
                my_public_key_file_path):
            print('private or public key does not exist!')
            choice = get_choice(hint='1. generate key pair\n2. exit\nchoice: ',
                                options=['1', '2'])
            if choice == '1':
                my_private_key = rsa.generate_private_key(
                    public_exponent=65537, key_size=2048, backend=self.backend)
                private_key_password = getpass.getpass(
                    'input a password for private_key, default is empty: ')
                if private_key_password:
                    my_private_key_bytes = my_private_key.private_bytes(
                        serialization.Encoding.DER,
                        format=serialization.PrivateFormat.PKCS8,
                        encryption_algorithm=serialization.
                        BestAvailableEncryption(
                            private_key_password.encode('utf8')))
                else:
                    my_private_key_bytes = my_private_key.private_bytes(
                        serialization.Encoding.DER,
                        format=serialization.PrivateFormat.PKCS8,
                        encryption_algorithm=serialization.NoEncryption())
                open(my_private_key_file_path,
                     'wb').write(my_private_key_bytes)

                my_public_key = my_private_key.public_key()
                my_public_key_bytes = my_public_key.public_bytes(
                    serialization.Encoding.DER,
                    serialization.PublicFormat.SubjectPublicKeyInfo)
                open(my_public_key_file_path, 'wb').write(my_public_key_bytes)
            if choice == '2':
                exit(0)

        choice = get_choice(
            hint=
            '1. generate secret_key for talk\n2. decrypt encrypted secret_key from your friend\nchoice: ',
            options=['1', '2'])
        if choice == '1':
            secret_key = os.urandom(32)

            friend_key_names = os.listdir(friend_keys_dir_path)
            if not friend_key_names:
                print('there is no one friend\'s public key, exit')
                exit(0)
            hint = 'friend_key_names:\n {}\ninput a key name you want: '.format(
                ' \n'.join(friend_key_names))
            selected_friend_key_name = get_choice(hint=hint,
                                                  options=friend_key_names)
            my_friend_public_key_file_path = os.path.join(
                friend_keys_dir_path, selected_friend_key_name)
            my_friend_public_key_content = open(my_friend_public_key_file_path,
                                                'rb').read()
            my_friend_public_key = serialization.load_der_public_key(
                my_friend_public_key_content, self.backend)
            encrypted_secret_key = my_friend_public_key.encrypt(
                secret_key,
                padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                             algorithm=hashes.SHA256(),
                             label=None))
            msg = 'encrypted_secret_key:{}'.format(
                binascii.hexlify(encrypted_secret_key).decode('utf8'))
            print(
                'Please send the following encrypted_secret_key msg to your friend'
            )
            print(msg)
        if choice == '2':
            my_private_key_content = open(my_private_key_file_path,
                                          'rb').read()
            private_key_password = getpass.getpass(
                'input the password of private_key, default is empty: ')
            if private_key_password:
                my_private_key = serialization.load_der_private_key(
                    my_private_key_content,
                    private_key_password.encode('utf8'), self.backend)
            else:
                my_private_key = serialization.load_der_private_key(
                    my_private_key_content, None, self.backend)
            while True:
                encrypted_secret_key_msg = input(
                    'Please input encrypted_secret_key msg from your friend: '
                ).strip()

                if encrypted_secret_key_msg.startswith(
                        'encrypted_secret_key:') and is_hex_str(
                            encrypted_secret_key_msg[21:]):
                    break
                else:
                    print(
                        '[!] encrypted_secret_key msg must start with "encrypted_secret_key:" and have correct hex_str'
                    )
                    continue

            encrypted_secret_key_bytes = bytes.fromhex(
                encrypted_secret_key_msg[21:])
            secret_key = my_private_key.decrypt(
                encrypted_secret_key_bytes,
                padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                             algorithm=hashes.SHA256(),
                             label=None))

        self.fernet = Fernet(base64.urlsafe_b64encode(secret_key))
Esempio n. 46
0
def decode_rsa_key(pem_key):
    decoded = base64.b64decode(''.join(pem_key.splitlines()[1:-1]))
    return serialization.load_der_public_key(decoded, default_backend())
Esempio n. 47
0
#     print "Usage - python client.py -sip server-ip -sp <PORT> -sk <SERVER_PUBLIC_KEY_PATH>"
#     sys.exit()

if not args.sk:
    print "Usage - python client.py -sip server-ip -sp <PORT> -sk <SERVER_PUBLIC_KEY_PATH>"
    sys.exit()

PORT = args.sp
HOST = args.sip
# CLIENT_PORT = args.cp

# Read the public key file for the Server and load it into a public key variable
public_key_file_path = args.sk
try:
    with open(public_key_file_path, 'rb') as f:
        s_public_key = serialization.load_der_public_key(
            f.read(), backend=default_backend())
except:
    print "Error while Reading the key File"
    sys.exit()


# INPUT : Asymmetric Key,Message in Byte Format
# OUTPUT : Cipher
# Method used for asymmetric encryption
def encrypt_with_asymmetric_key(key, message):
    try:
        cipher = key.encrypt(
            message,
            padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA1()),
                         algorithm=hashes.SHA1(),
                         label=None))
Esempio n. 48
0
 def load(cls, der_encoded_key: bytes):
     key = cls()
     key._pub_key = serialization.load_der_public_key(
         der_encoded_key, default_backend())
     return key
Esempio n. 49
0
    def process(self, msg):
        if (self.msg_cnt == 0):

            self.server_private_key = ec.generate_private_key(
                ec.SECP256K1(), default_backend())

            self.server_public_key = self.server_private_key.public_key()

            new_msg = {
                "pubKey":
                self.server_public_key.public_bytes(
                    Encoding.DER, PublicFormat.SubjectPublicKeyInfo)
            }

            msg = new_msg

            self.msg_cnt += 1

        elif (self.msg_cnt == 1):

            msg = msg.decode()

            msg_dict = ast.literal_eval(msg)

            nounce = msg_dict['nounce']
            key = msg_dict['key']
            ciphertext = msg_dict['ct']
            signature = msg_dict['sign']
            pub_key = msg_dict['pub_key']

            self.client_public_key = load_der_public_key(
                pub_key, backend=default_backend())

            self.shared_key = self.server_private_key.exchange(
                ec.ECDH(), self.client_public_key)

            cip = ChaCha20Poly1305(key)

            try:
                self.client_public_key.verify(signature, ciphertext,
                                              ec.ECDSA(hashes.SHA256()))
                message = cip.decrypt(nounce, ciphertext, None)
                print('%d : %r' % (self.id, message.decode('utf-8')))

            except:
                print("Error while decrypt")

            self.msg_cnt += 1
        else:

            msg = msg.decode()

            msg_dict = ast.literal_eval(msg)

            nounce = msg_dict['nounce']
            key = msg_dict['key']
            ciphertext = msg_dict['ct']
            signature = msg_dict['sign']

            cip = ChaCha20Poly1305(key)

            try:
                self.client_public_key.verify(signature, ciphertext,
                                              ec.ECDSA(hashes.SHA256()))
                message = cip.decrypt(nounce, ciphertext, None)
                print('%d : %r' % (self.id, message.decode('utf-8')))

            except:
                print("Error while decrypt")

            self.msg_cnt += 1

        print('NEXT!')
        return msg if len(msg) > 0 else None
Esempio n. 50
0
def get_public_key_from_der(data):
    return serialization.load_der_public_key(
        data, backend=backends.default_backend())
Esempio n. 51
0
 def checkAsymPubKey(self, rsa_key):
     public_key = serialization.load_der_public_key(
         rsa_key, backend=default_backend())
     pass
Esempio n. 52
0
def pub_key_der_to_addr(pub_key):
    pub_key_loaded = serialization.load_der_public_key(pub_key, backend=default_backend())
    return get_addr_from_public_key(pub_key_loaded)
Esempio n. 53
0
 def public_key(self):
     return serialization.load_der_public_key(bytes(self.pubkey),
                                              backend=default_backend())
Esempio n. 54
0
 def import_from_der(self, pubkey):
     # XXX does the cryptography lib support explicit curves?
     # check also for compressed points
     self.pubkey = serialization.load_der_public_key(pubkey,
                                                 backend=default_backend())
Esempio n. 55
0
 def save_pub_key(pubkey, path):
     '''save public key to path'''
     pubk = load_der_public_key(pubkey, backend=default_backend())
     data = pubk.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
     with open(path, 'wb') as write_to:
         write_to.write(data)
Esempio n. 56
0
def login(address, protocol_version, debug, access_token, uuid, user_name):
    connection = TCPConnection(address, debug)

    # Handshake with Next state set to 2 (login)
    packet_out = Packet()
    packet_out.write_varint(0x00)
    packet_out.write_varint(protocol_version)
    packet_out.write_utf(address[0])
    packet_out.write_ushort(address[1])
    packet_out.write_varint(2)
    connection.send_packet(packet_out)

    # Login start
    packet_out = Packet()
    packet_out.write_varint(0x00)
    packet_out.write_utf(user_name)
    connection.send_packet(packet_out)

    # Begin login phase loop.
    while True:
        receive_ready, send_ready, exception_ready = select.select(
            [connection.socket], [connection.socket], [], 0.01)
        if len(receive_ready) > 0:
            packet_in = connection.receive_packet()
            packet_id = packet_in.read_varint()
            if debug:
                print('L Packet ' + hex(packet_id))

            # Disconnect (login)
            if packet_id == 0x00:
                print(packet_in.read_utf())

            # Encryption request
            if packet_id == 0x01:
                server_id = packet_in.read_utf()
                pub_key = packet_in.read_bytearray_as_str()
                ver_tok = packet_in.read_bytearray_as_str()

                # Client auth
                shared_secret = os.urandom(16)
                verify_hash = sha1()
                verify_hash.update(server_id.encode('utf-8'))
                verify_hash.update(shared_secret)
                verify_hash.update(pub_key)
                server_id = format(
                    int.from_bytes(verify_hash.digest(),
                                   byteorder='big',
                                   signed=True), 'x')
                res = requests.post(
                    'https://sessionserver.mojang.com/session/minecraft/join',
                    data=json.dumps({
                        'accessToken': access_token,
                        'selectedProfile': uuid,
                        'serverId': server_id
                    }),
                    headers={'content-type': 'application/json'})
                print('Client session auth', res.status_code)

                # Send Encryption Response
                packet_out = Packet()
                packet_out.write_varint(0x01)
                pub_key = load_der_public_key(pub_key, default_backend())
                encrypt_token = pub_key.encrypt(ver_tok, PKCS1v15())
                encrypt_secret = pub_key.encrypt(shared_secret, PKCS1v15())
                packet_out.write_varint(len(encrypt_secret))
                packet_out.write(encrypt_secret)
                packet_out.write_varint(len(encrypt_token))
                packet_out.write(encrypt_token)
                connection.send_packet(packet_out)
                connection.configure_encryption(shared_secret)

            # Login Success
            if packet_id == 0x02:
                u = packet_in.read_utf()
                n = packet_in.read_utf()
                print('Name: ' + n + '  |  UUID: ' + u)
                print('Switching to PLAY')
                break

            # Set Compression
            if packet_id == 0x03:
                connection.compression_threshold = packet_in.read_varint()
                print('Compression enabled, threshold:',
                      connection.compression_threshold)
    return connection
Esempio n. 57
0
    def do_authenticate(self) -> None:
        """
            Send server an authentication request
            May need to obtain user credentials
            User may choose authenticate by password or CC
        """
        logger.info("Begining authn process")

        # Gen key
        d = self.read()

        b_server_pub_key = base64.b64decode(d['server_public_key'])
        server_pub_key = serialization.load_der_public_key(
            b_server_pub_key, backend=default_backend())
        shared_key = self.private_key.exchange(server_pub_key)

        # Derivation
        self.key = HKDF(algorithm=hashes.SHA256(),
                        length=16,
                        salt=None,
                        info=b'derivation',
                        backend=default_backend()).derive(shared_key)

        # Send authentication request
        self.server_nonce = os.urandom(16)
        text = str.encode(
            json.dumps({
                "type":
                'AUTHN_REQ',
                "nonce":
                base64.b64encode(self.server_nonce).decode('utf-8')
            }))
        payload, mac = self.encrypt(text)
        msg = {
            "type": 'SECURE',
            "payload": base64.b64encode(payload).decode('utf-8'),
            "h_mac": base64.b64encode(mac).decode('utf-8')
        }
        self.send(msg)

        # Authenticate server
        data = self.read()
        logger.debug("KEY_GEN got -> {}".format(data))
        mtype = data.get('type', 'UNKNOWN')
        if mtype != 'KEY_GEN_OK':
            raise Exception("Something went wrong in key gen")

        sv_nonce = base64.b64decode(data["nonce"])
        b_sv_crt = base64.b64decode(data["sv_cert"])
        self.sv_crt = x509.load_der_x509_certificate(b_sv_crt,
                                                     backend=default_backend())

        with open("./certs/rootCA.crt", "rb") as f:
            data = f.read()
            self.rootCA_crt = x509.load_pem_x509_certificate(
                data, backend=default_backend())

        self.sv_crt_pub_key = self.sv_crt.public_key()
        self.rootCA_crt_pub_key = self.rootCA_crt.public_key()

        hs = hashes.Hash(hashes.SHA256(), backend=default_backend())
        hs.update(self.server_nonce)
        digest = hs.finalize()

        # Verify the signature validation
        try:
            self.sv_crt_pub_key.verify(
                sv_nonce, digest,
                padder.PSS(mgf=padder.MGF1(hashes.SHA256()),
                           salt_length=padder.PSS.MAX_LENGTH),
                utils.Prehashed(hashes.SHA256()))
            logger.info("Server authenticated")
        except Exception as e:
            #TODO fix this ... DONE!
            logger.exception("Invalid signature {}".format(e))
            exit(1)

        #TODO VALIDATE SERVER CHAIN ???

        if self.auth_mode == "pass":
            self.password_validation_request()
        else:
            self.send({"type": "ERROR"})
            raise Exception("Authentication mode not suported")

        # Check if authentication went ok
        p_reply = self.read()
        logger.info(p_reply)
        logger.debug("AUTHN got -> {}".format(p_reply))
        mtype = p_reply.get('type', 'UNKNOWN')
        if mtype != 'AUTHN_OK':
            raise Exception("Authentication fail!!")

        logger.info("Advancing state")
        self.state = STATE_AUTHZ
Esempio n. 58
0
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from pwn import *

p = process("challenge.py")

client_sk = ec.generate_private_key(ec.SECP384R1(), default_backend())
client_pk = client_sk.public_key()
client_der = client_pk.public_bytes(
    encoding=serialization.Encoding.DER,
    format=serialization.PublicFormat.SubjectPublicKeyInfo)

res = p.recvuntil("Send your public key (hex):")
server_der = res.split("\n")[1].decode("hex")

server_pk = serialization.load_der_public_key(server_der, default_backend())
shared_key = client_sk.exchange(ec.ECDH(), server_pk)
derived_key = HKDF(algorithm=hashes.SHA256(),
                   length=16,
                   salt=None,
                   info=b"handshake data",
                   backend=default_backend()).derive(shared_key)

p.sendline(client_der.encode('hex'))
res = p.recvuntil("Please, prove you know stuffs: ")
msg = process(["collide.py",
               derived_key.encode("hex")]).recvall().split("\n")[1]
p.sendline(msg)
flag = p.recvall()
print(flag)
Esempio n. 59
0
    def verifySignature(buffer,
                        signature,
                        publicKey,
                        digestAlgorithm=DigestAlgorithm.SHA256):
        """
        Verify the buffer against the signature using the public key.

        :param buffer: The input buffer to verify.
        :type buffer: Blob or an object which is the same as the bytes() operator
        :param signature: The signature bytes.
        :type signature: Blob or an object which is the same as the bytes()
          operator
        :param publicKey: The object containing the public key, or the public
          key DER which is used to make the PublicKey object.
        :type publicKey: PublicKey or Blob or  an object which is the same as
          the bytes() operator
        :param digestAlgorithm: (optional) The digest algorithm. If omitted, use
          DigestAlgorithm.SHA256.
        :type digestAlgorithm: int from DigestAlgorithm
        :return: True if verification succeeds, False if verification fails.
        :rtype: bool
        :raises: ValueError for an invalid public key type or digestAlgorithm.
        """
        if digestAlgorithm == None:
            digestAlgorithm = DigestAlgorithm.SHA256

        if isinstance(buffer, Blob):
            buffer = buffer.toBytes()
        if isinstance(signature, Blob):
            signature = signature.toBytes()
        if not isinstance(publicKey, PublicKey):
            # Turn publicKey into a PublicKey object.
            if not isinstance(publicKey, Blob):
                publicKey = Blob(publicKey)
            publicKey = PublicKey(publicKey)

        if digestAlgorithm == DigestAlgorithm.SHA256:
            if publicKey.getKeyType() == KeyType.RSA:
                # Get the public key.
                try:
                    cryptoPublicKey = load_der_public_key(
                        publicKey.getKeyDer().toBytes(),
                        backend=default_backend())
                except:
                    return False

                try:
                    cryptoPublicKey.verify(signature, buffer,
                                           padding.PKCS1v15(), hashes.SHA256())
                    return True
                except:
                    return False
            elif publicKey.getKeyType() == KeyType.EC:
                # Get the public key.
                try:
                    cryptoPublicKey = load_der_public_key(
                        publicKey.getKeyDer().toBytes(),
                        backend=default_backend())
                except:
                    return False

                try:
                    cryptoPublicKey.verify(signature, buffer,
                                           ec.ECDSA(hashes.SHA256()))
                    return True
                except:
                    return False
            else:
                raise ValueError("verifySignature: Invalid key type")
        else:
            raise ValueError("verifySignature: Invalid digest algorithm")
Esempio n. 60
0
File: ecc.py Progetto: vinerr/fwlite
 def save_pub_key(pubkey, dest):
     pubk = load_der_public_key(pubkey)
     data = pubk.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo)
     with open(dest, 'wb') as f:
         f.write(data)