示例#1
0
 def tx_content(self, tx):
     if tx[-256:-192] == self.public_key_hex:
         tx_type = tx[:2]
         logging.debug(f"{tx_type}")
         peer_pub_key = tx[-192:-128]
         try:
             user = self.pub_keys[peer_pub_key]
         except KeyError:
             self.save_key(peer_pub_key)
             user = self.pub_keys[peer_pub_key]
         logging.debug(f"user: {user}")
         if tx_type == "00":
             logging.debug("som v 00")
             dh_peer_key = X25519PublicKey.from_public_bytes(
                 bytes.fromhex(tx[2:66]))
             shared_key = self.dh_private_key.exchange(dh_peer_key)
             derived_key = HKDF(
                 algorithm=SHA256(),
                 length=32,
                 salt=None,
                 info=b'blockchain',
                 backend=backend,
             ).derive(shared_key)
             if user[1] == "no":  #mozno by som nemal prijimat tx pocas syncovania
                 self.send_message("send", cargo=["", peer_pub_key, "00"])
             self.pub_keys[peer_pub_key][1] = derived_key.hex()
             logging.debug("posuvam do edit key files")
             self.edit_key_file(peer_pub_key, derived_key.hex(),
                                2)  #musim kukat aj tx od seba ktore nemam
         elif tx_type == "01":
             nonce = bytes.fromhex(tx[2:34])
             msg_size = int(tx[34:38], 16) * 2
             msg = bytes.fromhex(tx[38:msg_size + 38])
             if user[1] == "no" or user[1] == "sent":
                 if user[0] == "__unknown" and user[1] == "no":
                     self.del_pub_key(peer_pub_key)
                     del self.pub_keys[peer_pub_key]
                 print("sifrovana sprava ale neprebehla vymena klucov")
                 return False
             encryption_key = bytes.fromhex(user[1])
             algorithm = ChaCha20(encryption_key, nonce)
             cipher = Cipher(algorithm, mode=None, backend=backend)
             decryptor = cipher.decryptor()
             msg = decryptor.update(msg)
             msg = msg.decode("utf-8")
             print(f"e {user[0]}: {msg}")
         elif tx_type == "02":
             msg_size = int(tx[2:6], 16) * 2
             msg = bytes.fromhex(tx[6:msg_size + 6]).decode("utf-8")
             print(f"{user[0]}: {msg}")
示例#2
0
class ECDH:
    def __init__(self):
        #default curve is secp256r1
        self.ecc_curve = NIST256p
        self.prv_key = SigningKey.generate(curve=self.ecc_curve)
        self.pub_key = self.prv_key.get_verifying_key()
        logging.info('N2 public key:')
        logging.info(self.pub_key.to_string())
        logging.info("N2 public key size: ")
        logging.info(len(self.pub_key.to_string()))
        self.private_key = load_pem_private_key(self.prv_key.to_pem(),
                                                password=None,
                                                backend=default_backend())
        self.public_key = load_pem_public_key(self.pub_key.to_pem(),
                                              backend=default_backend())
        self.derived_key = None

    def encrypt(self, public_key, salt):
        logging.info('N1 public key')
        logging.info(public_key)
        pk = load_pem_public_key(VerifyingKey.from_string(
            public_key, curve=self.ecc_curve).to_pem(),
                                 backend=default_backend())
        shared_key = self.private_key.exchange(ec.ECDH(), pk)
        logging.info('Shared Key:')
        logging.info(shared_key.hex())
        logging.info('Salt:')
        logging.info(salt.hex())
        self.derived_key = HKDF(algorithm=hashes.SHA256(),
                                length=16,
                                salt=salt,
                                info=None,
                                backend=default_backend()).derive(shared_key)
        logging.info('Symmetric Key:')
        logging.info(self.derived_key.hex())
