コード例 #1
0
ファイル: opgp.py プロジェクト: nevun/yubikey-manager
 def create_digest(self):
     algorithm = {self.SHA256: hashes.SHA256, self.SHA512: hashes.SHA512}[self]
     return hashes.Hash(algorithm(), default_backend())
コード例 #2
0
ファイル: dsa.py プロジェクト: nryoung/cryptography
 def __init__(self, backend, private_key, algorithm):
     self._backend = backend
     self._private_key = private_key
     self._algorithm = algorithm
     self._hash_ctx = hashes.Hash(self._algorithm, self._backend)
コード例 #3
0
def Hash(s):
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(s)
    return digest.finalize()
コード例 #4
0
    def hash_sha256(self, payload: bytes):
        digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
        digest.update(payload)

        return digest.finalize()
コード例 #5
0
    conn.connect((HOST, PORT))

    #receive N and g
    NBytes = conn.recv(64)
    gBytes = conn.recv(64)
    N = int.from_bytes(NBytes, 'big')
    g = int.from_bytes(gBytes, 'big')
    print("Client: N = " + str(N))
    print("Client: g = " + str(g))

    # compute k = hash(N||g)
    Nbytes = N.to_bytes(64, 'big')
    gBytes = g.to_bytes(64, 'big')
    tohash = b"".join([Nbytes, gBytes])

    k = hashes.Hash(hashes.SHA256(), backend=default_backend())
    k.update(tohash)
    k = k.finalize()
    print("Client: k = " + str(int.from_bytes(k, 'big')))

    # generate a random 16-byte salt (s)
    s = os.urandom(16)
    print("Client: s = <" + s.hex() + ">")

    # compute x = H(s||p)
    pBytes = p.encode('utf-8')
    tohash = b"".join([s, pBytes])

    x = hashes.Hash(hashes.SHA256(), backend=default_backend())
    x.update(tohash)
    x = x.finalize()
コード例 #6
0
    def generateSignEC(self, params, session):
        public_template = [
            (PyKCS11.CKA_CLASS, PyKCS11.CKO_PUBLIC_KEY),
            (PyKCS11.CKA_VERIFY, PyKCS11.CK_TRUE),
            (PyKCS11.CKA_KEY_TYPE, PyKCS11.CKK_EC),
            (PyKCS11.CKA_EC_PARAMS, params),
        ]

        private_template = [
            (PyKCS11.CKA_CLASS, PyKCS11.CKO_PRIVATE_KEY),
            (PyKCS11.CKA_SIGN, PyKCS11.CK_TRUE),
        ]

        if params == P256_PARAMS:
            keysize = 256
            mech = PyKCS11.CKM_ECDSA_SHA256
            h = hashes.SHA256()
        elif params == P384_PARAMS:
            keysize = 384
            mech = PyKCS11.CKM_ECDSA_SHA384
            h = hashes.SHA384()
        elif params == P521_PARAMS:
            keysize = 521
            mech = PyKCS11.CKM_ECDSA_SHA512
            h = hashes.SHA512()

        self.assertIn(PyKCS11.CKM[mech], self.mechs)
        info = self.pkcs11.getMechanismInfo(self.slot, PyKCS11.CKM[mech])
        self.assertGreaterEqual(keysize, info.ulMinKeySize)
        self.assertLessEqual(keysize, info.ulMaxKeySize)

        (pubkey, privkey) = session.generateKeyPair(
            public_template, private_template, mecha=PyKCS11.MechanismECGENERATEKEYPAIR
        )

        tosign = os.urandom(2000)
        digest = hashes.Hash(h, backend=default_backend())
        digest.update(tosign)
        hashed = digest.finalize()

        signature = session.sign(privkey, tosign, PyKCS11.Mechanism(mech, None))

        res = session.verify(pubkey, tosign, signature, PyKCS11.Mechanism(mech, None))
        self.assertTrue(res)

        key = self.pubobjToKey(pubkey, session)
        key2 = serialization.load_der_public_key(
            bytes(session.getAttributeValue(pubkey, [PyKCS11.CKA_VALUE])[0]),
            default_backend(),
        )
        self.assertEqual(key.public_numbers(), key2.public_numbers())

        signature = decode_ec_sig(signature)
        key.verify(signature, tosign, ec.ECDSA(h))

        signature = session.sign(
            privkey, hashed, PyKCS11.Mechanism(PyKCS11.CKM_ECDSA, None)
        )

        res = session.verify(
            pubkey, hashed, signature, PyKCS11.Mechanism(PyKCS11.CKM_ECDSA, None)
        )
        self.assertTrue(res)

        key = self.pubobjToKey(pubkey, session)
        signature = decode_ec_sig(signature)
        key.verify(signature, tosign, ec.ECDSA(h))

        session.destroyObject(privkey)
コード例 #7
0
 def fingerprint(self, algorithm):
     h = hashes.Hash(algorithm, self._backend)
     h.update(self.public_bytes(serialization.Encoding.DER))
     return h.finalize()
コード例 #8
0
 def test_unsupported_hash(self, backend):
     with raises_unsupported_algorithm(_Reasons.UNSUPPORTED_HASH):
         hashes.Hash(DummyHashAlgorithm(), backend)
