예제 #1
0
def verify(public_key: KEY_PUBLIC_TYPES, blocks: Generator[bytes, None, None],
           signature: bytes) -> Tuple[int, bool]:
    count = 0
    try:
        chosen_hash = hashes.SHA256()
        hasher = hashes.Hash(chosen_hash)
        count = 0
        for block in blocks:
            count += len(block)
            hasher.update(block)
        digest = hasher.finalize()
        if isinstance(public_key, RSAPublicKey):
            public_key.verify(
                signature, digest,
                padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                utils.Prehashed(chosen_hash))
        elif isinstance(public_key, Ed25519PublicKey):
            public_key.verify(signature, digest)
        elif isinstance(public_key, EllipticCurvePublicKey):
            public_key.verify(signature, digest,
                              ECDSA(utils.Prehashed(chosen_hash)))
        else:
            raise InternalException("Unknown key type")
        return count, True
    except InvalidSignature:
        return count, False
예제 #2
0
    def stitch_ta():
        try:
            with open(args.sigf, 'r') as sigfile:
                sig = base64.b64decode(sigfile.read())
        except IOError:
            if not os.path.exists(args.digf):
                generate_digest()
            logger.error(
                'No signature file found. Please sign\n %s\n' +
                'offline and place the signature at \n %s\n' +
                'or pass a different location ' +
                'using the --sig argument.\n', args.digf, args.sigf)
            sys.exit(1)
        else:
            try:
                if args.algo == 'TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256':
                    key.verify(
                        sig, img_digest,
                        padding.PSS(mgf=padding.MGF1(chosen_hash),
                                    salt_length=digest_len),
                        utils.Prehashed(chosen_hash))
                elif args.algo == 'TEE_ALG_RSASSA_PKCS1_V1_5_SHA256':
                    key.verify(sig, img_digest, padding.PKCS1v15(),
                               utils.Prehashed(chosen_hash))
            except exceptions.InvalidSignature:
                logger.error('Verification failed, ignoring given signature.')
                sys.exit(1)

            write_image_with_signature(sig)
            logger.info('Successfully applied signature.')
예제 #3
0
    def sign_encrypt_ta():
        if not isinstance(key, rsa.RSAPrivateKey):
            logger.error('Provided key cannot be used for signing, ' +
                         'please use offline-signing mode.')
            sys.exit(1)
        else:
            if args.algo == 'TEE_ALG_RSASSA_PKCS1_PSS_MGF1_SHA256':
                sig = key.sign(
                    img_digest,
                    padding.PSS(
                        mgf=padding.MGF1(chosen_hash),
                        salt_length=digest_len
                    ),
                    utils.Prehashed(chosen_hash)
                )
            elif args.algo == 'TEE_ALG_RSASSA_PKCS1_V1_5_SHA256':
                sig = key.sign(
                    img_digest,
                    padding.PKCS1v15(),
                    utils.Prehashed(chosen_hash)
                )

            if len(sig) != sig_len:
                raise Exception(("Actual signature length is not equal to ",
                                 "the computed one: {} != {}").
                                format(len(sig), sig_len))
            write_image_with_signature(sig)
            logger.info('Successfully signed application.')