示例#3
0
def keyGenerate():
    global count
    count += 1
    private_key = Ed25519PrivateKey.generate()
    private_bytes = private_key.private_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PrivateFormat.Raw,
        encryption_algorithm=serialization.NoEncryption())
    public_key = private_key.public_key()
    public_bytes = public_key.public_bytes(
        encoding=serialization.Encoding.Raw,
        format=serialization.PublicFormat.Raw)
    tmpnid = hashlib.sha256()
    tmpnid.update(public_bytes)
    nid = HKDF(algorithm=hashes.SHA256(), length=16, salt=None,
               info=None).derive(tmpnid.digest())
    print("私钥" + str(count), private_bytes, len(private_bytes))
    print("公钥" + str(count), public_bytes, len(public_bytes))
    print("nid", nid.hex())
    return private_key, private_bytes, public_key, public_bytes, nid.hex()
示例#4
0
def x25519_key_derive(private, peer):
    peer_public = X25519PublicKey.from_public_bytes(
        bytes.fromhex(peer.strip()))
    shared = private.exchange(peer_public)
    derived_key = HKDF(
        algorithm=hashes.SHA256(),
        length=32,
        salt=b'',
        info=b'exchange',
        backend=default_backend()
    ).derive(shared)
    return derived_key.hex().strip()
示例#5
0
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print("Shared Secret between Alice and Bob : ")
print("------------------------------------------------")
print("\t - Shared Key compute by Alice : ", Alice_Shared_Key.hex())
print("\t - Shared Key compute by Bob   : ", Bob_Shared_Key.hex())

# Perform key derivation with Alice_Shared_Key.
Alice_Derived_Key = HKDF(
    algorithm=hashes.SHA256(),
    length=32,
    salt=None,
    info=b'handshake data',
    backend=default_backend(),
).derive(Alice_Shared_Key)

# Perform key derivation with Bob_Shared_Key.
Bob_Derived_Key = HKDF(
    algorithm=hashes.SHA256(),
    length=32,
    salt=None,
    info=b'handshake data',
    backend=default_backend(),
).derive(Bob_Shared_Key)

# Display Key Derivation
print("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%")
print("Key Derivation of Alice and Bob : ")
print("------------------------------------------------")
print("\t - Key Derivation with Alice_Shared_Key : ", Alice_Derived_Key.hex())
print("\t - Key Derivation with Bob_Shared_Key   : ", Bob_Derived_Key.hex())
示例#6
0
    #    devices = scanner.scan(10.0)
    #
    #    for dev in devices:
    #        print("Device %s (%s), RSSI=%d dB" % (dev.addr, dev.addrType, dev.rssi))
    #        for (adtype, desc, value) in dev.getScanData():
    #            print("  %s = %s" % (desc, value))

    private_key = ec.generate_private_key(ec.SECP256R1(), default_backend())
    public_key = private_key.public_key()
    shared_key = private_key.exchange(ec.ECDH(), public_key)
    print(" shared key :", shared_key.hex())
    derived_key = HKDF(algorithm=hashes.SHA256(),
                       length=64,
                       salt=None,
                       info=b'mible-setup-info',
                       backend=default_backend()).derive(shared_key)
    print("derived key :", derived_key.hex())
    token = derived_key[0:12]
    bind_key = derived_key[12:28]
    A = derived_key[28:44]
    print("      token :", token.hex())
    print("   bind_key :", bind_key.hex())
    print("          A :", A.hex())

    aesccm = AESCCM(A)
    nonce = bytearray([16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27])
    did = "blt.3.129vl4ap05o01".encode()
    aad = "devID".encode()
    did_ct = aesccm.encrypt(nonce, did, aad)
    print("    AES did :", did_ct.hex())