コード例 #9
0
ファイル: authdatabase.py プロジェクト: hungn97/CoroNOTrack
def main():
    with sqlite3.connect("user_database.db") as db:
        cursor = db.cursor()

    # All the fields that will be include in the auth database
    cursor.execute("""CREATE TABLE IF NOT EXISTS user(
            user_id VARBINARY(300) NOT NULL,    
            user_pw VARBINARY(300) NOT NULL,
            role VARBINARY(300) NOT NULL,
            dpub VARBINARY(300) NOT NULL
    )""")
    ''' FORMAT : userid, H{userpw}, role, AES{DPub}'''

    # DOCTOR #1: 30096073, H{password}, 1, AES{publickey}---------------------
    User = '******'

    Prehash_Password = '******'
    pw_hash_func = hashes.Hash(hashes.SHA256(), backend=default_backend())
    pw_hash_func.update(Prehash_Password.encode())
    Password = pw_hash_func.finalize()

    Role = '1'
    Dpub = enc.encrypt(key)
    params = (User, Password, Role, Dpub)
    cursor.execute("""
    INSERT INTO user(user_id,user_pw,role,dpub)
    VALUES(?,?,?,?)""", params)

    # PATIENT #1: H{12131415}, H{password}, 0, AES{publickey}---------------------
    User = '******'
    Prehash_Password = '******'
    pw_hash_func = hashes.Hash(hashes.SHA256(), backend=default_backend())
    pw_hash_func.update(Prehash_Password.encode())
    Password = pw_hash_func.finalize()
    Role = '0'
    Dpub = enc.encrypt(key)

    params = (User,Password,Role, Dpub)

    cursor.execute("""
    INSERT INTO user(user_id,user_pw,role,dpub)
    VALUES(?,?,?,?)""", params)

    # DOCTOR #2: H{13141516}, H{password}, 1, AES{publickey}---------------------
    User = '******'
    Prehash_Password = '******'
    pw_hash_func = hashes.Hash(hashes.SHA256(), backend=default_backend())
    pw_hash_func.update(Prehash_Password.encode())
    Password = pw_hash_func.finalize()
    Role = '1'
    Dpub = enc.encrypt(key)

    params = (User,Password,Role, Dpub)

    cursor.execute("""
    INSERT INTO user(user_id,user_pw,role,dpub)
    VALUES(?,?,?,?)""", params)

    # INSURANCE #1: H{14151617}, H{password}, 2, AES{publickey}---------------------
    User = '******'
    Prehash_Password = '******'
    pw_hash_func = hashes.Hash(hashes.SHA256(), backend=default_backend())
    pw_hash_func.update(Prehash_Password.encode())
    Password = pw_hash_func.finalize()
    Role = '2'
    Dpub = enc.encrypt(key)
    print(Dpub)
    print(enc.decrypt(Dpub))
    params = (User,Password,Role, Dpub)

    cursor.execute("""
    INSERT INTO user(user_id,user_pw,role, dpub)
    VALUES(?,?,?,?)""", params)

    db.commit()

    cursor.execute("SELECT * FROM user")
    user = cursor.fetchone()
    print(user)
コード例 #10
0
 def test_hash_reject_unicode(self, backend):
     m = hashes.Hash(hashes.SHA1(), backend=backend)
     with pytest.raises(TypeError):
         m.update("\u00FC")  # type: ignore[arg-type]
コード例 #11
0
 def test_hash_algorithm_instance(self, backend):
     with pytest.raises(TypeError):
         hashes.Hash(hashes.SHA1, backend=backend)  # type: ignore[arg-type]
コード例 #12
0
def test_buffer_protocol_hash(backend):
    data = binascii.unhexlify(b"b4190e")
    h = hashes.Hash(hashes.SHA256(), backend)
    h.update(bytearray(data))
    assert h.finalize() == binascii.unhexlify(
        b"dff2e73091f6c05e528896c4c831b9448653dc2ff043528f6769437bc7b975c2")
コード例 #13
0
def test_invalid_backend():
    pretend_backend = object()

    with raises_unsupported_algorithm(_Reasons.BACKEND_MISSING_INTERFACE):
        hashes.Hash(hashes.SHA1(), pretend_backend)
コード例 #14
0
def create_hash(msg):
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(msg)
    msg_digest = digest.finalize()
    return base64.b64encode(msg_digest)
コード例 #15
0
    def rsaPkcsSigs(self, session, pubkey, privkey):
        mechs = [
            {
                "name": "CKM_SHA1_RSA_PKCS",
                "h": hashes.SHA1(),
                "m": PyKCS11.CKM_SHA1_RSA_PKCS,
                "di": SHA1_DI,
            },
            {
                "name": "CKM_SHA256_RSA_PKCS",
                "h": hashes.SHA256(),
                "m": PyKCS11.CKM_SHA256_RSA_PKCS,
                "di": SHA256_DI,
            },
            {
                "name": "CKM_SHA384_RSA_PKCS",
                "h": hashes.SHA384(),
                "m": PyKCS11.CKM_SHA384_RSA_PKCS,
                "di": SHA384_DI,
            },
            {
                "name": "CKM_SHA512_RSA_PKCS",
                "h": hashes.SHA512(),
                "m": PyKCS11.CKM_SHA512_RSA_PKCS,
                "di": SHA512_DI,
            },
        ]
        for mech in mechs:
            self.assertIn(mech["name"], self.mechs)
            info = self.pkcs11.getMechanismInfo(self.slot, mech["name"])
            self.assertGreaterEqual(2048, info.ulMinKeySize)
            self.assertLessEqual(2048, info.ulMaxKeySize)

            tosign = os.urandom(2000)
            digest = hashes.Hash(mech["h"], backend=default_backend())
            hashed = mech["di"]
            digest.update(tosign)
            hashed += digest.finalize()

            signature = session.sign(
                privkey, tosign, PyKCS11.Mechanism(mech["m"], None)
            )

            res = session.verify(
                pubkey, tosign, signature, PyKCS11.Mechanism(mech["m"], None)
            )
            self.assertTrue(res)

            key = self.pubobjToKey(pubkey, session)
            key2 = serialization.load_der_public_key(
                bytes(session.getAttributeValue(pubkey, [PyKCS11.CKA_VALUE])[0]),
                default_backend(),
            )
            self.assertEqual(key.public_numbers(), key2.public_numbers())

            key.verify(
                bytes(signature), tosign, padding.PKCS1v15(), mech["h"]
            )

            signature = session.sign(
                privkey, hashed, PyKCS11.Mechanism(PyKCS11.CKM_RSA_PKCS, None)
            )

            res = session.verify(
                pubkey, hashed, signature, PyKCS11.Mechanism(PyKCS11.CKM_RSA_PKCS, None)
            )
            self.assertTrue(res)

            key.verify(
                bytes(signature), tosign, padding.PKCS1v15(), mech["h"]
            )
コード例 #16
0
    def precompute_values(self) -> bytes:
        capsule = self.task.capsule
        cfrag = self.task.cfrag

        umbral_params = default_params()
        e, v, _ = capsule.components()

        e1 = cfrag.point_e1
        v1 = cfrag.point_v1
        e2 = cfrag.proof.point_e2
        v2 = cfrag.proof.point_v2
        u = umbral_params.u
        u1 = cfrag.proof.point_kfrag_commitment
        u2 = cfrag.proof.point_kfrag_pok
        metadata = cfrag.proof.metadata

        h = self.get_proof_challenge_scalar()

        e1h = h * e1
        v1h = h * v1
        u1h = h * u1

        z = cfrag.proof.bn_sig
        ez = z * e
        vz = z * v
        uz = z * u

        only_y_coord = dict(x_coord=False, y_coord=True)
        # E points
        e_y = get_coordinates_as_bytes(e, **only_y_coord)
        ez_xy = get_coordinates_as_bytes(ez)
        e1_y = get_coordinates_as_bytes(e1, **only_y_coord)
        e1h_xy = get_coordinates_as_bytes(e1h)
        e2_y = get_coordinates_as_bytes(e2, **only_y_coord)
        # V points
        v_y = get_coordinates_as_bytes(v, **only_y_coord)
        vz_xy = get_coordinates_as_bytes(vz)
        v1_y = get_coordinates_as_bytes(v1, **only_y_coord)
        v1h_xy = get_coordinates_as_bytes(v1h)
        v2_y = get_coordinates_as_bytes(v2, **only_y_coord)
        # U points
        uz_xy = get_coordinates_as_bytes(uz)
        u1_y = get_coordinates_as_bytes(u1, **only_y_coord)
        u1h_xy = get_coordinates_as_bytes(u1h)
        u2_y = get_coordinates_as_bytes(u2, **only_y_coord)

        # Get hashed KFrag validity message
        hash_function = hashes.Hash(hashes.SHA256(), backend=backend)

        kfrag_id = cfrag.kfrag_id
        precursor = cfrag.point_precursor
        delegating_pubkey = self.delegating_pubkey
        receiving_pubkey = self.receiving_pubkey

        validity_input = (kfrag_id, delegating_pubkey, receiving_pubkey, u1,
                          precursor)
        kfrag_validity_message = bytes().join(
            bytes(item) for item in validity_input)
        hash_function.update(kfrag_validity_message)
        hashed_kfrag_validity_message = hash_function.finalize()

        # Get KFrag signature's v value
        kfrag_signature_v = get_signature_recovery_value(
            message=hashed_kfrag_validity_message,
            signature=cfrag.proof.kfrag_signature,
            public_key=self.verifying_pubkey,
            is_prehashed=True)

        cfrag_signature_v = get_signature_recovery_value(
            message=bytes(cfrag),
            signature=self.task.cfrag_signature,
            public_key=self.ursula_pubkey)

        metadata_signature_v = get_signature_recovery_value(
            message=self.task.signature,
            signature=metadata,
            public_key=self.ursula_pubkey)

        specification = self.task.get_specification(
            ursula_pubkey=self.ursula_pubkey,
            alice_address=self.alice_address,
            blockhash=self.blockhash,
            ursula_identity_evidence=self.ursula_identity_evidence)

        specification_signature_v = get_signature_recovery_value(
            message=specification,
            signature=self.task.signature,
            public_key=self.bob_verifying_key)

        ursula_pubkey_prefix_byte = bytes(self.ursula_pubkey)[0:1]

        # Bundle everything together
        pieces = (
            e_y,
            ez_xy,
            e1_y,
            e1h_xy,
            e2_y,
            v_y,
            vz_xy,
            v1_y,
            v1h_xy,
            v2_y,
            uz_xy,
            u1_y,
            u1h_xy,
            u2_y,
            hashed_kfrag_validity_message,
            self.alice_address,
            # The following single-byte values are interpreted as a single bytes5 variable by the Solidity contract
            kfrag_signature_v,
            cfrag_signature_v,
            metadata_signature_v,
            specification_signature_v,
            ursula_pubkey_prefix_byte,
        )
        return b''.join(pieces)
