Exemple #1
0
def test_vectors():
    print "Testing the Hash MD2 algorithm first..."
    print "Test vectors running..."

    string1 = "The quick brown fox jumps over the lazy dog"
    string2 = "The quick brown fox jumps over the lazy cog"
    string3 = ""
    string4 = "a"
    string5 = "abc"
    string6 = "message digest"
    string7 = "abcdefghijklmnopqrstuvwxyz"
    string8 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
    string9 = "12345678901234567890123456789012345678901234567890123456789012345678901234567890"
    
    md2_hash_value_1 = MD2.new(string1).hexdigest()
    md2_hash_value_2 = MD2.new(string2).hexdigest()
    md2_hash_value_3 = MD2.new(string3).hexdigest()
    md2_hash_value_4 = MD2.new(string4).hexdigest()
    md2_hash_value_5 = MD2.new(string5).hexdigest()
    md2_hash_value_6 = MD2.new(string6).hexdigest()
    md2_hash_value_7 = MD2.new(string7).hexdigest()
    md2_hash_value_8 = MD2.new(string8).hexdigest()
    md2_hash_value_9 = MD2.new(string9).hexdigest()
    
    print md2_hash_value_1
    print md2_hash_value_2
    print md2_hash_value_3
    print md2_hash_value_4
    print md2_hash_value_5
    print md2_hash_value_6
    print md2_hash_value_7
    print md2_hash_value_8
    print md2_hash_value_9
Exemple #2
0
def calculate_hamming(x1):
    pos = random.randint(0,127)
    
    mask = 1 << pos
    x2 = x1 ^ mask

    m1 = BitArray(uint=x1, length=128)
    m2 = BitArray(uint=x2, length=128)

    hash_of_m1 = MD2.new(str(m1))

    md2_hash_value_1 = MD2.new(str(m1)).hexdigest()
    md2_hash_value_2 = MD2.new(str(m2)).hexdigest()

    hamming_result = (distance.hamming(md2_hash_value_1, md2_hash_value_2)+2) << 1
    return hamming_result
Exemple #3
0
    def login(self, user, pswd):
        """
        Login to server


        :param user: user name
        :type user: str
        :param pswd: password
        :type pswd: str
        :return: first byte of access right bit mask 1 - enabled 0 - disabled
        :rtype: int
        :raise LoginFailed: if login or passsword incorrect
        :raise UnknownData: if data field is missing
        """
        salt = self._get_login_info()
        h = MD2.new()
        h.update(pswd.encode())
        h.update(salt)
        hd = h.digest()
        data = user.encode() + b'\x00' * (32 - len(user.encode())) + hd
        result = self.send_command('login_try', data=data)
        try:
            if result['data']:
                return int(result['data'][0])
            else:
                raise LoginFailed('Login failed. Login or password incorrect')
        except KeyError:
            raise UnknownData('Unknown Error. Data field is missing', result)
Exemple #4
0
def test(nb_chunks, chunk_size):
    h = MD2.new()
    f = open("test.txt", "rb")
    for i in range(nb_chunks):
        h.update(f.read(chunk_size))
    f.close()
    d = h.hexdigest()
    def check_signature(self, cacert):
        """Verifies that the certificate is signed by cacert.

        Args:
        cacert: Certificate object which is suspected to be the parent
        of this one in the trust chain.

        Returns:
        True if this certificate was signed by cacert, false
        otherwise.
        """

        cakey = cacert.get_pub_key()
        cahash = None

        if self._algo == _OID_RSA_SHA1:
            cahash = SHA.new(self._certdata)
        elif self._algo == _OID_RSA_MD4:
            cahash = MD4.new(self._certdata)
        elif self._algo == _OID_RSA_MD2:
            cahash = MD2.new(self._certdata)
        elif self._algo == _OID_RSA_MD5:
            cahash = MD5.new(self._certdata)
        elif self._algo == _OID_RSA_SHA256:
            cahash = SHA256.new(self._certdata)
        else:
            raise X509SignatureAlgorithmUnsupported(
                "No algorithm known for " + self._algo)

        verifier = PKCS1_v1_5.new(cakey)
        return verifier.verify(cahash, self._signature)
def encipher():
    # print('start encipher()')
    # creation 256 bit session key
    try:
        bpassphrase = passphrase.encode('utf-8')
        sessionkey = MD2.new(bpassphrase).digest() + Random.new().read(16)
        # print('passphrase')
    except:
        sessionkey = Random.new().read(32)  # 256 bit
        # print('random')
    # encryption AES of the message
    f = open('data/users8.json', 'rb')
    bplaintext = f.read()
    f.close()
    obj = AES.new(sessionkey, AES.MODE_ECB)
    ciphertext = obj.encrypt(pad(bplaintext, BLOCK_SIZE))
    f = open('data/users8.json', 'wb')
    f.write(ciphertext)
    f.close()
    # encryption RSA of the session key
    publickey = RSA.importKey(open('publickey.txt', 'rb').read())
    cipherrsa = PKCS1_OAEP.new(publickey)
    sessionkey = cipherrsa.encrypt(sessionkey)
    f = open('sessionkey8.txt', 'wb')
    f.write(bytes(sessionkey))
    f.close()
 def get_md2(self):
     hash_obj = MD2.new()
     hash_obj.update(self.value)
     return {
         "digest": hash_obj.digest(),
         "hexdigets": hash_obj.hexdigest(),
         "warning": "WARNING: Insecure."
     }