示例#7
0
 def tx_content(self, tx):
     sender = False
     if tx[-192:-128] == self.public_key_hex:
         sender = True
     if tx[-256:-192] == self.public_key_hex or sender:
         tx_type = tx[:2]
         logging.debug(f"{tx_type}")
         if sender:
             peer_pub_key = tx[-256:-192]
         else:
             peer_pub_key = tx[-192:-128]
         timestamp = int(tx[-264:-256], 16)
         try:
             user = self.pub_keys[peer_pub_key]
         except KeyError:
             self.save_key(peer_pub_key)
             user = self.pub_keys[peer_pub_key]
             self.c_m.execute(f"""CREATE TABLE '{peer_pub_key}' (
                 timestamp INTEGER,
                 message TEXT,
                 sender INTEGER,
                 encryption INTEGER)
                 """)
             init_msg = "Komunikácia bola zahájená druhou stranou, ešte nemôžeš posielať šifrované správy"
             self.c_m.execute(
                 f"INSERT INTO '{peer_pub_key}' VALUES (?,?,?,?);",
                 (int(time()), init_msg, 3, 1))
             self.conn_m.commit()
         logging.debug(f"user: {user}")
         if tx_type == "00":
             if sender:
                 if user[1] == "no":
                     user[1] = "sent"
                 return
             logging.debug("som v 00")
             dh_peer_key = X25519PublicKey.from_public_bytes(
                 bytes.fromhex(tx[2:66]))
             shared_key = self.dh_private_key.exchange(dh_peer_key)
             derived_key = HKDF(
                 algorithm=SHA256(),
                 length=32,
                 salt=None,
                 info=b'blockchain',
                 backend=backend,
             ).derive(shared_key)
             if user[1] == "no":  #mozno by som nemal prijimat tx pocas syncovania
                 self.send_message("send", cargo=["", peer_pub_key, "00"])
             self.pub_keys[peer_pub_key][1] = derived_key.hex()
             logging.debug("posuvam do edit key files")
             self.edit_key_file(peer_pub_key, derived_key.hex(),
                                2)  #musim kukat aj tx od seba ktore nemam
             exchange_msg = "Výmena kľúčov prebehla úspešne odteraz môžeš správy posielať šifrované"
             self.c_m.execute(
                 f"INSERT INTO '{peer_pub_key}' VALUES (?,?,?,?);",
                 (timestamp, exchange_msg, 3, 1))
             self.conn_m.commit()
             self.ui_in.put([
                 "new", [timestamp, exchange_msg, "Info", 1, peer_pub_key]
             ])
             return
         elif tx_type == "01":
             nonce = bytes.fromhex(tx[2:34])
             msg_size = int(tx[34:38], 16) * 2
             msg = bytes.fromhex(tx[38:msg_size + 38])
             if user[1] == "no" or user[1] == "sent":
                 if user[0] == "__unknown" and user[
                         1] == "no" and not sender:
                     self.del_pub_key(peer_pub_key)
                     del self.pub_keys[peer_pub_key]
                 print("sifrovana sprava ale neprebehla vymena klucov")
                 return False
             encryption_key = bytes.fromhex(user[1])
             algorithm = ChaCha20(encryption_key, nonce)
             cipher = Cipher(algorithm, mode=None, backend=backend)
             decryptor = cipher.decryptor()
             msg = decryptor.update(msg)
             msg = msg.decode("utf-8")
             print(f"{user[0]}: {msg}")
         elif tx_type == "02":
             msg_size = int(tx[2:6], 16) * 2
             msg = bytes.fromhex(tx[6:msg_size + 6]).decode("utf-8")
             print(f"{user[0]}: {msg}")
         msg_sender = 0
         name = user[0]
         if sender:
             msg_sender = 1
             name = "Me"
         self.c_m.execute(
             f"INSERT INTO '{peer_pub_key}' VALUES (?,?,?,?);",
             (timestamp, msg, msg_sender, int(not int(tx_type) - 1)))
         self.conn_m.commit()
         self.ui_in.put([
             "new",
             [timestamp, msg, user[0], not int(tx_type) - 1, peer_pub_key]
         ])
def checkNidPublickey(nid, public_key_bytes):
    calcnid = HKDF(algorithm=hashes.SHA256(), length=16, salt=None,
                   info=None).derive(public_key_bytes)
    return nid == calcnid.hex()