コード例 #17
0
    def rsaPssSigs(self, session, pubkey, privkey, saltlen=0):
        mechs = [
            {
                "name": "CKM_SHA1_RSA_PKCS_PSS",
                "m_mech": PyKCS11.CKM_SHA1_RSA_PKCS_PSS,
                "m_hash": PyKCS11.CKM_SHA_1,
                "mgf1": PyKCS11.CKG_MGF1_SHA1,
                "hash": hashes.SHA1(),
            },
            {
                "name": "CKM_SHA256_RSA_PKCS_PSS",
                "m_mech": PyKCS11.CKM_SHA256_RSA_PKCS_PSS,
                "m_hash": PyKCS11.CKM_SHA256,
                "mgf1": PyKCS11.CKG_MGF1_SHA256,
                "hash": hashes.SHA256(),
            },
            {
                "name": "CKM_SHA384_RSA_PKCS_PSS",
                "m_mech": PyKCS11.CKM_SHA384_RSA_PKCS_PSS,
                "m_hash": PyKCS11.CKM_SHA384,
                "mgf1": PyKCS11.CKG_MGF1_SHA384,
                "hash": hashes.SHA384(),
            },
            {
                "name": "CKM_SHA512_RSA_PKCS_PSS",
                "m_mech": PyKCS11.CKM_SHA512_RSA_PKCS_PSS,
                "m_hash": PyKCS11.CKM_SHA512,
                "mgf1": PyKCS11.CKG_MGF1_SHA512,
                "hash": hashes.SHA512(),
            },
        ]

        for mech in mechs:
            self.assertIn(mech["name"], self.mechs)
            info = self.pkcs11.getMechanismInfo(self.slot, mech["name"])

            tosign = os.urandom(1500)

            sig = session.sign(
                privkey,
                tosign,
                PyKCS11.RSA_PSS_Mechanism(
                    mecha=mech["m_mech"],
                    hashAlg=mech["m_hash"],
                    mgf=mech["mgf1"],
                    sLen=saltlen,
                ),
            )

            res = session.verify(
                pubkey,
                tosign,
                sig,
                PyKCS11.RSA_PSS_Mechanism(
                    mech["m_mech"],
                    hashAlg=mech["m_hash"],
                    mgf=mech["mgf1"],
                    sLen=saltlen,
                ),
            )
            self.assertTrue(res)

            key = self.pubobjToKey(pubkey, session)
            key2 = serialization.load_der_public_key(
                bytes(session.getAttributeValue(pubkey, [PyKCS11.CKA_VALUE])[0]),
                default_backend(),
            )
            self.assertEqual(key.public_numbers(), key2.public_numbers())

            key.verify(
                bytes(sig),
                tosign,
                padding.PSS(padding.MGF1(mech["hash"]), saltlen),
                mech["hash"],
            )

            digest = hashes.Hash(mech["hash"], backend=default_backend())
            digest.update(tosign)
            hashed = digest.finalize()

            sig = session.sign(
                privkey,
                hashed,
                PyKCS11.RSA_PSS_Mechanism(
                    mecha=mech["m_mech"],
                    hashAlg=mech["m_hash"],
                    mgf=mech["mgf1"],
                    sLen=saltlen,
                ),
            )
            res = session.verify(
                pubkey,
                hashed,
                sig,
                PyKCS11.RSA_PSS_Mechanism(
                    mech["m_mech"],
                    hashAlg=mech["m_hash"],
                    mgf=mech["mgf1"],
                    sLen=saltlen,
                ),
            )
            self.assertTrue(res)
コード例 #18
0
def sign_csr(cert_sign_req, ca_cert, ca_privkey, device_sn, nva_years):

    csr = x509.load_pem_x509_csr(cert_sign_req, default_backend())

    nvb_time = datetime.utcnow()
    nvb_time = nvb_time.replace(minute=0, second=0)
    nva_time = nvb_time
    nva_time = nva_time.replace(year=nvb_time.year + nva_years)
    expire_years = 0
    enc_dates = encode_dates(nvb_time, expire_years)
    # SAH256 hash of the public key and encoded dates
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    pub_nums = csr.public_key().public_numbers()

    try:
        pubkey = pub_nums.x.to_bytes(32, byteorder='big', signed=False)
        pubkey += pub_nums.y.to_bytes(32, byteorder='big', signed=False)
    except AttributeError:  # In case of python2 above code block will raise AttributeError
        pubkey = bytes(
            bytearray.fromhex(hex(pub_nums.x)[2:-1] + hex(pub_nums.y)[2:-1]))

    digest.update(pubkey)
    digest.update(enc_dates)
    raw_sn = bytearray(digest.finalize()[:16])
    raw_sn[
        0] = raw_sn[0] & 0x7F  # Force MSB bit to 0 to ensure positive integer
    raw_sn[0] = raw_sn[
        0] | 0x40  # Force next bit to 1 to ensure the integer won't be trimmed in ASN.1 DER encoding
    try:
        cert_sn = int.from_bytes(raw_sn, byteorder='big', signed=False)
    except AttributeError:  # In case of python2 above code block will raise AttributeError
        cert_sn = int(binascii.hexlify(raw_sn), 16)

    dev_sn = str(device_sn.upper())

    device_subject = x509.Name([
        x509.NameAttribute(
            NameOID.ORGANIZATION_NAME,
            ca_cert.subject.get_attributes_for_oid(
                NameOID.ORGANIZATION_NAME)[0].value),
        x509.NameAttribute(NameOID.COMMON_NAME, dev_sn),
    ])

    device_cert = x509.CertificateBuilder().subject_name(
        device_subject).issuer_name(ca_cert.subject).public_key(
            csr.public_key()).serial_number(cert_sn).not_valid_before(
                nvb_time).not_valid_after(nva_time).add_extension(
                    x509.KeyUsage(digital_signature=True,
                                  key_encipherment=True,
                                  content_commitment=True,
                                  data_encipherment=False,
                                  key_agreement=False,
                                  encipher_only=False,
                                  decipher_only=False,
                                  key_cert_sign=False,
                                  crl_sign=False),
                    critical=True).add_extension(
                        x509.BasicConstraints(ca=False, path_length=None),
                        critical=True).add_extension(
                            x509.AuthorityKeyIdentifier.from_issuer_public_key(
                                ca_privkey.public_key()),
                            critical=False).sign(private_key=ca_privkey,
                                                 algorithm=hashes.SHA256(),
                                                 backend=default_backend())
    return device_cert.public_bytes(serialization.Encoding.PEM)