Exemple #8
0
def doCrack(address, username, password):
    hash_str = getPath(address)
    m = MD2.new()
    m.update(password)
    encrypt_str = m.hexdigest()
    if encrypt_str.lower() == hash_str.lower():
        return True, 'Crack success!'
    else:
        return False, 'Crack fail!'
Exemple #9
0
def decrypt(filename):
    key = input("Enter secret phrase: ")
    f = open(filename, 'rb')
    tempkey = MD2.new(data=key.encode()).digest()
    cipher = ARC4.new(tempkey)
    plaintext = cipher.decrypt(f.read())
    f.close()
    f = open(filename, 'wb')
    f.write(plaintext)
Exemple #10
0
    def md2(self):
        """Get MD2 hash
        
        The MD2 (Message-Digest 2) algorithm is a cryptographic hash function developed by 
        Ronald Rivest in 1989. The algorithm is optimized for 8-bit computers.Although MD2 is 
        no longer considered secure, even as of 2014, it remains in use in public key 
        infrastructures as part of certificates generated with MD2 and RSA.

        Returns:
            Chepy: The Chepy object. 
        """
        h = MD2.new()
        h.update(self._convert_to_bytes())
        self.state = h.hexdigest()
        return self
Exemple #11
0
def hash(text):

    bin_text = bytes(text, "ascii")

    sha1 = hashlib.sha1(bin_text)
    first = sha1.digest()

    md2 = MD2.new()
    md2.update(first)
    second = md2.digest()

    md5 = hashlib.md5()
    md5.update(second)

    return md5.hexdigest()
Exemple #12
0
def bf(h, dictionary):

    f = open(dictionary, 'r')
    lines = f.readlines()
    print('\033[1;34m[*]\033[0m Starting Brute Force - hash = ' + h)
    for i in lines:

        md2hasher = MD2.new()
        md2hasher.update(i[:-1])
        h2 = md2hasher.hexdigest()

        if h == h2:

            print('\033[1;32m[+]\033[0m Hash Cracked! - Password = ' + i)
            exit()
Exemple #13
0
def md_sha_hash(flag, text):
    hash_text = None
    if flag == 'MD2':
        h = MD2.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'MD4':
        h = MD4.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'MD5':
        h = MD5.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA1':
        h = SHA1.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA224':
        h = SHA224.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA256':
        h = SHA256.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA384':
        h = SHA384.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'SHA512':
        h = SHA512.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'RIPEMD':
        h = RIPEMD.new()
        h.update(text)
        hash_text = h.hexdigest()
    elif flag == 'RIPEMD160':
        h = RIPEMD160.new()
        h.update(text)
        hash_text = h.hexdigest()
    else:
        return {'error': False, 'msg': u'未知hash算法!'}
    return {'error': True, 'msg': hash_text}
Exemple #14
0
def hash(combo):

    first_pass = hashlib.sha1()

    first_pass.update(b'combo')

    sha1_hashed = first_pass.digest()

    second_pass = MD2.new()

    second_pass.update(sha1_hashed)

    md2_hashed = second_pass.digest()

    third_pass = hashlib.md5()

    third_pass.update(md2_hashed)

    return third_pass.hexdigest()