예제 #4
0
def validate_cert_matches_private_key(cert_data, key_data, password=None):
    """
    Validate a cert and private key match, and signature can be verified

    :param cert_data: Cert data to test
    :type cert_data: bytes
    :param key_data: Private key data to test
    :type key_data: bytes
    :param password: Optional password of private key
    :return: List of any warnings or raises PkiValidationError
    :rtype: list
    """
    warn = []

    priv_key = load_private_key(key_data, password=password)
    priv_pub_key = priv_key.public_key()

    certs, msgs = load_certs(cert_data)
    if not certs:
        raise PkiValidationError(
            'No certificate found to match against private key.')
    if len(certs) > 1:
        warn.append('Multiple certificates found to compare against key. '
                    'Using first.')
    if msgs:
        warn.extend(msgs)
    cert = certs[0]
    """:type: x509.Certificate"""
    cert_pub_key = cert.public_key()

    priv_pub_key_pem = priv_pub_key.public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo)
    cert_pub_key_pem = cert_pub_key.public_bytes(
        serialization.Encoding.PEM,
        serialization.PublicFormat.SubjectPublicKeyInfo)
    if priv_pub_key_pem != cert_pub_key_pem:
        raise PkiValidationError(
            'Public keys of certificate and private key do not match.')

    # See cryptography.hazmat.primitives.asymmetric.utils.Prehashed example
    prehashed_msg = hashlib.sha256(b"A message I want to sign").digest()
    signature = priv_key.sign(
        prehashed_msg,
        padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                    salt_length=padding.PSS.MAX_LENGTH),
        utils.Prehashed(hashes.SHA256()))
    try:
        priv_pub_key.verify(
            signature, prehashed_msg,
            padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                        salt_length=padding.PSS.MAX_LENGTH),
            utils.Prehashed(hashes.SHA256()))
    except InvalidSignature:
        raise PkiValidationError(
            'Private key signature could not be verified with certificate '
            'public key.')

    return warn
예제 #5
0
    def verify_ta():
        # Extract header
        [magic, img_type, img_size, algo_value, digest_len,
         sig_len] = struct.unpack('<IIIIHH', img[:SHDR_SIZE])

        # Extract digest and signature
        start, end = SHDR_SIZE, SHDR_SIZE + digest_len
        digest = img[start:end]

        start, end = end, SHDR_SIZE + digest_len + sig_len
        signature = img[start:end]

        # Extract UUID and TA version
        start, end = end, end + 16 + 4
        [uuid, ta_version] = struct.unpack('<16sI', img[start:end])

        if magic != SHDR_MAGIC:
            raise Exception("Unexpected magic: 0x{:08x}".format(magic))

        if img_type != SHDR_BOOTSTRAP_TA:
            raise Exception("Unsupported image type: {}".format(img_type))

        if algo_value not in algo.values():
            raise Exception(
                'Unrecognized algorithm: 0x{:08x}'.format(algo_value))

        # Verify signature against hash digest
        if algo_value == 0x70414930:
            key.verify(
                signature, digest,
                padding.PSS(mgf=padding.MGF1(chosen_hash),
                            salt_length=digest_len),
                utils.Prehashed(chosen_hash))
        else:
            key.verify(signature, digest, padding.PKCS1v15(),
                       utils.Prehashed(chosen_hash))

        h = hashes.Hash(chosen_hash, default_backend())

        # sizeof(struct shdr)
        h.update(img[:SHDR_SIZE])

        # sizeof(struct shdr_bootstrap_ta)
        h.update(img[start:end])

        # raw image
        start = end
        end += img_size
        h.update(img[start:end])

        if digest != h.finalize():
            raise Exception('Hash digest does not match')

        logger.info('Trusted application is correctly verified.')
예제 #6
0
    def verify(self, data, signature, rsa_signature_padding=RsaSignaturePadding.PSS):
        """
        Verify signature for selected key implementation.

        Args:
            data (str): data string which will be verified
            signature (str): hex string of signature
            rsa_signature_padding (RsaSignaturePadding, optional): RSA padding for signature

        Returns:
            Boolean ``True`` if signature is correct, or ``False`` if invalid.
        """
        if isinstance(data, str):
            data = utf8_to_bytes(data)

        if rsa_signature_padding:

            if rsa_signature_padding == RsaSignaturePadding.PSS:

                try:
                    prehashed_msg = hashlib.sha256(data).digest()

                    self._public_key_obj.verify(
                        signature=signature,
                        data=prehashed_msg,
                        padding=padding.PSS(
                            mgf=padding.MGF1(hashes.SHA256()),
                            salt_length=padding.PSS.MAX_LENGTH
                        ),
                        algorithm=utils.Prehashed(hashes.SHA256()),
                    )
                    return True

                except InvalidSignature:
                    return False

            if rsa_signature_padding == RsaSignaturePadding.PKCS1v15:

                try:
                    prehashed_msg = hashlib.sha256(data).digest()

                    self._public_key_obj.verify(
                        signature=signature,
                        data=prehashed_msg,
                        padding=padding.PKCS1v15(),
                        algorithm=utils.Prehashed(hashes.SHA256()),
                    )
                    return True

                except InvalidSignature:
                    return False
예제 #7
0
    def verify_signature(self, key_url, signature):

        block_size = 16 * 1024

        chosen_hash = hashes.SHA512()
        hasher = hashes.Hash(chosen_hash, default_backend())
        raw = self.get_raw_data()

        buffer = raw.read(block_size)
        while len(buffer) > 0:
            hasher.update(buffer)
            buffer = raw.read(block_size)

        try:
            self._get_public_key(key_url).verify(
                binascii.unhexlify(signature),
                hasher.finalize(),
                padding.PSS(
                    mgf=padding.MGF1(hashes.SHA512()),
                    salt_length=padding.PSS.MAX_LENGTH
                ),
                utils.Prehashed(chosen_hash)
            )
        except (InvalidSignature, binascii.Error):
            self.logger.error("Bad signature")
            raise InvalidSignature()

        return re.sub(r":.*", "", urllib.parse.urlparse(key_url).netloc)
예제 #8
0
def verify_signature_ec(signature, message, key_name):
    """
    Verify the validity of an 'EC_SIGN_P256_SHA256' signature
    for the specified message

    Example key_name:
      "projects/PROJECT_ID/locations/global/keyRings/RING_ID/cryptoKeys\
              /KEY_ID/cryptoKeyVersions/1"

    Requires:
      cryptography.exceptions.InvalidSignature
      cryptography.hazmat.primitives.asymmetric.ec
      cryptography.hazmat.primitives.asymmetric.utils
      cryptography.hazmat.primitives.hashes
      hashlib
    """
    # get the public key
    client = kms_v1.KeyManagementServiceClient()
    response = client.get_public_key(key_name)
    key_txt = response.pem.encode('ascii')
    public_key = serialization.load_pem_public_key(key_txt, default_backend())

    # get the digest of the message
    digest_bytes = hashlib.sha256(message).digest()

    try:
        # Attempt verification
        public_key.verify(signature, digest_bytes,
                          ec.ECDSA(utils.Prehashed(hashes.SHA256())))
        # No errors were thrown. Verification was successful
        return True
    except InvalidSignature:
        return False
예제 #9
0
파일: ec.py 프로젝트: devsh/zephyrmodules
    def sign_prehashed(self, hash):

        sig_der = self.key.sign(hash, ec.ECDSA(utils.Prehashed(SHA256())))
        signature = utils.decode_dss_signature(sig_der)
        signature_bin = signature[0].to_bytes(32, 'big')
        signature_bin += signature[1].to_bytes(32, 'big')
        return signature_bin
예제 #10
0
def verify_signature(key, hash, signature):
    """ Verification command to check signature

    Verifies a signature which is returned by ``generate_signature``
    using a public key and the hashed message. The returned value
    is a True boolean if the signature is verified correctly, but
    returns a InvalidSignature exception if incorrect.

    Args:
        key (bytes): `SEC1`_ encoded uncompressed public key
        hash (bytes): 32 byte long hash which was signed
        signature (bytes): DER encoded signature
    
    Returns:   
        verification:
            boolean: True if signature gets verified correctly
    
    Raises:
        Any exceptions thrown by the cryptography wrapper are passed through.
    """
    logger.debug('VERIFY SIGNATURE public key %s, hash %s, signature %s',
                 key.hex(), hash.hex(), signature.hex())

    public_key = ec.EllipticCurvePublicKey.from_encoded_point(
        ec.SECP256K1(), key)
    return public_key.verify(signature, hash,
                             ec.ECDSA(utils.Prehashed(
                                 hashes.SHA256()))) == None
예제 #11
0
 def process_challenge_pass(self, message: str) -> None:
     """
         Verify if the challenge reply is corrent
         :param message: challenge reply from client
     """
     if self.state != STATE_CHALLENGE:
         logger.warning("Invalid state (CHALLENGE). Discarding")
         raise Exception("WRONG STATE!!")
     logger.info("PROCESSING CHALLENGE PASSWORD")
     self.user = message["user"]
     self.pwd = base64.b64decode(message["password"])
     if self.user not in user_list.keys():
         self.send({"type": "ERROR", "payload": "Wrong username/password"})
         raise Exception("Something went wrong. Check your user/pass")
     else:
         password = user_list.get(
             self.user).get("password").encode() + self.chalenge_nonce
         hs = hashes.Hash(hashes.SHA256(), backend=default_backend())
         hs.update(password)
         digest = hs.finalize()
         try:
             self.rsa_client_pub_key.verify(
                 self.pwd, digest,
                 padder.PSS(mgf=padder.MGF1(hashes.SHA256()),
                            salt_length=padder.PSS.MAX_LENGTH),
                 utils.Prehashed(hashes.SHA256()))
             self.send({"type": "AUTHN_OK"})
             logger.info("User {} authenticated".format(self.user))
             self.state = STATE_AUTHN
         except Exception as e:
             logger.info("Something went wrong... {}".format(e))
             self.send({"type": "ERROR", "payload": "Invalid signature"})
def verify_sig(user_certfile, sig_file, file_to_sign):
    backend = default_backend()

    with open(user_certfile, 'rb') as file:
        certificate = x509.load_pem_x509_certificate(data=file.read(),
                                                     backend=backend)

    public_key = certificate.public_key()
    # Use the PKCS1v15 padding
    pad = asympadding.PKCS1v15()

    # Load the signature from the signature file
    with open(sig_file, 'rb') as file:
        # get signature from file
        sig = file.read().split(b"-----BEGIN SIGNATURE-----\n")[1].split(
            b"\n-----END SIGNATURE-----")[0]

        myhash, digest = getMyhashDigest(file_to_sign)

        try:
            public_key.verify(signature=base64_decode(sig)[0],
                              data=digest,
                              padding=pad,
                              algorithm=utils.Prehashed(myhash))
        except:
            print("sig is invalid")
        else:
            print("sig is valid")
예제 #13
0
def verify_digest(hash_hex, pubkey_hex, sigb64, hashfunc=hashlib.sha256):
    """
    Given a digest, public key (as hex), and a base64 signature,
    verify that the public key signed the digest.
    Return True if so
    Return False if not
    """
    # NOTE: this method uses the ecdsa package, not cryptography.
    # it is much slower, since it's pure Python.

    if not isinstance(hash_hex, (str, unicode)):
        raise ValueError("hash hex is not a string")

    hash_hex = str(hash_hex)
    pubk_uncompressed_hex = keylib.key_formatting.decompress(pubkey_hex)
    sig_r, sig_s = decode_signature(sigb64)

    pubk = ec.EllipticCurvePublicNumbers.from_encoded_point(
        ec.SECP256K1(),
        pubk_uncompressed_hex.decode('hex')).public_key(default_backend())
    signature = encode_dss_signature(sig_r, sig_s)

    try:
        pubk.verify(signature, hash_hex.decode('hex'),
                    ec.ECDSA(utils.Prehashed(hashes.SHA256())))
        return True
    except InvalidSignature:
        return False
예제 #14
0
    def verify(self, msghash, signature):
        """Verifies the signature of the message hash.

        Args:
            msghash (:class:`pyflocker.ciphers.base.BaseHash`):
                It must be a :any:`BaseHash` object, used to digest the
                message to sign.

            signature (bytes, bytearray): The signature of the message.

        Returns:
            None

        Raises:
            SignatureError: if the signature was incorrect.
            TypeError: If the key is a private key.
        """
        if self._is_private:
            raise TypeError("Only public keys can verify messages.")
        try:
            return self._ctx_func(
                signature=signature,
                data=msghash.digest(),
                algorithm=utils.Prehashed(Hash._get_hash_algorithm(msghash)),
            )
        except bkx.InvalidSignature as e:
            raise exc.SignatureError from e
def verify_signature(filename, backend_sig):
    with open(filename, 'rb') as file:
        data_to_encrypt = file.read()

    myhash = hashes.SHA256()
    hasher_sha256 = hashes.Hash(myhash, backend_sig)
    hasher_sha256.update(data_to_encrypt)
    digest = hasher_sha256.finalize()

    #load the public key from task 2
    with open("ku.pem", 'rb') as file:
        public_key = serialization.load_pem_public_key(data=file.read(),
                                                       backend=backend_sig)

    # Load the signature from the signature file
    with open("file.sig", 'rb') as file:
        #get signature from file
        sig = file.read().split(b"-----BEGIN SIGNATURE-----\n")[1].split(
            b"\n-----END SIGNATURE-----")[0]

    # unpad using same algorithm
    pad = asympadding.PSS(mgf=asympadding.MGF1(hashes.SHA256()),
                          salt_length=asympadding.PSS.MAX_LENGTH)

    try:
        public_key.verify(signature=base64_decode(sig)[0],
                          data=digest,
                          padding=pad,
                          algorithm=utils.Prehashed(myhash))
    except:
        print("sig is invalid")
    else:
        print("signature was verified")
예제 #16
0
파일: signing.py 프로젝트: umutbb/hubble
def sign_target(fname, ofname, private_key=None, **kwargs):  # pylint: disable=unused-argument
    """
    Sign a given `fname` and write the signature to `ofname`.
    """
    if private_key is None:
        private_key = Options.private_key
    # NOTE: This is intended to crash if there's some number of keys other than
    # exactly 1 read from the private_key file:
    the_keys = list(read_certs(private_key))
    if not the_keys:
        log.error(
            'unable to sign %s with %s (no such file or error reading certs)',
            os.path.abspath(fname), os.path.abspath(private_key))
        return
    first_key = the_keys[0]
    hasher, chosen_hash = hash_target(fname, obj_mode=True)
    args = {'data': hasher.finalize()}

    salt_padding_bits = _format_padding_bits(Options.salt_padding_bits)

    log.error('signing %s using %s', fname, private_key)

    if isinstance(first_key, rsa.RSAPrivateKey):
        log.error('signing %s using SBP:%s', fname,
                  _format_padding_bits_txt(salt_padding_bits))
        args['padding'] = padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                      salt_length=salt_padding_bits)
        args['algorithm'] = utils.Prehashed(chosen_hash)
    sig = first_key.sign(**args)
    with open(ofname, 'w') as fh:
        log.error('writing signature of %s to %s', os.path.abspath(fname),
                  os.path.abspath(ofname))
        fh.write(PEM.encode(sig, 'Detached Signature of {}'.format(fname)))
        fh.write('\n')
예제 #17
0
def verify(signature, digest, chosen_hash):
    try:
        public_key = private_key.public_key()
        public_key.verify(signature, digest, utils.Prehashed(chosen_hash))
        return True
    except:
        return False
예제 #18
0
    def verify_message_signature(self,
                                 message: str,
                                 signature: bytes,
                                 hash_algorithm: str = 'SHA256') -> None:
        '''
        Verify the signature for a message

        :raises: InvalidSignature if the signature is invalid, ValueError
                 if the input is invalid
        '''

        if isinstance(message, str):
            message = message.encode('utf-8')
        elif not isinstance(message, bytes):
            raise ValueError(
                f'Message must be of type string or bytes, not {type(message)}'
            )

        if hash_algorithm != 'SHA256':
            raise NotImplementedError(
                'Only SHA256 is supported as hash algorithm')

        chosen_hash = hashes.SHA256()
        digest = Secret._get_digest(message, chosen_hash)

        self.cert.public_key().verify(
            signature, digest,
            padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                        salt_length=padding.PSS.MAX_LENGTH),
            utils.Prehashed(chosen_hash))
예제 #19
0
    def sign_message(self,
                     message: str,
                     hash_algorithm: str = 'SHA256') -> bytes:
        '''
        Sign a message message

        :returns: signature for the message
        :raises: ValueError, NotImplementedError
        '''

        if isinstance(message, str):
            message = message.encode('utf-8')
        elif not isinstance(message, bytes):
            raise ValueError(
                f'Message must be of type string or bytes, not {type(message)}'
            )

        chosen_hash = hashes.SHA256()

        digest = Secret._get_digest(message, chosen_hash)

        signature = self.private_key.sign(
            digest,
            padding.PSS(mgf=padding.MGF1(chosen_hash),
                        salt_length=padding.PSS.MAX_LENGTH),
            utils.Prehashed(chosen_hash))

        return signature
def verify_certificate(user_certfile):

    backend = default_backend()

    with open(user_certfile, 'rb') as file:
        certificate = x509.load_pem_x509_certificate(data=file.read(),
                                                     backend=backend)

    public_key = certificate.public_key()
    sig = certificate.signature
    #print("sig is", sig)
    data = certificate.tbs_certificate_bytes

    myhash, digest = hashData(backend, data)
    pad = asympadding.PKCS1v15()

    try:
        public_key.verify(
            #signature=base64_decode(sig)[0],
            signature=sig,
            data=digest,
            padding=pad,
            algorithm=utils.Prehashed(myhash))
    except:
        print("sig is invalid")
    else:
        print("sig is valid")
예제 #21
0
def verifySignatureRSA(signature, message, client, key_path):
    """
    Verify the validity of an 'RSA_SIGN_PSS_2048_SHA256' signature for the
    specified message

    Requires:
      cryptography.exceptions.InvalidSignature
      cryptography.hazmat.primitives.asymmetric.padding
      cryptography.hazmat.primitives.asymmetric.utils
      cryptography.hazmat.primitives.hashes
      hashlib
    """
    public_key = getAsymmetricPublicKey(client, key_path)
    digest_bytes = hashlib.sha256(message).digest()

    try:
        # Attempt verification
        public_key.verify(
            signature, digest_bytes,
            padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=32),
            utils.Prehashed(hashes.SHA256()))
        # No errors were thrown. Verification was successful
        return True
    except InvalidSignature:
        return False
예제 #22
0
파일: ECC.py 프로젝트: arunanshub/pyflocker
    def verify(self, msghash: base.BaseHash, signature: bytes) -> None:
        """Verifies the signature of the message hash.

        Args:
            msghash (:class:`pyflocker.ciphers.base.BaseHash`):
                The hash algorithm used to digest the object.

            signature (bytes, bytesarray):
                signature must be a ``bytes`` or ``bytes-like`` object.

        Returns:
            None

        Raises:
            SignatureError: if the signature was incorrect.
            TypeError: if the key is not a public key.
        """
        if self._is_private:
            raise TypeError("Only public keys can verify messages.")

        try:
            if self._algorithm is None:
                return self._ctx_func(signature, msghash.digest())
            return self._ctx_func(
                signature,
                msghash.digest(),
                self._algorithm(
                    utils.Prehashed(Hash._get_hash_algorithm(msghash))),
            )
        except bkx.InvalidSignature as e:
            raise exc.SignatureError from e
예제 #23
0
    def rsa_signature(self, data):

        # Generate a hash function based on SHA256
        hash = hashes.SHA256()
        hash_object = hashes.Hash(hash, default_backend())

        # In blocks of size of 2048 bits, sign the
        # data passed to the function.
        data_len = len(data)
        read_size = 2048
        if data_len > 2048:
            with open(data, 'rb') as obj:
                while data_len > 0:
                    hash_object.update(obj.read(read_size))
                    data_len = data_len - read_size
                    read_size = data_len
        else:
            hash_object.update(data)

        digest = hash_object.finalize()

        signature = self.__private_key.sign(digest,
                                            padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
                                                        salt_length=padding.PSS.MAX_LENGTH),
                                            utils.Prehashed(hash))

        return signature
def sign_file(password, file_to_sign, private_key_file, sig_filename):
    backend = default_backend()
    myhash, digest = getMyhashDigest(file_to_sign)

    #load the private key from task 2
    password = bytes(password, 'utf-8')

    with open(private_key_file, 'rb') as file:
        private_key = serialization.load_pem_private_key(data=file.read(),
                                                         password=password,
                                                         backend=backend)

    # hashed data needs to be padded so it fits correctly
    pad = asympadding.PKCS1v15()

    sig = base64_encode(
        private_key.sign(data=digest,
                         padding=pad,
                         algorithm=utils.Prehashed(myhash)))[0]

    sig_file = open(sig_filename, "wb")
    sig_file.write(b"-----BEGIN SIGNATURE-----\n")
    sig_file.write(sig)
    sig_file.write(b"-----END SIGNATURE-----\n")
    sig_file.close()
def sign_file(file_name, backend_sign):
    with open(file_name, 'rb') as file:
        data_to_encrypt = file.read()

    myhash = hashes.SHA256()
    hasher_sha256 = hashes.Hash(myhash, backend)
    hasher_sha256.update(data_to_encrypt)
    digest = hasher_sha256.finalize()

    #load the private key from task 2
    password = bytes("hello", 'utf-8')

    with open("kr.pem", 'rb') as file:
        private_key = serialization.load_pem_private_key(data=file.read(),
                                                         password=password,
                                                         backend=backend_sign)

    # hashed data needs to be padded so it fits correctly
    pad = asympadding.PSS(mgf=asympadding.MGF1(hashes.SHA256()),
                          salt_length=asympadding.PSS.MAX_LENGTH)

    sig = base64_encode(
        private_key.sign(data=digest,
                         padding=pad,
                         algorithm=utils.Prehashed(myhash)))[0]

    sig_file = open("file.sig", "wb")
    sig_file.write(b"-----BEGIN SIGNATURE-----\n")
    sig_file.write(sig)
    sig_file.write(b"-----END SIGNATURE-----\n")
    sig_file.close()

    print("Signed file with private key and wrote to file.sig")
예제 #26
0
    def verify(self,
               message: bytes,
               verifying_key: UmbralPublicKey,
               is_prehashed: bool = False) -> bool:
        """
        Verifies that a message's signature was valid.

        :param message: The message to verify
        :param verifying_key: UmbralPublicKey of the signer
        :param is_prehashed: True if the message has been prehashed previously
        :return: True if valid, False if invalid
        """
        cryptography_pub_key = verifying_key.to_cryptography_pubkey()
        if is_prehashed:
            signature_algorithm = ECDSA(utils.Prehashed(self.hash_algorithm()))
        else:
            signature_algorithm = ECDSA(self.hash_algorithm())

        # TODO: Raise error instead of returning boolean
        try:
            cryptography_pub_key.verify(
                signature=self._der_encoded_bytes(),
                data=message,
                signature_algorithm=signature_algorithm)
        except InvalidSignature:
            return False
        return True
예제 #27
0
def sign(source_path, target_path, cert_path, priv_path):
    hasher = hashes.Hash(HASH, default_backend())

    with open(priv_path, 'rb') as fkey:
        key = serialization.load_pem_private_key(fkey.read(),
                                                 password=None,
                                                 backend=default_backend())

    with open(source_path, 'rb') as filein:
        buf = filein.read(BUFLEN)

        while buf:
            hasher.update(buf)
            buf = filein.read(BUFLEN)

        digest = hasher.finalize()
        signature = key.sign(digest, PADDING, utils.Prehashed(HASH))

        with open(target_path, 'wb') as fileout:
            fileout.write(MAGIC)

            with open(cert_path, 'rb') as filecert:
                copyfileobj(filecert, fileout)

            fileout.write(b'\0' + signature)
            filein.seek(0, SEEK_SET)
            copyfileobj(filein, fileout)
예제 #28
0
    def sign_data(self, data, is_hash=False):
        """인증서 개인키로 DATA 서명

        :param data: 서명 대상 원문
        :param is_hash: when data is hashed True
        :return: 서명 데이터
        """
        hash_algorithm = hashes.SHA256()
        if is_hash:
            hash_algorithm = utils.Prehashed(hash_algorithm)
            if isinstance(data, str):
                try:
                    data = binascii.unhexlify(data)
                except Exception as e:
                    logging.error(
                        f"hash data must hex string or bytes \n exception : {e}"
                    )
                    return None

        if not isinstance(data, (bytes, bytearray)):
            logging.error(f"data must be bytes \n")
            return None

        if isinstance(self.__peer_pri,
                      ec.EllipticCurvePrivateKeyWithSerialization):
            return self.__peer_pri.sign(data, ec.ECDSA(hash_algorithm))
        elif isinstance(self.__peer_pri, rsa.RSAPrivateKeyWithSerialization):
            return self.__peer_pri.sign(data, padding.PKCS1v15(),
                                        hash_algorithm)
        else:
            logging.error("Unknown PrivateKey Type : %s",
                          type(self.__peer_pri))
            return None
예제 #29
0
    def testCorrectTransactionIsVerified(self):
        private_key = dsa.generate_private_key(2048,
                                               backends.default_backend())
        public_key = private_key.public_key()
        public_key_bytes = public_key.public_bytes(
            serialization.Encoding.PEM,
            serialization.PublicFormat.SubjectPublicKeyInfo)
        public_key_string = binascii.hexlify(public_key_bytes)

        first_transaction = plebcoin_pb2.Transaction()
        output = first_transaction.outputs.add()
        output.amount = 10.0
        output.receiver = public_key_string
        first_transaction_hash = node._HashTransaction(first_transaction)
        transactions = {first_transaction_hash: first_transaction}

        transaction = plebcoin_pb2.Transaction()
        transaction.inputs.add(sender=public_key_string,
                               transaction=first_transaction_hash)
        transaction.outputs.add(amount=10.0, receiver='1')

        transaction.hash, hash_bytes = (
            node._ComputeInnerTransactionHash(transaction))
        signature_bytes = private_key.sign(hash_bytes,
                                           utils.Prehashed(hashes.SHA256()))
        signature = binascii.hexlify(signature_bytes)
        transaction.signatures.append(signature)

        self.assertTrue(
            node._VerifyTransaction(transaction, transactions, set()))
예제 #30
0
def writeSig(sig_fname, digest, private_key):
    # This implementation uses lower padding for the verification
    #pad = paddingAsym.PSS(
    #                      mgf=paddingAsym.MGF1(hashes.SHA256()),
    #                      salt_length=paddingAsym.PSS.MAX_LENGTH
    #                      )

    pad = paddingAsym.PKCS1v15()

    if debug:
        print("Pad:", pad)

    sig = private_key.sign(data=digest,
                           padding=pad,
                           algorithm=utils.Prehashed(hashes.SHA256()))

    if debug:
        print("Sig Written:", sig)
        print("Encoded Sig:", base64.encodestring(sig))  # has \n included

    # Writing signature to .pem files
    try:
        with open(sig_fname, 'wb') as file:
            file.write(str.encode("-----BEGIN SIGNATURE-----\n"))
            file.write(base64.encodestring(sig))
            file.write(str.encode("-----END SIGNATURE-----"))
            file.close()
    except IOError:
        print("Could not read file:", sig_fname)
        raise IOError
        return False

    return sig