def sign_binary(private_key, message_binary):
    type(message_binary)
    signature = private_key.sign(
        message_binary,
        padding.PSS(mgf=padding.MGF1(hashes.SHA3_256()),
                    salt_length=padding.PSS.MAX_LENGTH), hashes.SHA3_256())
    return signature
def verify_binary(public_key, signature, message_binary):
    try:
        verify = public_key.verify(
            signature, message_binary,
            padding.PSS(mgf=padding.MGF1(hashes.SHA3_256()),
                        salt_length=padding.PSS.MAX_LENGTH), hashes.SHA3_256())
    except InvalidSignature:
        return False
    return True
示例#3
0
def _generate_signature(msg):
    with open(KEY_PATH + 'key.pem', 'rb') as private_key_file:
        private_key = serialization.load_pem_private_key(
            private_key_file.read(), password=None, backend=default_backend())
        return base64.urlsafe_b64encode(
            private_key.sign(
                msg.encode('utf8'),
                padding.PSS(mgf=padding.MGF1(hashes.SHA3_256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA3_256())).decode()
示例#4
0
文件: crypto.py 项目: bee344/THESIS
def verify_binary(public_key, signature, message_in_binary):
    try:
        verify = public_key.verify(
            signature,
            message_in_binary,
            padding.PSS(
                mgf=padding.MGF1(hashes.SHA3_256()),
                salt_length=padding.PSS.MAX_LENGTH
            ),
            hashes.SHA3_256()
        )
def login():
    fileChoice = passwordFileSelection()
    fileName = open(fileChoice, "r")
    print("Enter your login credentials below: \n")
    username = input("Username: "******"Password: "******"Username found in file: " + fileChoice)

            if fileChoice == "plaintextpsswrd.txt":
                userPassword = line.split(" ", 1)[1]
                passwordwithNewLine = password + '\n'
                if userPassword == passwordwithNewLine:
                    print("Successful Login")
                else:
                    print("Failed Login")
                return
            elif fileChoice == "hashedpsswrd.txt":
                passwordasBytes = password.encode("ascii")
                digest = hashes.Hash(hashes.SHA3_256(),
                                     backend=openssl.backend)
                digest.update(passwordasBytes)
                hashedpsswrd = digest.finalize()
                hashedpsswrd = hashedpsswrd.hex()
                userPassword = line.split(" ", 1)[1]
                passwordwithNewLine = hashedpsswrd + '\n'
                if userPassword == passwordwithNewLine:
                    print("Successful Login")
                else:
                    print("Failed Login")
                return
            elif fileChoice == "salthashedpsswrd.txt":
                userSalt = line.split(" ", 2)[2]
                saltwithNewLine = userSalt + '\n'
                saltyPassword = password + saltwithNewLine
                saltypasswordasBytes = saltyPassword.encode("ascii")
                digest = hashes.Hash(hashes.SHA3_256(),
                                     backend=openssl.backend)
                digest.update(saltypasswordasBytes)
                salthashedpsswrd = digest.finalize()
                salthashedpsswrd = salthashedpsswrd.hex()
                userPassword = line.split(" ", 2)[1]
                if userPassword == userPassword:
                    print("Successful Login")
                else:
                    print("Failed Login")

        else:
            print("Username does not exist in this file")
示例#6
0
def communicate():
    peer_publickey_encoded = input("Please enter your identity key: ")
    if (not (peer_publickey_encoded in friends
             or peer_publickey_encoded in best_friends)):
        print("I do not know you.")
        exit(-1)
    peer_publickey = get_peer_publickey(peer_publickey_encoded)
    if (not peer_publickey):
        print("Bad key")
        exit(-1)

    # Do key agreement
    # Authenticate the peer with the identity keys to prevent Man-in-the-middle
    sharedkey_static = private_key.exchange(peer_publickey)
    # Lets also do an ephemeral key agreement for added forward secrecy
    ephemeralkey_bytes = urandom(32)
    ephemeralkey = x25519.X25519PrivateKey.from_private_bytes(
        ephemeralkey_bytes)
    ephemeral_publickey_encoded = encode_publickey(ephemeralkey)
    print("My ephemeral key is {}.".format(ephemeral_publickey_encoded))
    peer_ephemeralkey_encoded = input("What is yours? ")
    peer_ephemeralkey = get_peer_publickey(peer_ephemeralkey_encoded)
    if (not peer_ephemeralkey):
        print("Bad key")
        exit(-1)
    sharedkey_ephemeral = ephemeralkey.exchange(peer_ephemeralkey)
    digest = hashes.Hash(hashes.SHA3_256(), backend=default_backend())
    digest.update(sharedkey_static)
    digest.update(sharedkey_ephemeral)
    sharedkey = digest.finalize()

    # Do a challenge/response authentication with the peer
    challenge = urandom(16)
    print(
        "Proof that you really know your private keys. Here is your challenge: {}"
        .format(b64encode(challenge).decode("ascii")))
    response = input("What is your response? ")
    mac = hmac.HMAC(sharedkey, hashes.SHA3_256(), backend=default_backend())
    mac.update(challenge)
    expected_response = b64encode(mac.finalize()).decode("ascii")
    if (response != expected_response):
        print("This is not the response I was looking for")
        exit(-1)

    # We are really talking to a friend
    if (peer_publickey_encoded in best_friends):
        print("Hello BFF. Here is your flag: {}".format(FLAG))
        exit(0)
    else:
        print("Well done, friend. Now sod off.")
示例#7
0
def test_derive_key_hkdf_return_exactly_the_same_key_than_hkdf_derivation_if_same_input(
):
    # Given
    algorithm = hashes.SHA3_256()
    length = 32
    salt = b''
    info = b"test"
    key_to_derive = b"01234567890123456789012346789012345678912345678"

    expected_result = HKDF(
        algorithm=algorithm,
        length=length,
        salt=salt,
        info=info,
    ).derive(key_to_derive)

    # When
    result = derive_key_hkdf(key=key_to_derive,
                             length=length,
                             salt=salt,
                             info=info,
                             algorithm=algorithm)

    # Then
    assert result == expected_result
示例#8
0
def to_public_key_checksum(public_key):
    """
    Convert a public key to a checksum key. This will first make all a-f chars lower case
    then convert a-f chars to uppercase depending on the hash of the public key.

    :params str public_key: Key to convert to a checksum key.

    :returns: Checksum key of the public_key.

    """
    digest = hashes.Hash(hashes.SHA3_256(), backend=backend)
    digest.update(to_bytes(hexstr=public_key))
    public_key_hash = remove_0x_prefix(to_hex(digest.finalize()))
    public_key_clean = remove_0x_prefix(public_key.lower())
    checksum = ''
    hash_index = 0
    for value in public_key_clean:
        if int(public_key_hash[hash_index], 16) > 7:
            checksum += value.upper()
        else:
            checksum += value
        hash_index += 1
        if hash_index >= len(public_key_hash):
            hash_index = 0
    return add_0x_prefix(checksum)
示例#9
0
def pad_encrypt_then_HMAC(plaintext: bytes, key_cypher: bytes,
                          key_HMAC: bytes) -> bytes:
    """Encrypt a plaintext with AES-256. Note the order of operations!
    
    PARAMETERS
    ==========
    plaintext: The bytes object to be encrypted.
    key_cypher: The bytes object used as a key to encrypt the plaintext.
    key_HMAC: The bytes object used as a key for the keyed-hash MAC.

    RETURNS
    =======
    The cyphertext, as a bytes object.
    """

    assert type(plaintext) is bytes
    assert type(key_cypher) is bytes
    assert len(key_cypher) == 32
    assert type(key_HMAC) is bytes
    #pad message to 128, generate random IV 16 bytes, encrypt with AES-256 in CBC mode, IV
    padded_plaintext = pad_message_128(plaintext)
    iv = os.urandom(16)
    cipher = Cipher(algorithms.AES(key_cypher), modes.CBC(iv))
    encryptor = cipher.encryptor()
    ct = encryptor.update(padded_plaintext) + encryptor.finalize()
    h = hmac.HMAC(key_HMAC, hashes.SHA3_256())
    h.update(iv + ct)
    hmac_hash = h.finalize()
    return iv + ct + hmac_hash
示例#10
0
def verify_signature(msg):
    split_msg = msg.split('(╯°□°)╯︵ ┻━┻')
    message = split_msg[0]
    signature = base64.urlsafe_b64decode(split_msg[1].encode())
    with open(KEY_PATH + 'key.pub', 'rb') as public_key_file:
        public_key = serialization.load_pem_public_key(
            public_key_file.read(), backend=default_backend())
        try:
            public_key.verify(
                signature, message.encode(),
                padding.PSS(mgf=padding.MGF1(hashes.SHA3_256()),
                            salt_length=padding.PSS.MAX_LENGTH),
                hashes.SHA3_256())
            return True
        except InvalidSignature:
            return False
def pad_encrypt_then_HMAC(plaintext: bytes, key_cypher: bytes,
                          key_HMAC: bytes) -> bytes:
    """Encrypt a plaintext with AES-256. Note the order of operations!
    
    PARAMETERS
    ==========
    plaintext: The bytes object to be encrypted.
    key_cypher: The bytes object used as a key to encrypt the plaintext.
    key_HMAC: The bytes object used as a key for the keyed-hash MAC.

    RETURNS
    =======
    The cyphertext, as a bytes object.
    """

    assert type(plaintext) is bytes
    assert type(key_cypher) is bytes
    assert len(key_cypher) == 32
    assert type(key_HMAC) is bytes

    pad_ob = padding.PKCS7(128).padder()
    msg_pad = pad_ob.update(plaintext)
    msg_pad += pad_ob.finalize()

    iv = os.urandom(16)
    encrypt = Cipher(algorithms.AES(bytes(key_cypher)), modes.CBC(bytes(iv)),
                     default_backend()).encryptor()
    encrypted_text = encrypt.update(msg_pad) + encrypt.finalize()

    hash = hmac.HMAC(key_HMAC, hashes.SHA3_256())
    hash.update(iv + encrypted_text)
    hash = hash.finalize()
    print(len(hash))
    return iv + encrypted_text + hash
示例#12
0
def my_hash(algorithm):
    hashes.Hash(algorithm)  # OK
    hashes.MD5()  # Noncompliant
    hashes.SHA1()  # Noncompliant
    hashes.SHA256()
    hashes.SHA3_256()
    foo(hashes)  #coverage
    def write_encrypted(self, passcode, filename):
        """Write encrypted credential to a file."""

        # Encode the passcode and generate set the 'salt.'
        passcode = passcode.encode()
        salt = b'Rm\x95\xaf\xe9p`=\xbe\xf3\xb3\xa1\xef\x112\xf5'

        # Create the key definition object using the 'salt.'
        key_def = PBKDF2HMAC(algorithm=hashes.SHA3_256(),
                             length=32,
                             salt=salt,
                             iterations=100000,
                             backend=default_backend())

        # Derive the encryption key by combining the key definition with the passcode.
        key = base64.urlsafe_b64encode(key_def.derive(passcode))

        # Construct the encryptor using the key.
        encryptor = Fernet(key)

        message = [
            encryptor.encrypt(self.batch_account_name.encode()),
            encryptor.encrypt(self.batch_account_key.encode()),
            encryptor.encrypt(self.batch_account_url.encode()),
            encryptor.encrypt(self.storage_account_name.encode()),
            encryptor.encrypt(self.storage_account_key.encode())
        ]

        with open(filename, "wb") as f:
            pickle.dump(message, f)
示例#14
0
文件: utils.py 项目: Alvarios/Hermes
def derive_key_hkdf(
    key: bytes,
    length: Optional[int] = 32,
    salt: Optional[Union[None, bytes]] = None,
    info: Optional[Union[None, bytes]] = None,
    algorithm=hashes.SHA3_256()
) -> bytes:
    """Return a derived key from the inputs of a given length using HKDF algorithm.

    :param key: The key to derive.
    :param length: The length of the output.
    :param salt:  A salt. Randomizes the KDF’s output. Optional, but highly recommended. Ideally as many bits of entropy
     as the security level of the hash: often that means cryptographically random and as long as the hash output.
     Worse (shorter, less entropy) salt values can still meaningfully contribute to security. May be reused.
     Does not have to be secret, but may cause stronger security guarantees if secret; see RFC 5869 and the HKDF paper
     for more details. If None is explicitly passed a default salt of algorithm.digest_size // 8 null bytes will
     be used.
    :param info: Application specific context information. If None is explicitly passed an empty byte string
    will be used.
    :param algorithm: An instance of HashAlgorithm.

    :return: A derived key of given length as bytes.
    """
    return HKDF(
        algorithm=algorithm,
        length=length,
        salt=salt,
        info=info,
    ).derive(key)
示例#15
0
 def generate_csr(private_key, name: X509Name,
                  subject: X509SubjectAlternativeName):
     return x509.CertificateSigningRequestBuilder().subject_name(x509.Name(name.collect())) \
         .add_extension(x509.SubjectAlternativeName(subject.collect()), critical=False) \
         .sign(private_key,
               hashes.SHA3_256(),
               default_backend())
class TestSHA3256(object):
    test_sha3_256 = generate_hash_test(
        load_hash_vectors,
        os.path.join("hashes", "SHA3"),
        ["SHA3_256LongMsg.rsp", "SHA3_256ShortMsg.rsp"],
        hashes.SHA3_256(),
    )
示例#17
0
 def check_password(self, password):
     digest = hashes.Hash(hashes.SHA3_256(), backend=default_backend())
     digest.update(bytes(bytearray(password, 'utf-8')))
     hashValue = digest.finalize()
     if hashValue == self.password_hash:
         return True
     else:
         return False
示例#18
0
def generate_sha3_256(key, nonce_or_iv):
    digest = hashes.Hash(hashes.SHA3_256(), backend=default_backend())

    def do_computation(msg: bytes):
        digest.update(msg)
        # digest.finalize()

    return do_computation
示例#19
0
 def get_algorithm(self):
     if self.bits == 224:
         return hashes.SHA3_224()
     elif self.bits == 256:
         return hashes.SHA3_256()
     elif self.bits == 384:
         return hashes.SHA3_384()
     elif self.bits == 521:
         return hashes.SHA3_512()
示例#20
0
 def passwordEncrypt(hashedString):
     passwordasBytes = hashedString.encode("ascii")
     digest = hashes.Hash(hashes.SHA3_256(),
                          backend=openssl.backend)
     digest.update(passwordasBytes)
     hashedpsswrd = digest.finalize()
     hashedpsswrd = hashedpsswrd.hex()
     hashpasswordwithNewLine = hashedpsswrd + '\n'
     return hashpasswordwithNewLine
示例#21
0
 def passwordEncrypt(hashedString):
     saltypasswordasBytes = hashedString.encode("ascii")
     digest = hashes.Hash(hashes.SHA3_256(),
                          backend=openssl.backend)
     digest.update(saltypasswordasBytes)
     salthashedpsswrd = digest.finalize()
     salthashedpsswrd = salthashedpsswrd.hex()
     saltpasswordwithNewLine = salthashedpsswrd
     return saltpasswordwithNewLine
示例#22
0
def KeyFromPassword(password: str, salt: bytes):
    # Expand Key
    provider = PBKDF2HMAC(algorithm=hashes.SHA3_256(),
                          length=32,
                          salt=salt,
                          iterations=1000000,
                          backend=default_backend())

    return provider.derive(password.encode())
示例#23
0
    def _GetLongHash(self, fileObj):
        digest = hashes.Hash(hashes.SHA3_256(), backend=default_backend())

        fileObj.seek(0)
        for chunk in self._ChunksOf(fileObj):
            digest.update(chunk)
        fileObj.seek(0)

        return digest.finalize()
示例#24
0
 def test_unsupported_hash_algorithm(self, backend):
     # ConcatKDF requires a hash algorithm with an internal block size.
     with pytest.raises(TypeError):
         ConcatKDFHMAC(
             hashes.SHA3_256(),
             16,
             salt=None,
             otherinfo=None,
             backend=backend,
         )
示例#25
0
def start_hmac(key,who):
    global CSUIT
    alg,modo,dige = CSUIT[who].split("_")
    if(dige == "SHA256"):
        digest = hashes.SHA256()
    elif(dige == "SHA512"):
        digest = hashes.SHA512()
    elif(dige == "SHA3256"):
        digest = hashes.SHA3_256()
    elif(dige == "SHA3512"):
        digest = hashes.SHA3_512()
    return hmac.HMAC(key, digest, backend=default_backend())
示例#26
0
def get_encryption_key(user):
    password_provided = user.password['user_password']
    password = password_provided.encode()
    login = user.login['user_login']
    salt = b'salt_'  # Placeholder value - use a key from os.urandom(16), always use the same key, must be of type bytes
    kdf = PBKDF2HMAC(algorithm=hashes.SHA3_256(),
                     length=32,
                     salt=salt,
                     iterations=250000,
                     backend=default_backend())
    key = base64.urlsafe_b64encode(kdf.derive(password))
    return key
示例#27
0
def sha3(data: bytes) -> bytes:
    """
    Raises:
        RuntimeError: If Keccak lib initialization failed, or if the function
        failed to compute the hash.

        TypeError: This function does not accept unicode objects, they must be
        encoded prior to usage.
    """
    digest = hashes.Hash(hashes.SHA3_256())
    digest.update(data)
    return digest.finalize()
示例#28
0
def get_hashing_algorithm():
    print('Odaberite algoritam za RSA enkripciju: a) SHA-2\tb) SHA-3')
    alg = input('[a/b]? : ')
    if alg == 'a':
        print('Odaberite veličinu za SHA-2: a) SHA-256\tb) SHA-512')
        size = input('[a/b]? : ')
        hashing_algorithm = hashes.SHA256() if size == 'a' else hashes.SHA512()
    else:
        print('Odaberite veličinu za SHA-3: a) SHA3-256\tb) SHA3-512')
        size = input('[a/b]? : ')
        hashing_algorithm = hashes.SHA3_256(
        ) if size == 'a' else hashes.SHA3_512()
    return hashing_algorithm
示例#29
0
def digest_data(data):
    """
    Compute the hash of the passed data

    :param bytes data: Data to be hashed
    :return str: Hex of data digest
    """
    data_hash = hashes.Hash(hashes.SHA3_256())
    data_hash.update(data)

    return data_hash\
        .finalize()\
        .hex()
示例#30
0
def hash_bytes(input):
    """Hash the given input using SHA-2 224.

   PARAMETERS
   ==========
   input: A bytes object containing the value to be hashed.

   RETURNS
   =======
   A bytes object containing the hash value.
   """
    myhash = hashes.Hash(hashes.SHA3_256())
    myhash.update(input)
    hashed_output = myhash.finalize()
    return hashed_output