コード例 #19
0
ファイル: Encryption.py プロジェクト: coal0/Steganography
def get_key(password):
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(password)
    return base64.urlsafe_b64encode(digest.finalize())
コード例 #20
0
ファイル: ec.py プロジェクト: lastknight00/web_scraping
 def __init__(self, backend, public_key, signature, algorithm):
     self._backend = backend
     self._public_key = public_key
     self._signature = signature
     self._digest = hashes.Hash(algorithm, backend)
コード例 #21
0
def sha512(data):
    h = hashes.Hash(hashes.SHA512(), backend=crypto_backend)
    h.update(data)
    return binascii.b2a_hex(h.finalize())
コード例 #22
0
ファイル: ec.py プロジェクト: lastknight00/web_scraping
 def __init__(self, backend, private_key, algorithm):
     self._backend = backend
     self._private_key = private_key
     self._digest = hashes.Hash(algorithm, backend)
コード例 #23
0
 def generatesymkey(self, key):
     digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
     digest.update(str.encode(str(key)))
     ssu = digest.finalize()
     return ssu
コード例 #24
0
def get_symmetric_signature(options, manifestInput, enc_data):
    input_hash = manifestGet(manifestInput, 'signature.hash') or b''

    # There should always be a signing key on create.
    if not hasattr(options, 'private_key') or not options.private_key:
        if 'psk-master-key' in manifestInput:
            try:
                options.private_key = open(manifestInput['psk-master-key'],
                                           'rb')
            except:
                LOG.critical(
                    'No PSK master key specified and default key ({}) cannot be opened'
                    .format(manifestInput['private-key']))
                sys.exit(1)
        else:
            LOG.critical(
                'Resource is not signed and no PSK master key is provided.')
            sys.exit(1)

    if not symmetricArgsOkay(options):
        LOG.critical('--mac requires:')
        LOG.critical(
            '    --private-key: The master key for generating device PSKs')
        #                                                                                 80 chars ->|
        #             ================================================================================
        LOG.critical(
            '    --psk-table: the output file for PSKs. This argument is optional/ignored'
        )
        LOG.critical('                 when inline encoding is used.')
        LOG.critical(
            '    --psk-table-encoding: the encoding to use for the PSK output file.'
        )
        LOG.critical('    Either:')
        LOG.critical(
            '        --device-urn: The device URN for the target device (Endpoint Client Name)'
        )
        LOG.critical('    OR:')
        LOG.critical(
            '        --filter-id: The filter identifier used to gather device URNs'
        )
        sys.exit(1)

    # Get SHA-256 hash of content and sign it using private key
    sha_content = utils.sha_hash(enc_data)
    # If a hash is provided in the input json, then the encoded content must match the provided hash
    if input_hash and sha_content != binascii.a2b_hex(input_hash):
        LOG.critical(
            'Manifest hash provided in input file does not match hashed output'
        )
        LOG.critical('Expected: {0}'.format(input_hash))
        LOG.critical('Actual:   {0}'.format(binascii.b2a_hex(sha_content)))
        sys.exit(1)

    # Load a default URN out of the settings file.
    devices = manifestGet(manifestInput, 'deviceURNs') or []
    LOG.info('Loaded device URNs from {!r}'.format(defaults.config))
    for dev in devices:
        LOG.info('    {!r}'.format(dev))

    # Optionally load a URN out of the command-line arguments
    if hasattr(options, 'device_urn') and options.device_urn:
        cmdDevs = [options.device_urn]
        LOG.info('Loaded device URNs from input arguments')
        for dev in cmdDevs:
            LOG.info('    {!r}'.format(dev))
        devices.extend(cmdDevs)
    if hasattr(options, 'filter_id') and options.filter_id:
        LOG.critical('Device Filters not supported yet.')
        sys.exit(1)

    # Use only unique devices
    devices = list(set(devices))

    crypto_mode = get_crypto_mode(options, manifestInput)

    payload_key = b''
    if hasattr(options, 'payload_key') and options.payload_key:
        LOG.debug('Converting payload key ({0}) to binary'.format(
            options.payload_key))
        payload_key = bytes(binascii.a2b_hex(options.payload_key))
    LOG.debug('Payload key length: {0}'.format(len(payload_key)))
    master_key = options.private_key.read()
    vendor_id = manifestGet(manifestInput,
                            'resource.resource.manifest.vendorId', 'vendorId')
    class_id = manifestGet(manifestInput, 'resource.resource.manifest.classId',
                           'classId')
    iv = os.urandom(13)
    deviceSymmetricInfos = {}
    # For each device
    maxIndexSize = 0
    maxRecordSize = 0
    LOG.info('Creating per-device validation codes...')
    for device in devices:
        LOG.info('    {!r}'.format(device))

        hkdf = utils.getDevicePSK_HKDF(
            cryptoMode(crypto_mode).name, master_key,
            uuid.UUID(vendor_id).bytes,
            uuid.UUID(class_id).bytes, b'Authentication')
        psk = hkdf.derive(bytes(device, 'utf-8'))
        maxIndexSize = max(maxIndexSize, len(device))
        # Now encrypt the hash with the selected AE algorithm.
        pskCipherData = getDevicePSKData(crypto_mode, psk, iv, sha_content,
                                         payload_key)
        recordData = der_encoder.encode(
            OctetString(
                hexValue=binascii.b2a_hex(pskCipherData).decode("ascii")))
        maxRecordSize = max(maxRecordSize, len(recordData))
        deviceSymmetricInfos[device] = recordData
    # print (deviceSymmetricInfos)
    def proto_encode(x):
        keytable = keytable_pb2.KeyTable()

        for k, d in x.items():
            entry = keytable.entries.add()
            entry.urn = k
            entry.opaque = d
        return keytable.SerializeToString()

    # Save the symmetric info file
    encodedSymmertricInfos = {
        'json':
        lambda x: json.JSONEncoder(default=binascii.b2a_base64).encode(x),
        'cbor':
        lambda x: None,
        'protobuf':
        proto_encode,
        'text':
        lambda x: '\n'.join([
            ','.join([binascii.b2a_hex(y) for y in (k, d)])
            for k, d in x.items()
        ]) + '\n'
        # 'inline' : lambda x : None
    }.get(options.psk_table_encoding)(deviceSymmetricInfos)
    options.psk_table.write(encodedSymmertricInfos)

    #=========================
    # PSK ID is the subject key identifier (hash) of the master key.
    # The URI of the "certificate" is the location at which to find the key table or key query.
    # PSK is known only to the signer and the device
    # PSK Signature is AE(PSK, hash), but it is not included, since it must be distributed in the key table.
    shaMaster = cryptoHashes.Hash(cryptoHashes.SHA256(),
                                  cryptoBackends.default_backend())
    shaMaster.update(master_key)
    subjectKeyIdentifier = shaMaster.finalize()

    mb = MacBlock(pskID=subjectKeyIdentifier,
                  keyTableIV=iv,
                  keyTableRef='thismessage://1',
                  keyTableVersion=0,
                  keyTableRecordSize=maxRecordSize,
                  keyTableIndexSize=maxIndexSize)
    macs = [mb]
    rs = ResourceSignature(hash=sha_content, signatures=[], macs=macs)
    return rs
コード例 #25
0
ファイル: CA.py プロジェクト: furkanatas/SecureChatRoom
def hashMessage(msg):
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(msg)
    return digest.finalize()
コード例 #26
0
def ttp_sign( sock: socket.socket, ttp_key: RSA_key, \
        database: Mapping[str,RSA_key]  ) -> Optional[Mapping[str,RSA_key]]:
    """Carry out the TTP's signing procedure. IMPORTANT: 's' has already
       been read!
    
    PARAMETERS
    ==========
    sock: The communication socket to send/receive data over. Must be closed
       before the function exits.
    ttp_key: An RSA_key object.
    database: A dictionary of all signatures generated, of the form 
        database[server_name] = key, where server_name is a string and
        key is an RSA_key object.

    RETURNS
    =======
    If the server has not requested a signature before, and the values can be 
       signed, return an updated version of the database. If the server has 
       already requested a signature but with different information, return None. 
       If the information was the same, return the database unmodified. If a
       socket error occurs, return None.
    """

    assert type(sock) is socket.socket
    assert type(database) == dict
    nameLengthBytes = receive(sock, 1)

    nameLength = bytes_to_int(nameLengthBytes)
    nameBytes = receive(sock, nameLength)
    N_bytes = receive(sock, 128)
    e_bytes = receive(sock, 128)
    if (len(N_bytes) != 128) or (len(e_bytes) != 128):
        sock.close()
        return None
    hash = hashes.Hash(hashes.SHA3_512())
    hash.update(nameBytes + N_bytes + e_bytes)
    t = hash.finalize()
    hash1 = hashes.Hash(hashes.SHA3_512())
    hash1.update(t)
    tDash = hash1.finalize()
    tAndtdash = bytes_to_int(t + tDash)
    N = bytes_to_int(N_bytes)
    e = bytes_to_int(e_bytes)
    S = tAndtdash % ttp_key.N
    if database.get(nameBytes.decode('utf-8')) == None:
        key = RSA_key(pubkey=(N, e))
        sig = ttp_key.sign(S)
        database[nameBytes.decode('utf-8')] = key

        newNbytes = int_to_bytes(ttp_key.N, 128)
        if (sig == None):
            sock.close()
            return database
        sentLength = send(sock, newNbytes)
        if sentLength != 128:
            sock.close()
            return database

        sig_bytes = int_to_bytes(sig, 128)
        sentLength = send(sock, sig_bytes)
        if sentLength != 256:
            sock.close()
            return database
        sock.close()
        return database
    else:
        key = database[nameBytes.decode('utf-8')]
        if key.N == N and key.e == e:
            #send(sock,N_bytes)
            sig = ttp_key.sign(S)
            newNbytes = int_to_bytes(ttp_key.N, 128)
            if (sig == None):
                sock.close()
                return database
            sentLength = send(sock, newNbytes)
            if sentLength != 128:
                sock.close()
                return database

            sig_bytes = int_to_bytes(sig, 128)
            sentLength = send(sock, sig_bytes)
            if sentLength != 256:
                sock.close()
                return database
            sock.close()
            return database

        sock.close()
        return None
コード例 #27
0
def hashBytes(a, b):
    concat = b"".join([a, b])
    digest = hashes.Hash(hashes.SHA256(), backend=default_backend())
    digest.update(concat)
    return int.from_bytes(digest.finalize(), 'big')
コード例 #28
0
def client_protocol( ip: str, port: int, dh: DH_params, ttp_key: RSA_key, \
        username: str, pw: str, s: bytes, file_bytes: bytes ) -> \
        Optional[tuple[int,int]]:
    """Generate the shared key and send the file, from the client side.
       IMPORTANT: don't forget to send 'p'!

    PARAMETERS
    ==========
    ip: The IP address to connect to, as a string.
    port: The port to connect to, as an int.
    dh: A DH_params object.
    ttp_key: An RSA_key object.
    username: The username to register, as a string.
    pw: The password, as a string.
    s: The salt, a bytes object 16 bytes long. Must match what the server sends
       back.
    file_bytes: The plaintext to send to the server, as a bytes object.

    RETURNS
    =======
    If successful, return a tuple of the form (a, K_client), where both a and
       K_client are integers. If not, return None.
    """
    try:
        sock = create_socket(ip, port)
        # if sock==None:
        #     return None
        p = 'p'.encode('utf-8')
        send(sock, p)
        usernameUTF = username.encode('utf-8')
        send(sock, int_to_bytes(len(usernameUTF), 1))
        send(sock, usernameUTF)

        serverNameLen1 = receive(sock, 1)
        serverNameLen = bytes_to_int(serverNameLen1)
        serverNameBytes = receive(sock, serverNameLen)
        serverName = serverNameBytes.decode('utf-8')
        servN_bytes = receive(sock, 128)
        serve_bytes = receive(sock, 128)

        servN = bytes_to_int(servN_bytes)
        serve = bytes_to_int(serve_bytes)
        server_key = RSA_key(pubkey=(servN, serve))

        ttpSig_bytes = receive(sock, 128)
        NameNe = serverNameBytes + servN_bytes + serve_bytes
        ttpSign = bytes_to_int(ttpSig_bytes)
        digest = hashes.Hash(hashes.SHA3_512())
        digest.update(NameNe)
        t = digest.finalize()
        digest = hashes.Hash(hashes.SHA3_512())
        digest.update(t)
        tdash = digest.finalize()
        tFinal = bytes_to_int(t + tdash)
        verSig = pow(tFinal, ttp_key.d, ttp_key.N)

        # verify
        if (verSig != ttpSign):
            sock.close()
            return None
        N = dh.N
        g = dh.g
        a = random.randint(0, N - 1)
        A = calc_A(N, g, a)
        encA = server_key.encrypt(A)
        encABytes = int_to_bytes(encA, 128)
        sentLen = send(sock, encABytes)

        salt = receive(sock, 16)

        if salt != s:
            sock.close()
            return None
        B = receive(sock, 64)
        # calc u
        u = calc_u(A, B)

        k = calc_u(N, g)

        # calc x
        x = calc_x(s, pw)

        # calc v
        v = pow(g, x, N)
        # calc K_client
        k_client = calc_K_client(N, B, k, v, a, u, x)
        # calc M1 and send
        M1 = calc_M1(A, B, k_client)
        sentLen = send(sock, M1)
        if sentLen < len(M1):
            sock.close()
            return None

        M2 = receive(sock, 32)
        clientM2 = calc_M2(A, M1, k_client)
        if (M2 == clientM2):
            k_client_bytes = int_to_bytes(k_client, 64)
            aesKey = k_client_bytes[:32]
            hmacKey = k_client_bytes[32:]
            cyphertext = pad_encrypt_then_HMAC(file_bytes, aesKey, hmacKey)
            cypherLen = int_to_bytes(len(cyphertext), 4)
            send(sock, cypherLen)
            send(sock, cyphertext)
            sock.close()
            return (A, k_client)
        sock.close()
        return None
    except:
        return None
コード例 #29
0
def c_openssl_sha256_hexdigest(data):
    digest = hashes.Hash(hashes.SHA256(), backend=c_openssl)
    digest.update(data.encode())
    bin_str = digest.finalize()
    ascii_str = binstr_to_ascii(bin_str)
    return ascii_str
コード例 #30
0
ファイル: signer.py プロジェクト: OstapHybaDataart/pdf_signer
def sign(datau,
         key,
         cert,
         othercerts,
         hashalgo,
         attrs=True,
         signed_value=None,
         hsm=None,
         pss=False,
         timestampurl=None,
         timestampcredentials=None):
    if signed_value is None:
        signed_value = getattr(hashlib, hashalgo)(datau).digest()
    signed_time = datetime.now(tz=util.timezone.utc)

    if hsm is not None:
        keyid, cert = hsm.certificate()
        cert = cert2asn(cert, False)
    else:
        cert = cert2asn(cert)

    certificates = []
    certificates.append(cert)
    for i in range(len(othercerts)):
        certificates.append(cert2asn(othercerts[i]))

    hashalgo = unicode(hashalgo) if sys.version[0] < '3' else hashalgo

    signer = {
        'version':
        'v1',
        'sid':
        cms.SignerIdentifier({
            'issuer_and_serial_number':
            cms.IssuerAndSerialNumber({
                'issuer': cert.issuer,
                'serial_number': cert.serial_number,
            }),
        }),
        'digest_algorithm':
        algos.DigestAlgorithm({'algorithm': hashalgo}),
        'signature':
        signed_value,
    }
    if not pss:
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm(
            {'algorithm': 'rsassa_pkcs1v15'})
    else:
        if isinstance(key, keys.PrivateKeyInfo):
            salt_length = key.byte_size - hashes.SHA512.digest_size - 2
            salt_length = hashes.SHA512.digest_size
        else:
            salt_length = padding.calculate_max_pss_salt_length(
                key, hashes.SHA512)
        signer['signature_algorithm'] = algos.SignedDigestAlgorithm({
            'algorithm':
            'rsassa_pss',
            'parameters':
            algos.RSASSAPSSParams({
                'hash_algorithm':
                algos.DigestAlgorithm({'algorithm': 'sha512'}),
                'mask_gen_algorithm':
                algos.MaskGenAlgorithm({
                    'algorithm':
                    algos.MaskGenAlgorithmId('mgf1'),
                    'parameters': {
                        'algorithm': algos.DigestAlgorithmId('sha512'),
                    }
                }),
                'salt_length':
                algos.Integer(salt_length),
                'trailer_field':
                algos.TrailerField(1)
            })
        })

    if attrs:
        if attrs is True:
            signer['signed_attrs'] = [
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('content_type'),
                    'values': ('data', ),
                }),
                cms.CMSAttribute({
                    'type': cms.CMSAttributeType('message_digest'),
                    'values': (signed_value, ),
                }),
                cms.CMSAttribute({
                    'type':
                    cms.CMSAttributeType('signing_time'),
                    'values':
                    (cms.Time({'utc_time': core.UTCTime(signed_time)}), )
                }),
            ]
        else:
            signer['signed_attrs'] = attrs

    config = {
        'version':
        'v1',
        'digest_algorithms':
        cms.DigestAlgorithms((algos.DigestAlgorithm({'algorithm':
                                                     hashalgo}), )),
        'encap_content_info': {
            'content_type': 'data',
        },
        'certificates':
        certificates,
        # 'crls': [],
        'signer_infos': [
            signer,
        ],
    }
    datas = cms.ContentInfo({
        'content_type': cms.ContentType('signed_data'),
        'content': cms.SignedData(config),
    })
    if attrs:
        tosign = datas['content']['signer_infos'][0]['signed_attrs'].dump()
        tosign = b'\x31' + tosign[1:]
    else:
        tosign = datau
    if hsm is not None:
        signed_value_signature = hsm.sign(keyid, tosign, hashalgo)
    elif isinstance(key, keys.PrivateKeyInfo):
        key = asymmetric.load_private_key(key)
        if pss:
            signed_value_signature = asymmetric.rsa_pss_sign(
                key, tosign, 'sha512')
        else:
            signed_value_signature = asymmetric.rsa_pkcs1v15_sign(
                key, tosign, hashalgo.lower())
    else:
        if pss:
            hasher = hashes.Hash(hashes.SHA512(),
                                 backend=backends.default_backend())
            hasher.update(tosign)
            digest = hasher.finalize()
            signed_value_signature = key.sign(
                digest,
                padding.PSS(mgf=padding.MGF1(hashes.SHA512()),
                            salt_length=salt_length),
                utils.Prehashed(hashes.SHA512()))
        else:
            signed_value_signature = key.sign(
                tosign, padding.PKCS1v15(),
                getattr(hashes, hashalgo.upper())())

    if timestampurl is not None:
        signed_value = getattr(hashlib,
                               hashalgo)(signed_value_signature).digest()
        tspreq = tsp.TimeStampReq({
            "version":
            1,
            "message_imprint":
            tsp.MessageImprint({
                "hash_algorithm":
                algos.DigestAlgorithm({'algorithm': hashalgo}),
                "hashed_message":
                signed_value,
            }),
            #'req_policy', ObjectIdentifier, {'optional': True}),
            "nonce":
            int(time.time() * 1000),
            "cert_req":
            True,
            #'extensions': tsp.Extensions()
        })
        tspreq = tspreq.dump()

        tspheaders = {"Content-Type": "application/timestamp-query"}
        if timestampcredentials is not None:
            username = timestampcredentials.get("username", None)
            password = timestampcredentials.get("password", None)
            if username and password:
                auth_header_value = b64encode(
                    bytes(username + ':' + password, "utf-8")).decode("ascii")
                tspheaders["Authorization"] = f"Basic {auth_header_value}"
        tspresp = requests.post(timestampurl, data=tspreq, headers=tspheaders)
        if tspresp.headers.get('Content-Type',
                               None) == 'application/timestamp-reply':
            tspresp = tsp.TimeStampResp.load(tspresp.content)

            if tspresp['status']['status'].native == 'granted':
                attrs = [
                    cms.CMSAttribute({
                        'type':
                        cms.CMSAttributeType('signature_time_stamp_token'),
                        'values':
                        cms.SetOfContentInfo([
                            cms.ContentInfo({
                                'content_type':
                                cms.ContentType('signed_data'),
                                'content':
                                tspresp["time_stamp_token"]["content"],
                            })
                        ])
                    })
                ]
                datas['content']['signer_infos'][0]['unsigned_attrs'] = attrs

            else:
                raise ValueError("TimeStampResponse status is not granted")

        else:
            raise ValueError("TimeStampResponse has invalid content type")

    # signed_value_signature = core.OctetString(signed_value_signature)
    datas['content']['signer_infos'][0]['signature'] = signed_value_signature

    #open('signed-content-info', 'wb').write(datas.dump())
    # print(datas.dump())
    return datas.dump()