def populate_copy_as_menu(menu, obj, action_table):
	string_menu = menu.addMenu("Escaped string")
	action_table[string_menu.addAction("ASCII")] = lambda : obj.copy_as(lambda data : data.encode("string_escape").replace("\"", "\\\""), False)
	action_table[string_menu.addAction("UTF-8 URL")] = lambda : obj.copy_as(encode_url, False)
	action_table[string_menu.addAction("UTF-8 IDNA")] = lambda : obj.copy_as(lambda data : data.decode("utf8").encode("idna"), False)
	action_table[string_menu.addAction("UTF-16 (\\u)")] = lambda : obj.copy_as(lambda data : encode_utf16_string(data, "\\u"), False)
	action_table[string_menu.addAction("UTF-16 (%u)")] = lambda : obj.copy_as(lambda data : encode_utf16_string(data, "%u"), False)
	action_table[string_menu.addAction("UTF-16 URL")] = lambda : obj.copy_as(lambda data : encode_url(data.decode("utf16").encode("utf8")), False)
	action_table[string_menu.addAction("UTF-16 IDNA")] = lambda : obj.copy_as(lambda data : data.decode("utf16").encode("idna"), False)
	unicode_menu = menu.addMenu("Unicode")
	action_table[unicode_menu.addAction("UTF-16")] = lambda : obj.copy_as(lambda data : data.decode("utf16"), False)
	action_table[unicode_menu.addAction("UTF-32")] = lambda : obj.copy_as(lambda data : data.decode("utf32"), False)
	menu.addSeparator()
	action_table[menu.addAction("Hex dump")] = lambda : obj.copy_as(hex_dump_encode, False)
	action_table[menu.addAction("Raw hex")] = lambda : obj.copy_as(lambda data : data.encode("hex"), False)
	action_table[menu.addAction("Base64")] = lambda : obj.copy_as(lambda data : data.encode("base64"), False)
	action_table[menu.addAction("UUEncode")] = lambda : obj.copy_as(lambda data : data.encode("uu_codec"), False)
	compress_menu = menu.addMenu("Compressed")
	action_table[compress_menu.addAction("zlib")] = lambda : obj.copy_as(lambda data : data.encode("zlib"), True)
	action_table[compress_menu.addAction("bz2")] = lambda : obj.copy_as(lambda data : data.encode("bz2"), True)
	menu.addSeparator()
	array_menu = menu.addMenu("C array")
	action_table[array_menu.addAction("8-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 1, "B", "unsigned char", ""), False)
	action_table[array_menu.addAction("16-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 2, "<H", "unsigned short", ""), False)
	action_table[array_menu.addAction("32-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 4, "<I", "unsigned int", ""), False)
	action_table[array_menu.addAction("64-bit elements")] = lambda : obj.copy_as(lambda data : encode_c_array(data, 8, "<Q", "unsigned long long", "LL"), False)
	menu.addSeparator()
	hash_menu = menu.addMenu("Hash")
	action_table[hash_menu.addAction("MD2")] = lambda : obj.copy_as(lambda data : MD2.new(data).digest(), True)
	action_table[hash_menu.addAction("MD4")] = lambda : obj.copy_as(lambda data : MD4.new(data).digest(), True)
	action_table[hash_menu.addAction("MD5")] = lambda : obj.copy_as(lambda data : MD5.new(data).digest(), True)
	action_table[hash_menu.addAction("SHA-1")] = lambda : obj.copy_as(lambda data : SHA.new(data).digest(), True)
	action_table[hash_menu.addAction("SHA-256")] = lambda : obj.copy_as(lambda data : SHA256.new(data).digest(), True)
	hmac_menu = hash_menu.addMenu("HMAC")
	action_table[hmac_menu.addAction("MD2")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, MD2).digest(), True)
	action_table[hmac_menu.addAction("MD4")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, MD4).digest(), True)
	action_table[hmac_menu.addAction("MD5")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, MD5).digest(), True)
	action_table[hmac_menu.addAction("SHA-1")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, SHA).digest(), True)
	action_table[hmac_menu.addAction("SHA-256")] = lambda : obj.copy_as(lambda data : HMAC.new(request_key(obj), data, SHA256).digest(), True)
import json
import string
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtGui import QPixmap, QIcon
import sys
from PyQt5.QtWidgets import QMainWindow, QDialog, QLineEdit, QPushButton, QVBoxLayout, QMessageBox, QApplication,\
    QWidget
import os
from base64 import b64encode
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Hash import MD2
ha = MD2.new()
from padding import pad, unpad
iv = os.urandom(16)

users_template = {
    "admin": ""
}
with open('users.json', 'w') as file:
    json.dump(users_template, file)
with open('users.json', 'r') as f:
    users = json.load(f)
current = []
blocked = []
pw_check_enabled = []
secrets = []


class Window(QMainWindow):
    switch_window = pyqtSignal()
Exemple #17
0
from Crypto.Hash import SHA256
from Crypto.Hash import SHA224
from Crypto.Hash import RIPEMD
from Crypto.Hash import MD5
from Crypto.Hash import MD4
from Crypto.Hash import MD2
import whirlpool
import hashlib

a = raw_input("Digite uma string: ")
b = SHA512.new(a).hexdigest()
c = SHA384.new(a).hexdigest()
d = SHA256.new(a).hexdigest()
e = SHA224.new(a).hexdigest()
f = RIPEMD.new(a).hexdigest()
g = MD5.new(a).hexdigest()
h = MD4.new(a).hexdigest()
i = MD2.new(a).hexdigest()
j = whirlpool.new(a).hexdigest()
l = hashlib.sha1(a).hexdigest()
print "SHA512 = ", b
print "SHA384 = ", c
print "SHA256 = ", d
print "SHA224 = ", e
print "RIPEMD160 = ", f
print "MD5 = ", g
print "MD4 = ", h
print "MD2 = ", i
print "Whirlpool = ", j
print "SHA1 = ", l
Exemple #18
0
from cryptography.hazmat.primitives import hashes
from Crypto.Hash import MD2 as pycrypto_md2
from Crypto.Hash import MD4 as pycrypto_md4
from Crypto.Hash import MD5 as pycrypto_md5
from Cryptodome.Hash import MD2 as pycryptodomex_md2
from Cryptodome.Hash import MD4 as pycryptodomex_md4
from Cryptodome.Hash import MD5 as pycryptodomex_md5
import hashlib

hashlib.md5(1)
hashlib.md5(1).hexdigest()

abc = str.replace(hashlib.md5("1"), "###")

print(hashlib.md5("1"))

pycrypto_md2.new()
pycrypto_md4.new()
pycrypto_md5.new()

pycryptodomex_md2.new()
pycryptodomex_md4.new()
pycryptodomex_md5.new()

hashes.MD5()
Exemple #19
0
def _md2_new(*args):
    from Crypto.Hash import MD2
    _new_funcs['MD2'] = _new_funcs['md2'] = MD2.new
    return MD2.new(*args)
Exemple #20
0
 def setup(self, arg):
     self.h = MD2.new()
Exemple #21
0
##https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Hash/MD2.py

from Crypto.Hash import MD2

h = MD2.new()
h.update(b'Hello')
print h.hexdigest()
Exemple #22
0
def _md2_new(*args):
    from Crypto.Hash import MD2
    _new_funcs['MD2'] = _new_funcs['md2'] = MD2.new
    return MD2.new(*args)
Exemple #23
0
def readNormal():
	with open(wordlist, "r", encoding="ISO-8859-1") as FileObj:
		for line in FileObj:
			passwd1 = line.replace("\n", "")
			if hash_type == 0: #MD5
				passwd_hash = hashlib.md5(passwd1.encode()).hexdigest()
			elif hash_type == 1: #MD4
				passwd_hash = MD4.new(passwd1.encode()).hexdigest()
			elif hash_type == 2: #MD2
				passwd_hash = MD2.new(passwd1.encode()).hexdigest()
			elif hash_type == 3: #SHA1
				passwd_hash = hashlib.sha1(passwd1.encode()).hexdigest()
			elif hash_type == 4: #SHA-224
				passwd_hash = hashlib.sha224(passwd1.encode()).hexdigest()
			elif hash_type == 5: #SHA-256
				passwd_hash = hashlib.sha256(passwd1.encode()).hexdigest()
			elif hash_type == 6: #SHA-384
				passwd_hash = hashlib.sha384(passwd1.encode()).hexdigest()
			elif hash_type == 7: #SHA-512
				passwd_hash = hashlib.sha512(passwd1.encode()).hexdigest()
			elif hash_type == 8: #SHA3-224
				passwd_hash = hashlib.sha3_224(passwd1.encode()).hexdigest()
			elif hash_type == 9: #SHA3-256
				passwd_hash = hashlib.sha3_256(passwd1.encode()).hexdigest()
			elif hash_type == 10: #SHA3-384
				passwd_hash = hashlib.sha3_384(passwd1.encode()).hexdigest()
			elif hash_type == 11: #SHA3-512
				passwd_hash = hashlib.sha3_512(passwd1.encode()).hexdigest()
			elif hash_type == 12: #BLAKE2s256
				passwd_hash = hashlib.new('blake2s256', passwd1.encode()).hexdigest()
			elif hash_type == 13: #BLAKE2b512
				passwd_hash = hashlib.new('blake2b512', passwd1.encode()).hexdigest()
			elif hash_type == 14: #NTLM
				passwd_hash = hashlib.new('md4', passwd1.encode('utf-16le')).hexdigest()
			elif hash_type == 15: #Whirlpool
				passwd_hash = hashlib.new('whirlpool', passwd1.encode()).hexdigest()
			elif hash_type == 16: #SM3
				passwd_hash = hashlib.new('sm3', passwd1.encode()).hexdigest()
			elif hash_type == 17: #RIPEMD-160
				passwd_hash = hashlib.new('ripemd160', passwd1.encode()).hexdigest()
			else:
				print(color.RED + "[-] Invalid hash type...Exiting!" + color.END)
				sys.exit()
			if verbose == True:
				print(color.BLACK + "Trying {}" .format(str(repr(passwd1))) + color.END)
			if user_hash == passwd_hash:
				print(color.GREEN + "[+] Hash cracked! Results: " + color.RED + str(line) + color.END)
				endTime = time.time()
				deltaTime = endTime - startTime
				sys.stdout.write("\033[F")
				print(color.GREEN + "[+] Cracking finished in " + color.RED + str(format(deltaTime, ".3f")) + color.END + color.GREEN + "s" + color.END)
				if output == True:
					output_text = "\nDate: {0}\nHash: {1}\nCracked hash: {2}\nCracking time: {3}\nWordlist: {4}" .format(str(today.strftime("%d/%m/%Y")), str(user_hash), str(line).replace("\n", ""), format(deltaTime, ".3f"), str(wordlist))
					print(output_text, file=open("results.txt", "a"))
					print(color.ORANGE + "Results saved successfully in ./results.txt!" + color.END)
				if output_json == True:
					results = {
						"Date": str(today.strftime("%d/%m/%Y")),
						"hash": str(user_hash),
						"crackedHash": str(line).replace("\n", ""),
						"crackingTime": format(deltaTime, ".3f"),
						"wordlist": str(wordlist)
					}
					results_json = json.dumps(results, indent=2)
					print(results_json, file=open("results.json", "a"))
					print(color.ORANGE + "Results saved successfully in ./results.json!" + color.END)
				sys.exit()
		print(color.RED + "[-] Hash not found! Maybe another wordlist would help." + color.END)
		sys.exit()
Exemple #24
0
from Crypto.Hash import MD2
from Crypto.Hash import MD5
from Crypto.Hash import SHA
from Crypto.Hash import SHA256
from Crypto.Hash import SHA512
from itertools import product
import os
target_hash = "757c479895d6845b2b0530cd9a2b11" #original hash

#target_hash = "4ae2e4cc3750845b2b0530cd9a2b11" # test hash (aaaaaaaaaaab......
algorithms = ['md2', 'md5', 'sha1', 'sha256', 'sha512']
bitwidth = 6

input = []
hash_function = []
hash_function.append(MD2.new())
hash_function.append(MD5.new())
hash_function.append(SHA.new())
hash_function.append(SHA256.new())
hash_function.append(SHA512.new())

temp_res = []
temp_res.append("")
temp_res.append("")
temp_res.append("")
temp_res.append("")
temp_res.append("")

temp_input = []
temp_input.append("")
temp_input.append("")
Exemple #25
0
 def digest(self, data):
     return MD2.new(data).digest()
# -*- coding: utf-8 -*-
"""
Created on Wed Apr  8 17:17:32 2015

@author: zazkia
"""

import itertools
from Crypto.Hash import MD2,MD5,SHA,SHA256,SHA512

charset = 'abcdefghijklmnopqrstuvwxyz0123456789'

for i in itertools.product(charset, repeat=6): 
    MD2hash = MD2.new(''.join(i)).hexdigest()
    MD5hash = MD5.new(''.join(i)).hexdigest()
    SHA1hash = SHA.new(''.join(i)).hexdigest()
    SHA256hash = SHA256.new(''.join(i)).hexdigest()
    SHA512hash = SHA512.new(''.join(i)).hexdigest()
    
    if MD2hash.startswith('757c47'):
        print 'MD2: '+''.join(i)+' '+MD2hash 
        with open("egg_24_MD2.txt", "a") as myfile:
            myfile.write('MD2: '+''.join(i)+' '+MD2hash)
    
    if MD5hash[6:].startswith('9895d6'):
        print 'MD5: '+''.join(i)+' '+MD5hash 
        with open("egg_24_MD5.txt", "a") as myfile2:
            myfile2.write('MD5: '+''.join(i)+' '+MD5hash)
        
    if SHA1hash[12:].startswith('845b2b'):
        print 'SHA1: '+''.join(i)+' '+SHA1hash 
Exemple #27
0
def populate_copy_as_menu(menu, obj, action_table):
    string_menu = menu.addMenu("Escaped string")
    action_table[string_menu.addAction("ASCII")] = lambda: obj.copy_as(
        lambda data: data.encode("string_escape").replace("\"", "\\\""), False)
    action_table[string_menu.addAction(
        "UTF-8 URL")] = lambda: obj.copy_as(encode_url, False)
    action_table[string_menu.addAction("UTF-8 IDNA")] = lambda: obj.copy_as(
        lambda data: data.decode("utf8").encode("idna"), False)
    action_table[string_menu.addAction("UTF-16 (\\u)")] = lambda: obj.copy_as(
        lambda data: encode_utf16_string(data, "\\u"), False)
    action_table[string_menu.addAction("UTF-16 (%u)")] = lambda: obj.copy_as(
        lambda data: encode_utf16_string(data, "%u"), False)
    action_table[string_menu.addAction("UTF-16 URL")] = lambda: obj.copy_as(
        lambda data: encode_url(data.decode("utf16").encode("utf8")), False)
    action_table[string_menu.addAction("UTF-16 IDNA")] = lambda: obj.copy_as(
        lambda data: data.decode("utf16").encode("idna"), False)
    unicode_menu = menu.addMenu("Unicode")
    action_table[unicode_menu.addAction("UTF-16")] = lambda: obj.copy_as(
        lambda data: data.decode("utf16"), False)
    action_table[unicode_menu.addAction("UTF-32")] = lambda: obj.copy_as(
        lambda data: data.decode("utf32"), False)
    menu.addSeparator()
    action_table[menu.addAction(
        "Hex dump")] = lambda: obj.copy_as(hex_dump_encode, False)
    action_table[menu.addAction("Raw hex")] = lambda: obj.copy_as(
        lambda data: data.encode("hex"), False)
    action_table[menu.addAction("Base64")] = lambda: obj.copy_as(
        lambda data: data.encode("base64"), False)
    action_table[menu.addAction("UUEncode")] = lambda: obj.copy_as(
        lambda data: data.encode("uu_codec"), False)
    compress_menu = menu.addMenu("Compressed")
    action_table[compress_menu.addAction(
        "zlib")] = lambda: obj.copy_as(lambda data: data.encode("zlib"), True)
    action_table[compress_menu.addAction(
        "bz2")] = lambda: obj.copy_as(lambda data: data.encode("bz2"), True)
    menu.addSeparator()
    array_menu = menu.addMenu("C array")
    action_table[array_menu.addAction("8-bit elements")] = lambda: obj.copy_as(
        lambda data: encode_c_array(data, 1, "B", "unsigned char", ""), False)
    action_table[array_menu.addAction(
        "16-bit elements")] = lambda: obj.copy_as(
            lambda data: encode_c_array(data, 2, "<H", "unsigned short", ""),
            False)
    action_table[array_menu.addAction(
        "32-bit elements")] = lambda: obj.copy_as(
            lambda data: encode_c_array(data, 4, "<I", "unsigned int", ""),
            False)
    action_table[array_menu.addAction(
        "64-bit elements")] = lambda: obj.copy_as(
            lambda data: encode_c_array(data, 8, "<Q", "unsigned long long",
                                        "LL"), False)
    menu.addSeparator()
    hash_menu = menu.addMenu("Hash")
    action_table[hash_menu.addAction("MD2")] = lambda: obj.copy_as(
        lambda data: MD2.new(data).digest(), True)
    action_table[hash_menu.addAction("MD4")] = lambda: obj.copy_as(
        lambda data: MD4.new(data).digest(), True)
    action_table[hash_menu.addAction("MD5")] = lambda: obj.copy_as(
        lambda data: MD5.new(data).digest(), True)
    action_table[hash_menu.addAction("SHA-1")] = lambda: obj.copy_as(
        lambda data: SHA.new(data).digest(), True)
    action_table[hash_menu.addAction("SHA-256")] = lambda: obj.copy_as(
        lambda data: SHA256.new(data).digest(), True)
    hmac_menu = hash_menu.addMenu("HMAC")
    action_table[hmac_menu.addAction("MD2")] = lambda: obj.copy_as(
        lambda data: HMAC.new(request_key(obj), data, MD2).digest(), True)
    action_table[hmac_menu.addAction("MD4")] = lambda: obj.copy_as(
        lambda data: HMAC.new(request_key(obj), data, MD4).digest(), True)
    action_table[hmac_menu.addAction("MD5")] = lambda: obj.copy_as(
        lambda data: HMAC.new(request_key(obj), data, MD5).digest(), True)
    action_table[hmac_menu.addAction("SHA-1")] = lambda: obj.copy_as(
        lambda data: HMAC.new(request_key(obj), data, SHA).digest(), True)
    action_table[hmac_menu.addAction("SHA-256")] = lambda: obj.copy_as(
        lambda data: HMAC.new(request_key(obj), data, SHA256).digest(), True)
Exemple #28
0
 def _algorithm(self, data):
     from Crypto.Hash import MD2
     return MD2.new(data)
Exemple #29
0
#from django.contrib import admin
#from DevUtils1 import models

# Register your models here.
from Crypto.Hash import HMAC
from Crypto.Hash import MD2
from Crypto.Hash import MD4
from Crypto.Hash import MD5
from Crypto.Hash import RIPEMD
from Crypto.Hash import SHA224
from Crypto.Hash import SHA256
from Crypto.Hash import SHA384
from Crypto.Hash import SHA512

print("HMAC encryption", HMAC.new('abc').hexdigest())
print("MD2 encryption", MD2.new('abc').hexdigest())
print("MD4 encryption", MD4.new('abc').hexdigest())
print("MD5 encryption", MD5.new('abc').hexdigest())
print("RIPEMD encryption", RIPEMD.new('abc').hexdigest())
print("SHA224 encryption", SHA224.new('abc').hexdigest())
print("SHA256 encryption", SHA256.new('abc').hexdigest())
print("SHA384 encryption", SHA384.new('abc').hexdigest())
print("SHA512 encryption", SHA512.new('abc').hexdigest())



#################3
from Crypto.Cipher import DES
des = DES.new('01234567', DES.MODE_ECB)
text = 'abcdefgh'
cipher_text = des.encrypt(text)
Exemple #30
0
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time : 2020/8/3 16:59
# @Author : ahrist
# @Email : [email protected]
# @File : temp.py
# @Software: PyCharm

from Crypto.Hash import MD2
import hashlib

str1 = '73.25'
# m = hashlib.md5()
m = MD2.new()
b = str1.encode(encoding='utf-8')
for _ in range(100000000):
    m.update(b)
str_md5 = m.hexdigest()
print('MD5加密前为 :' + str1)
print('MD5加密后为 :' + str_md5)
def HeadlessBrowserInstance1():
    start = time.time()

    # Record variable with empty array
    Record = []

    # calling FetchRecord and storing return values i.e. URL and DOMAIN in Record[]
    Record = FetchRecord()
    url = Record[0]
    domain = Record[1]

    flag1 = int(1)
    try:
        # Updating FLAG1 in database for specific URL so another browser instance works on different URL
        updateflag1 = '''update Test set FLAG1=? where URL=?'''
        ExecuteQuery.execute(updateflag1, (flag1, url))
        DatabaseConnect.commit()
    except Exception as e:
        print(e)

    # storing arguments of headless browser in by importing Options
    parameters = Options()

    # --headless forces browser instance to work in headless mode
    parameters.add_argument("--headless")

    # creating webdriver variable for firefox by passing parameters and adding Gecko web driver to call firefox via python
    browser = webdriver.Firefox(firefox_options=parameters,
                                executable_path=r'C:\\webdriver\\geckodriver')

    # maximizing window of headless firefox
    browser.maximize_window()

    try:
        # Passing URL in headlesss firefox
        browser.get(url)
    except Exception as e:
        print(e)

    # generating Unique MD2 hash of each URL and convert them into string
    starthashtime = time.time()
    hashurl = str.encode(url)
    SHAVALUE = MD2.new(hashurl)
    endhashtime = time.time()

    # Capturing screenshot of webpage as PNG
    capturescreen = browser.get_screenshot_as_png()

    # quality is a parameter used while converting png to jpeg
    quality = 100

    # converting PNG into Bytes and then into jpeg
    try:
        img = Image.open(io.BytesIO(capturescreen))
        img = img.convert("RGB")
    except Exception as e:
        print(e)

    # creating subfolders with domain as naming convention under ScreenShots folder
    try:
        os.makedirs(os.path.join(r".\\ScreenShots\\", str(domain)))
    except Exception as e:
        print(e)

    # FolderPath stores path for that particular domain
    FolderPath = os.path.join(r'.\\ScreenShots\\', str(domain) + '\\')

    # Glob loop to scan all the domain directories in ScreenShots folder
    for folders in glob.glob(r'.\\ScreenShots\\*'):

        # If domain folder exists store converted screenshot of that URL in that specific domain
        if os.path.exists(FolderPath):
            StoragePath = os.path.join(r'.\\ScreenShots', str(domain) + '\\')

            # saving Image by specifying quality and setting image optimization to true
            try:
                img.save(str(StoragePath) + str(SHAVALUE.hexdigest()) +
                         '.jpeg',
                         'JPEG',
                         quality=quality,
                         optimise=True)
            except Exception as e:
                print(e)

        #  If domain folder doesn't exist create new folder and store image
        else:
            os.makedirs(os.path.join(r".\\ScreenShots\\", str(domain)))

            StoragePath = os.path.join(r'.\\ScreenShots', str(domain) + '\\')

            try:
                img.save(str(StoragePath) + str(SHAVALUE.hexdigest()) +
                         '.jpeg',
                         'JPEG',
                         quality=quality,
                         optimise=True)
            except Exception as e:
                print(e)

    # Converting hash into string, flag into integer, path into string
    hash = str(SHAVALUE.hexdigest())
    flag = int(1)
    Location = str(StoragePath) + hash + '.jpeg'
    Location = Location.strip(".\\")

    # updating record in database by updating flags, hash and path of that image
    try:
        updateHASH = (
            '''UPDATE "Test" SET FLAG=?, HASH=?, PATH=? WHERE URL = ?''')
        ExecuteQuery.execute(updateHASH, (flag, hash, Location, url))
        DatabaseConnect.commit()
    except Exception as e:
        print(e)

    # Safely closing browser instance
    browser.close()
    browser.quit()

    end = time.time()
Exemple #32
0
 def run(self, text):
     from Crypto.Hash import MD2
     return MD2.new(text.encode('utf-8',
                                errors='surrogateescape')).hexdigest()
Exemple #33
0
 def _get_md2_hash(self, string):
     """Compute md2 hash"""
     md2 = MD2.new()
     md2.update(string)
     return md2.hexdigest()
Exemple #34
0
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
#pip安装 pip install pycryptodome
from Crypto.Hash import MD2



# Press the green button in the gutter to run the script.
if __name__ == '__main__':
    #print_hi('PyCharm')
    txt = "39"
    # md2加密1亿次还是2亿此根据题目要求
    for i in range(200000000):
        txt = MD2.new(txt.encode("utf8")).hexdigest()
    print(txt)
#17130526923
# See PyCharm help at https://www.jetbrains.com/help/pycharm/


Exemple #35
0
 def Verify(self, issuer = None):
     if issuer == None:
         issuer = self
         
     sigAlgo = self.SignatureAlgorithm()
     CertDer = encoder.encode(self.Asn1Obj.getComponentByName('tbsCertificate'))
     
     if sigAlgo == 'sha1WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA1':
         from Crypto.Hash import SHA
         SigHash = SHA.new(CertDer)
     elif sigAlgo == 'sha256WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA256':
         from Crypto.Hash import SHA256
         SigHash = SHA256.new(CertDer)
     elif sigAlgo == 'sha384WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA384':
         from Crypto.Hash import SHA384
         SigHash = SHA384.new(CertDer)
     elif sigAlgo == 'sha512WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA512':
         from Crypto.Hash import SHA512
         SigHash = SHA512.new(CertDer)
     elif sigAlgo == 'sha224WithRSAEncryption' or sigAlgo == 'ecdsa-with-SHA224':
         from Crypto.Hash import SHA224
         SigHash = SHA224.new(CertDer)
     elif sigAlgo == 'md2WithRSAEncryption':
         from Crypto.Hash import MD2
         SigHash = MD2.new(CertDer)
     elif sigAlgo == 'md4WithRSAEncryption':
         from Crypto.Hash import MD4
         SigHash = MD4.new(CertDer)
     elif sigAlgo == 'md5WithRSAEncryption':
         from Crypto.Hash import MD5
         SigHash = MD5.new(CertDer)
     else:
         raise NotImplementedError('Signature algorithm not supported ({0})'.format(sigAlgo))
     
     
     
     if issuer.PublicKeyAlgorithm() == 'rsaEncryption':
         from Crypto.PublicKey import RSA
         from Crypto.Signature import PKCS1_v1_5
         
         PubKeyDer = issuer.PublicKey().Raw()
         key = RSA.importKey(PubKeyDer)
     
         verifier = PKCS1_v1_5.new(key)
         try:
             if verifier.verify(SigHash, self.Signature()):
                 return True
             else:
                 return False
         except ValueError:
             return False
     
     elif issuer.PublicKeyAlgorithm() == 'id-ecPublicKey':
         from ecdsa import VerifyingKey, NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1
         from ecdsa.util import sigdecode_der
         curves = [NIST192p, NIST224p, NIST256p, NIST384p, NIST521p, SECP256k1]
         
         TheCurve = None
         for crv in curves:
             if crv.name == issuer.PublicKey().CurveMap():
                 TheCurve = crv
                 break
             
         if TheCurve == None:
             raise NotImplementedError('Public Key Curve not supported ({0})'.format(issuer.PublicKey().CurveMap()))
         
         VerKey = VerifyingKey.from_string(issuer.PublicKey().Raw(), curve=TheCurve)
         
         try:
             if VerKey.verify_digest(self.Signature(), SigHash.digest(), sigdecode=sigdecode_der):
                 return True
             else:
                 return False
         except:
             return False
       
     else:
         raise NotImplementedError('Public key algorithm not supported ({0})'.format(issuer.PublicKeyAlgorithm()))
Exemple #36
0
def md2E(_str):
    m = MD2.new()
    m.update(_str)
    return m.hexdigest()
Exemple #37
0
from Crypto.Hash import MD5
from Crypto.Hash import RIPEMD
from Crypto.Hash import SHA
from Crypto.Hash import SHA256

HMAC-MD2-MD4-MD5-SHA-SHA526-RIPEMD  .. now lets try 


"""

secret = b'B3mB4m'
h = HMAC.new(secret)
h.update(word)
print "HMAC = " + h.hexdigest()

h2 = MD2.new()
h2.update(word)
print "MD2 = " + h2.hexdigest()

h3 = MD4.new()
h3.update(word)
print "MD4 = " + h3.hexdigest()

h4 = MD5.new()
h4.update(word)
print "MD5 = " + h3.hexdigest()

h5 = RIPEMD.new()
h5.update(word)
print "RIPEMD = " + h5.hexdigest()
Exemple #38
0
from Crypto.Hash import MD4 as pycrypto_md4
from Crypto.Hash import MD5 as pycrypto_md5
from Crypto.Hash import SHA as pycrypto_sha
from Cryptodome.Hash import MD2 as pycryptodomex_md2
from Cryptodome.Hash import MD4 as pycryptodomex_md4
from Cryptodome.Hash import MD5 as pycryptodomex_md5
from Cryptodome.Hash import SHA as pycryptodomex_sha
import hashlib

hashlib.md5(1)
hashlib.md5(1).hexdigest()

abc = str.replace(hashlib.md5("1"), "###")

print(hashlib.md5("1"))

hashlib.sha1(1)

pycrypto_md2.new()
pycrypto_md4.new()
pycrypto_md5.new()
pycrypto_sha.new()

pycryptodomex_md2.new()
pycryptodomex_md4.new()
pycryptodomex_md5.new()
pycryptodomex_sha.new()

hashes.MD5()
hashes.SHA1()
Exemple #39
0
# for every hash function a tuple is provided, giving access to
# - hash output length in byte
# - associated hash function that take data to be hashed as parameter
#   XXX I do not provide update() at the moment.
# - DER encoding of the leading bits of digestInfo (the hash value
#   will be concatenated to create the complete digestInfo).
#
# Notes:
# - MD4 asn.1 value should be verified. Also, as stated in
#   PKCS#1 v2.1, MD4 should not be used.
# - 'tls' one is the concatenation of both md5 and sha1 hashes used
#   by SSL/TLS when signing/verifying things
_hashFuncParams = {
    "md2":
    (16, MD2.new, lambda x: MD2.new(x).digest(),
     '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02\x05\x00\x04\x10'
     ),
    "md4":
    (16, MD4.new, lambda x: MD4.new(x).digest(),
     '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04\x05\x00\x04\x10'
     ),
    "md5":
    (16, md5, lambda x: md5(x).digest(),
     '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10'
     ),
    "sha1": (20, sha1, lambda x: sha1(x).digest(),
             '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'),
    "sha224":
    (28, sha224, lambda x: sha224(x).digest(),
     '\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c'
Exemple #40
0
# for every hash function a tuple is provided, giving access to
# - hash output length in byte
# - associated hash function that take data to be hashed as parameter
#   XXX I do not provide update() at the moment.
# - DER encoding of the leading bits of digestInfo (the hash value
#   will be concatenated to create the complete digestInfo).
#
# Notes:
# - MD4 asn.1 value should be verified. Also, as stated in
#   PKCS#1 v2.1, MD4 should not be used.
# - 'tls' one is the concatenation of both md5 and sha1 hashes used
#   by SSL/TLS when signing/verifying things
_hashFuncParams = {
    "md2"    : (16,
                MD2.new,
                lambda x: MD2.new(x).digest(),
                '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02\x05\x00\x04\x10'),
    "md4"    : (16,
                MD4.new,
                lambda x: MD4.new(x).digest(),
                '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04\x05\x00\x04\x10'),
    "md5"    : (16,
                md5,
                lambda x: md5(x).digest(),
                '\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10'),
    "sha1"   : (20,
                sha1,
                lambda x: sha1(x).digest(),
                '\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14'),
    "sha224" : (28,
                sha224,
Exemple #41
0
    n = int(bits, 2)

    return int2bytes(n).decode(encoding)


def int2bytes(i):

    hex_string = '%x' % i

    n = len(hex_string)

    return binascii.unhexlify(hex_string.zfill(n + (n & 1)))


md2hasher = MD2.new()


def md2(outputformat, importx, inputformat, raw, infilepath, outfilepath):

    if importx == 'file':

        f = open(infilepath, 'r')
        raw = f.read()
        f.close()

    elif importx == 'print':

        raw = raw

    else: