def _validate_response(self, req): try: body = req.stream.read() data = json.loads(body.decode('utf-8')) challenge = base64.b64decode(data['challenge']) response = base64.b64decode(data['response']) client_pub = RSA.importKey(data['pub']) decrypted_challenge = self.key.decrypt(challenge).decode() challenge_addr, challenge_time, junk = decrypted_challenge.split( '@', maxsplit=2) delta = int(challenge_time) - time() except Exception as e: return {'status': falcon.HTTP_400, 'error': 'Invalid request'} h = SHA224.new(challenge) verifier = PKCS1_v1_5.new(client_pub) if not verifier.verify(h, response): return {'status': falcon.HTTP_400, 'error': 'Invalid signature'} if challenge_addr != req.remote_addr: return {'status': falcon.HTTP_400, 'error': 'Invalid response'} if delta > 30: return {'status': falcon.HTTP_400, 'error': 'Expired response'} sha224 = SHA224.new(client_pub.exportKey(format='DER')).hexdigest() return { 'status': falcon.HTTP_200, 'sha224': sha224, 'error': None, }
def crypto_hash_sha224(data): """ 调用 Crypto 库的 sha224 函数进行哈希操作 :param data: 待哈希的数值, 比如 b"test_hash" :return: "acbcc08b23f746664cb9ce1ff6f234a76311d94a0c64108abc4c290f" """ return SHA224.new(data).hexdigest()
def decrypt(sk, ct_path="ciphertext.enc", savePT="plaintext.dec"): # Load Y and ciphertext with open(ct_path, 'rb') as input: y = dill.load(input) ciphertext = dill.load(input) # Compute x = RSA^(-1)(y) as y^d mod N x = pow(y, sk.d, sk.n) # Compute symmetric key with Hash function (SHA224) k = SHA224.new(repr(x).encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext print("K: "+str(k)) # Count block_size bs = Blowfish.block_size # Retreive IV vector iv = ciphertext[:bs] # Remove IV ciphertext = ciphertext[bs:] print("CT-LEN:"+str(len(ciphertext))) # Initialize Blowfish cipher cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv) # Decrypt plaintext = cipher.decrypt(ciphertext) # Remove padding last_byte = plaintext[-1] plaintext = plaintext[:- (last_byte if type(last_byte) is int else ord(last_byte))] # Write to file the plaintext decrypted io.open(savePT,"wb").write(plaintext) return plaintext
def encrypt(key, path="message.txt", saveCT="ciphertext.enc"): b = random.randrange(2, (key.p)-1) u = modexp(key.g, b, key.p) v = modexp(key.h, b, key.p) uv = str(u)+str(v) k = SHA224.new(uv.encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext with AES print("K: "+str(k)) # Open file plaintext to cipher plaintext = open(path,"rb").read() #plaintext = encode(plaintext, key.iNumBits) bs = Blowfish.block_size iv = Random.new().read(bs) cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv) plen = bs - divmod(len(plaintext),bs)[1] padding = [plen]*plen padding = struct.pack('b'*plen,*padding) ciphertext = iv + cipher.encrypt(plaintext+padding) # Save ciphertext to file: print("CT-LEN:"+str(len(ciphertext))) with open(saveCT, 'wb') as output: dill.dump(u, output) dill.dump(ciphertext, output) return plaintext, ciphertext
def encrypt(pk, path="message.txt",saveCT="ciphertext.enc"): # Generate random x in Zn x = random.randrange(2, (pk.n)-1) #random x in Zn # Calculate y = RSA(x) as x^e mod N y = pow(x, pk.e, pk.n) #y to send with ciphertext # Compute symmetric key with Hash function (SHA224) k = SHA224.new(repr(x).encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext print("K: "+str(k)) # Open file plaintext to cipher plaintext = open(path,"rb").read() # Count block_size bs = Blowfish.block_size # Generate a random init vector iv = Random.new().read(bs) # Initialize Blowfish cipher cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv) # Calculate Plaintext for padding plen = bs - divmod(len(plaintext),bs)[1] # Add padding padding = [plen]*plen padding = struct.pack('b'*plen,*padding) # Encrypt adding IV ciphertext = iv + cipher.encrypt(plaintext+padding) # Save ciphertext to file: print("CT-LEN:"+str(len(ciphertext))) with open(saveCT, 'wb') as output: dill.dump(y, output) dill.dump(ciphertext, output) return plaintext, ciphertext
def __init__(self, signatureFile, hashAlgorithm, keyLength, privateKeyE): self.signatureFile = open(signatureFile, "w") self.hashAlgorithmName = hashAlgorithm self.keyLength = keyLength self.privateKey = privateKeyE #tuple of (n, e, d) if hashAlgorithm == 'SHA-2-224': self.hashAlgorithm = SHA224.new() elif hashAlgorithm == 'SHA-2-256': self.hashAlgorithm = SHA256.new() elif hashAlgorithm == 'SHA-2-384': self.hashAlgorithm = SHA384.new() elif hashAlgorithm == 'SHA-2-512': self.hashAlgorithm = SHA512.new() elif hashAlgorithm == 'SHA-3-224': self.hashAlgorithm = SHA3_224.new() elif hashAlgorithm == 'SHA-3-256': self.hashAlgorithm = SHA3_256.new() elif hashAlgorithm == 'SHA-2-384': self.hashAlgorithm = SHA3_384.new() elif hashAlgorithm == 'SHA-2-256': self.hashAlgorithm = SHA3_512.new() else: raise Exception("Invalid hash function: " + hashAlgorithm)
def process_keys(self, bit, key='', iv=''): if key != '': key = key.encode('ascii') if bit == 256: #256/8 = 32 byte or character key key = SHA256.new(key).digest( ) # use SHA-256 over our key to get a proper-sized AES key from any size of string bytes, output length 32 elif bit == 192: #128/8 = 16 byte or character key key = SHA224.new( key).digest()[:-4] # 28 character to 24 character elif bit == 128: #128/8 = 16 byte or character key key = MD5.new(key).digest() if iv != '': if type(iv) == str: iv = iv.encode('ascii') self.has_iv = False else: self.has_iv = True #print("Needs to mix iv with encrypted text at starting.") if key != '' and iv != '': return key, iv elif key != '': return key elif iv != '': return iv else: raise ValueError("No parameter given to process.")
def get_sha224(data: str) -> dict: """ Returns the SHA224 hash value (hex). """ sha224_call = SHA224.new() sha224_call.update(data.encode('utf-8')) return {"SHA224_hex": sha224_call.hexdigest()}
def decrypt(key, ct_path="ciphertext.enc", savePT="plaintext.dec"): with open(ct_path, 'rb') as input: u = dill.load(input) ciphertext = dill.load(input) v = modexp(u, key.x, key.p) uv = str(u)+str(v) k = SHA224.new(uv.encode('utf-8')).hexdigest().encode('utf-8') #symmetric key for compute the ciphertext with AES print("K: "+str(k)) bs = Blowfish.block_size iv = ciphertext[:bs] # Remove IV ciphertext = ciphertext[bs:] print("CT-LEN:"+str(len(ciphertext))) cipher = Blowfish.new(k, Blowfish.MODE_CBC, iv) plaintext = cipher.decrypt(ciphertext) # Remove padding last_byte = plaintext[-1] plaintext = plaintext[:- (last_byte if type(last_byte) is int else ord(last_byte))] # Write to file the plaintext decrypted #plaintext = plaintext.decode(plaintext, key.iNumBits) io.open(savePT,"wb").write(plaintext) return plaintext
def testSignature(signatureFile, originalFile, pubFile): pubKeyL, n, e = readPublicKey(pubFile) public_key = RSA.construct((n, e)) verifier = PKCS1_v1_5.new(public_key) fileName, hashed, key, signature = readSignature(signatureFile) (hashing, hashingKeyL) = hashed (enc, encKeyL) = key assert fileName == originalFile assert enc == 'RSA' assert encKeyL == pubKeyL hashAlgorithm = hashing + "-" + str(hashingKeyL) if hashAlgorithm == 'SHA-2-224': hashAlgorithm = SHA224.new() elif hashAlgorithm == 'SHA-2-256': hashAlgorithm = SHA256.new() elif hashAlgorithm == 'SHA-2-384': hashAlgorithm = SHA384.new() elif hashAlgorithm == 'SHA-2-512': hashAlgorithm = SHA512.new() elif hashAlgorithm == 'SHA-3-224': hashAlgorithm = SHA3_224.new() elif hashAlgorithm == 'SHA-3-256': hashAlgorithm = SHA3_256.new() elif hashAlgorithm == 'SHA-2-384': hashAlgorithm = SHA3_384.new() elif hashAlgorithm == 'SHA-2-256': hashAlgorithm = SHA3_512.new() else: raise Exception("Invalid hash function: " + hashAlgorithm) data = open(originalFile, "rb").read() hashAlgorithm.update(data) assert verifier.verify(hashAlgorithm, signature) print("SIGNATURE TEST SUCCESSFUL!!")
def testSeal_verification(signatureFile, envelopeFile, pubFile): pubKeyL, n, e = readPublicKey(pubFile) public_key = RSA.construct((n, e)) verifier = PKCS1_v1_5.new(public_key) fileName, hashed, key, signature = readSignature(signatureFile) (hashing, hashingKeyL) = hashed (enc, encKeyL) = key assert enc == 'RSA' assert encKeyL == pubKeyL hashAlgorithm = hashing + "-" + str(hashingKeyL) if hashAlgorithm == 'SHA-2-224': hashAlgorithm = SHA224.new() elif hashAlgorithm == 'SHA-2-256': hashAlgorithm = SHA256.new() elif hashAlgorithm == 'SHA-2-384': hashAlgorithm = SHA384.new() elif hashAlgorithm == 'SHA-2-512': hashAlgorithm = SHA512.new() elif hashAlgorithm == 'SHA-3-224': hashAlgorithm = SHA3_224.new() elif hashAlgorithm == 'SHA-3-256': hashAlgorithm = SHA3_256.new() elif hashAlgorithm == 'SHA-2-384': hashAlgorithm = SHA3_384.new() elif hashAlgorithm == 'SHA-2-256': hashAlgorithm = SHA3_512.new() else: raise Exception("Invalid hash function: " + hashAlgorithm) fileName, simConf, rsaConf, data, cryptKey, mode, iv = readEnvelope( envelopeFile) hashAlgorithm.update(data + cryptKey) assert verifier.verify(hashAlgorithm, signature) print("SEAL SIGNATURE TEST SUCCESSFUL!!")
def getkey(header): h = SHA224.new() h.update(header) digestsha224 = h.digest() key = [None] * 16 for i in range(14): key[i] = digestsha224[i * 2] key[14] = digestsha224[len(digestsha224) - 3] key[15] = digestsha224[len(digestsha224) - 1] return ''.join(key)
def create_digest(alg): if alg == 'sha256': h = SHA256.new() elif alg == 'sha224': h = SHA224.new() elif alg == 'sha384': h = SHA384.new() elif alg == 'sha512': h = SHA512.new() else: raise ValueError("unexpected hash algorithm") return h
def get_key(password, salt=None, salt1=None, salt2=None, is256=True): #return bytes.fromhex(SHA256.new(password.encode("utf8")).hexdigest()) if (is256): h = SHA256.new() else: h = SHA224.new() h.update(password.encode("utf8")) if (salt): h.update(salt.encode("utf8")) if (salt1): h.update(salt1.encode("utf8")) if (salt2): h.update(salt2.encode("utf8")) return h.hexdigest()
def on_get(self, req, resp): """Handles GET requests""" token = '{}@{}@{}'.format( req.remote_addr, int(time()), SHA224.new(Random.new().read(64)).hexdigest(), ) challenge = self.pub.encrypt(token.encode(), '0')[0] challenge = base64.b64encode(challenge).decode() resp.body = json.dumps({ 'challenge': challenge, })
def generate_hash(string, type): if type not in ['SHA1', 'SHA224', 'SHA256', 'SHA384', 'SHA512']: print("unknown type of hash") return if type == 'SHA1': obj = SHA1.new() if type == 'SHA224': obj = SHA224.new() if type == 'SHA256': obj = SHA256.new() if type == 'SHA384': obj = SHA384.new() if type == 'SHA512': obj = SHA512.new() obj.update(string.encode()) return obj.hexdigest()
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}
def hashing(func, str): if func == 0: result = MD5.new(str) return result.hexdigest() if func == 1: result = SHA1.new(str) return result.hexdigest() if func == 2: return SHA256.new(str).hexdigest() if func == 3: result = SHA224.new(str) return result.hexdigest() if func == 4: result = SHA384.new(str) return result.hexdigest() if func == 5: result = SHA512.new(str) return result.hexdigest()
def function(self): if (self.hash == 'keccak'): self.digest = keccak.new(digest_bits=512) self.digest.update(self.text) elif (self.hash == 'SHA224'): self.digest = SHA224.new() self.digest.update(self.text) elif (self.hash == 'SHA256'): self.digest = SHA256.new() self.digest.update(self.text) elif (self.hash == 'SHA384'): self.digest = SHA384.new() self.digest.update(self.text) elif (self.hash == 'SHA512'): self.digest = SHA512.new() self.digest.update(self.text) return self.digest.hexdigest()
def CreateMessageDigest(message, digest_method): if digest_method == "SHA-1": digest = SHA.new() elif digest_method == "SHA-2-224": digest = SHA224.new() elif digest_method == "SHA-2-256": digest = SHA256.new() elif digest_method == "SHA-2-384": digest = SHA384.new() elif digest_method == "SHA-2-512": digest = SHA512.new() message = str(message) print "Message to digest: " + message digest.update(message) print "Digested message: " + digest.hexdigest() print "" return digest.hexdigest()
def verify_sign(public_key_loc, signature, data): ''' Verifies with a public key from whom the data came that it was indeed signed by their private key param: public_key_loc Path to public key param: signature String signature to be verified return: Boolean. True if the signature is valid; False otherwise. ''' from Crypto.PublicKey import RSA from Crypto.Signature import PKCS1_v1_5 from Crypto.Hash import SHA224 from base64 import b64decode pub_key = open(public_key_loc, "r").read() rsakey = RSA.importKey(pub_key) signer = PKCS1_v1_5.new(rsakey) digest = SHA224.new() # Assumes the data is base64 encoded to begin with digest.update(data) if signer.verify(digest, b64decode(signature)): return True return False
def get_hash_instance(type_): """Given a hash type code, returns a new hash instance for that type. """ if type_ == 1: return MD5.new() elif type_ == 2: return SHA.new() elif type_ == 3: return RIPEMD.new() elif type_ == 8: return SHA256.new() elif type_ == 9: return SHA384.new() elif type_ == 10: return SHA512.new() elif type_ == 11: return SHA224.new() else: raise UnsupportedDigestAlgorithm(type_)
def getHashValue(toHash: str, hashSize: int) -> str: if hashSize == 256: newHash = SHA256.new() newHash.update(toHash.encode('utf-8')) return newHash.hexdigest() elif hashSize == 224: newHash = SHA224.new() newHash.update(toHash.encode('utf-8')) return newHash.hexdigest() elif hashSize == 384: newHash = SHA384.new() newHash.update(toHash.encode('utf-8')) return newHash.hexdigest() elif hashSize == 512: newHash = SHA512.new() newHash.update(toHash.encode('utf-8')) return newHash.hexdigest() elif hashSize == 160: newHash = sha1(toHash.encode('utf-8')) return newHash.hexdigest() else: raise TypeError("Invalid Hash Size")
def identify_hash(self, hash2use): """ Identify type of cryptographic hashing to use for processing. :param hash2use: Value indicating type of hashing desired based upon user's input :return: No explicit value returned. Variables set for further processing. """ if hash2use == 1: self.h = RIPEMD.new() self.hstr = 'ripemd160' elif hash2use == 2: self.h = SHA224.new() self.hstr = 'sha224' elif hash2use == 3: self.h = SHA256.new() self.hstr = 'sha256' elif hash2use == 4: self.h = SHA384.new() self.hstr = 'sha384' elif hash2use == 5: self.h = SHA512.new() self.hstr = 'sha512'
def return_alg(k): """ @type k: str, unicode @return: @raise: """ if k == 'HMAC': return HMAC.new("kjhfsd") elif k == 'MD4': return MD4.new() elif k == 'MD5': return MD5.new() elif k == 'RIPEMD': return RIPEMD.new() elif k == 'SHA': return SHA.new() elif k == 'SHA224': return SHA224.new() elif k == 'SHA256': return SHA256.new() elif k == 'SHA384': return SHA384.new() elif k == 'SHA512': return SHA512.new()
from Crypto.Hash import SHA512 from Crypto.Hash import SHA384 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
#!/usr/bin/python3 from Crypto.Hash import SHA512, MD5, SHA224 msg0 = "Harry Porter" msg1 = "Alice in Wonderland" #hash directly on messages h512 = SHA512.new( msg0.encode()) #.new() initiaze a hash object; input should be byte string h224 = SHA224.new(msg0.encode()) h5 = MD5.new(msg0.encode()) #hash serveral messages sequentially. mh5 = MD5.new() mh5.update(msg0.encode()) # msg0 is hashed. mh5.update(msg1.encode()) # now msg0+msg1 is hashed. print("SHA512({})={}".format(msg0, h512.hexdigest())) print("SHA224({})={}".format(msg0, h224.hexdigest())) print("MD5({})={}".format(msg0, h5.hexdigest())) print("MD5({})={}".format(msg0 + msg1, mh5.hexdigest()))
def digest(algorithm=_DEFAULT_HASH_ALGORITHM, hash_library=_DEFAULT_HASH_LIBRARY): """ <Purpose> Provide the caller with the ability to create digest objects without having to worry about hash library availability or which library to use. The caller also has the option of specifying which hash algorithm and/or library to use. # Creation of a digest object using defaults # or by specifying hash algorithm and library. digest_object = tuf.hash.digest() digest_object = tuf.hash.digest('sha384') digest_object = tuf.hash.digest('pycrypto') # The expected interface for digest objects. digest_object.digest_size digest_object.hexdigest() digest_object.update('data') digest_object.digest() # Added hash routines by this module. digest_object = tuf.hash.digest_fileobject(file_object) digest_object = tuf.hash.digest_filename(filename) <Arguments> algorithm: The hash algorithm (e.g., md5, sha1, sha256). hash_library: The library providing the hash algorithms (e.g., pycrypto, hashlib). <Exceptions> tuf.UnsupportedAlgorithmError tuf.UnsupportedLibraryError <Side Effects> None. <Returns> Digest object (e.g., hashlib.new(algorithm) or algorithm.new() # pycrypto). """ # Was a hashlib digest object requested and is it supported? # If so, return the digest object. if hash_library == 'hashlib' and hash_library in _supported_libraries: try: return hashlib.new(algorithm) except ValueError: raise tuf.UnsupportedAlgorithmError(algorithm) # Was a pycrypto digest object requested and is it supported? elif hash_library == 'pycrypto' and hash_library in _supported_libraries: # Pycrypto does not offer a comparable hashlib.new(hashname). # Let's first check the 'algorithm' argument before returning # the correct pycrypto digest object using pycrypto's object construction. if algorithm == 'md5': return MD5.new() elif algorithm == 'sha1': return SHA.new() elif algorithm == 'sha224': return SHA224.new() elif algorithm == 'sha256': return SHA256.new() elif algorithm == 'sha384': return SHA384.new() elif algorithm == 'sha512': return SHA512.new() else: raise tuf.UnsupportedAlgorithmError(algorithm) # The requested hash library is not supported. else: raise tuf.UnsupportedLibraryError('Unsupported library requested. ' 'Supported hash libraries: '+str(_SUPPORTED_LIB_LIST))
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) text = des.decrypt(cipher_text) print(cipher_text, text) #############################3
def compute_hash(self, key, byte_stream): """"compute file hash""" h = SHA224.new() h.update(key) h.update(byte_stream) return h.hexdigest()
def _sha224_new(*args): from Crypto.Hash import SHA224 _new_funcs['SHA224'] = _new_funcs['sha224'] = SHA224.new return SHA224.new(*args)
def challenge(offer): h = SHA224.new() h.update(str(offer).encode()) return int(h.hexdigest(),16)
def get_sha224(self): hash_obj = SHA224.new(data=self.value) return { "digest": hash_obj.digest(), "hexdigets": hash_obj.hexdigest() }
##https://github.com/dlitz/pycrypto/blob/master/lib/Crypto/Hash/SHA224.py from Crypto.Hash import SHA224 h = SHA224.new() h.update(b'Hello') print h.hexdigest()
def main(): cliParser = ArgumentParser(description="RSA encryption Tool") subparsers = cliParser.add_subparsers(help='sub-command help', dest='command') # Add subparser parserEncrypt = subparsers.add_parser('encrypt', help='RSA encrypt') parserDecrypt = subparsers.add_parser('decrypt', help='RSA Decrypt') parserSign = subparsers.add_parser('sign', help='RSA Sign') parserVerify = subparsers.add_parser('verify', help='RSA Verify') # add arg to Encrypt parserEncrypt.add_argument('-pub', '--public', help='Public Key', required=True) parserEncrypt.add_argument('-i', '--input', help="Input Clear text", required=True) # add arg to Decrypt parserDecrypt.add_argument('-pri', '--private', help='Private Key', required=True) parserDecrypt.add_argument('-i', '--input', help="Input Cipher text", required=True) # add arg to Sign parserSign.add_argument('-pri', '--private', help='Private Key', required=True) parserSign.add_argument('-b', '--base64', help="Base64 Decode", action='store_true') parserSign.add_argument('-u', '--url', help="URL Decode", action='store_true') parserSign.add_argument( '-hh', '--hash', help="hash function {md5, sha-1, sha-224, sha-256, sha-384, sha-512}", required=True) parserSign.add_argument('-i', '--input', help="Input Clear text", required=True) # add arg to Verify parserVerify.add_argument('-pub', '--public', help='Public Key', required=True) parserVerify.add_argument('-b', '--base64', help="Base64 Decode", action='store_true') parserVerify.add_argument('-u', '--url', help="URL Decode", action='store_true') parserVerify.add_argument('-i', '--input', help="Input Signature text", required=True) cliParser.add_argument('-v', '--version', action='version', version='RSA Tool {} - M4rK0v'.format(VERSION), help='Version of this tool') args = cliParser.parse_args() # Load input try: inputFile = open(args.input, 'rb') except (FileExistsError, FileNotFoundError) as e: print(e) return -1 input = inputFile.read() input = input.strip() # check to do encrypt if args.command == 'encrypt': try: key = loadKey(args.public) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 pubKey = PKCS1_v1_5.new(key) cipher = key.encrypt(input, 32)[0] print("[+] Cipher Text:") print(base64.b64encode(cipher)) # check to elif args.command == 'decrypt': try: key = loadKey(args.private) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 cipher = base64.b64decode(input) clearText = key.decrypt(cipher) print("[+] Clear Text:") print(clearText) elif args.command == 'sign': try: key = loadKey(args.private) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 keySign = PKCS1_v1_5.new(key) if args.hash: if args.hash.lower() == 'md5': digest = MD5.new() elif args.hash.lower() == 'sha-1': digest = SHA.new() elif args.hash.lower() == 'sha-224': digest = SHA224.new() elif args.hash.lower() == 'sha-256': digest = SHA256.new() elif args.hash.lower() == 'sha-384': digest = SHA384.new() elif args.hash.lower() == 'SHA-512': digest = SHA512.new() else: print("[!] Hash algorithm not found.") return 0 digest.update(input) sign = keySign.sign(digest) print("[+] Hex Formart:") print(codecs.getencoder('hex')(sign)) # check if encode base64 if args.base64: signBase64 = base64.b64encode(sign) print("[+] Base64 format:") print(signBase64) # check if encode url if args.url: signURL = UrlEncode(signBase64) print("[+] URL encoded:") print(signURL) else: return -1 elif args.command == 'verify': try: key = loadKey(args.public) except (FileNotFoundError, FileExistsError) as e: print("[!] Key file not found.") return 0 except (ValueError, TypeError, IndexError) as e: print("[!] Key has improper format.") return 0 # Check to decode URL if args.url: input = UrlDecode(input.decode()) # Check to decode Base64 if args.base64: input = base64.b64decode(input) # Convert Input Bytes to Long sigLong = number.bytes_to_long(input) clearSigLong = pow(sigLong, key.e, key.n) # Convert clear Sign Long to Bytes clearSigByte = number.long_to_bytes(clearSigLong) print(codecs.getencoder('hex')(clearSigByte)) hashArg, clearSig = removePadding(clearSigByte) if hashArg == -1 or clearSig == -1: print("[!] Error! in remove padding.") else: print("[+] Hash algorithm: {}".format(hashArg)) print("[+] Clear Signature: ") print(codecs.getencoder('hex')(clearSig))
def sha224(self,data): h=SHA224.new() h.update(data) return h.hexdigest()
def Hash2(key): key = key + str(HASH2_RAND) h = SHA224.new() h.update(key) v = number.bytes_to_long(h.digest()) return v
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()))
def cmd_asydns(url, generate, revoke, verbose): """Requests a DNS domain name based on public and private RSA keys using the AsyDNS protocol https://github.com/portantier/asydns Example: \b $ habu.asydns -v Generating RSA key ... Loading RSA key ... { "ip": "181.31.41.231", "name": "07286e90fd6e7e6be61d6a7919967c7cf3bbfb23a36edbc72b6d7c53.a.asydns.org" } \b $ dig +short 07286e90fd6e7e6be61d6a7919967c7cf3bbfb23a36edbc72b6d7c53.a.asydns.org 181.31.41.231 """ if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') homedir = Path(pwd.getpwuid(os.getuid()).pw_dir) dotdir = homedir / '.asydns' dotdir.mkdir(exist_ok=True) pub_file = dotdir / 'rsa.pub' key_file = dotdir / 'rsa.key' if generate or not key_file.is_file(): logging.info('Generating RSA key ...') random_generator = Random.new().read key = RSA.generate(2048, random_generator) pub = key.publickey() with key_file.open('w') as k: k.write(key.exportKey('PEM').decode()) with pub_file.open('w') as p: p.write(pub.exportKey('PEM').decode()) logging.info('Loading RSA key ...') with key_file.open() as k: key = RSA.importKey(k.read()) with pub_file.open() as p: pub = RSA.importKey(p.read()) r = requests.get(url + '/api') if r.status_code != 200: logging.error('Error') logging.error(r.content.decode()) return False j = r.json() challenge = base64.b64decode(j['challenge']) signer = PKCS1_v1_5.new(key) response = signer.sign(SHA224.new(challenge)) response = base64.b64encode(response).decode() if revoke: r = requests.delete(url + '/api', json={'pub': pub.exportKey('PEM').decode(), 'challenge' : j['challenge'], 'response': response}) else: r = requests.post(url + '/api', json={'pub': pub.exportKey('PEM').decode(), 'challenge' : j['challenge'], 'response': response}) if r.status_code != 200: logging.error('Error') logging.error(r.content.decode()) return False print(json.dumps(r.json(), indent=4)) return True
def hash_doc(doc): return SHA224.new(doc)
def writeHash(password, salt): hashes = {} hashes[password] = "Plain-text" hashes[urllib.quote(password, safe='')] = "URL Encoded" hashes[password.encode("hex")] = "Hex" hashes[base64.b16encode(password)] = "Base16" hashes[base64.b32encode(password)] = "Base32" hashes[base64.b64encode(password)] = "Base64" hashes[base64.b64encode(salt + ":" + password)] = "Basic Auth" hashes[base64.b64encode(MD5.new(password).digest())] = "md5" hashes[base64.b64encode(MD5.new(password + salt).digest())] = "md5+salt" hashes[base64.b64encode(MD5.new(salt + password).digest())] = "salt+md5" hashes[base64.b64encode(HMAC.new( password, salt, SHA).digest())] = "hmac-sha1; key=password" hashes[base64.b64encode(HMAC.new(salt, password, SHA).digest())] = "hmac-sha1; key=salt" hashes[base64.b64encode(HMAC.new( password, salt, SHA256).digest())] = "hmac-sha256; key=password" hashes[base64.b64encode(HMAC.new( salt, password, SHA256).digest())] = "hmac-sha256; key=salt" hashes[base64.b64encode(HMAC.new( password, salt, SHA512).digest())] = "hmac-sha512; key=password" hashes[base64.b64encode(HMAC.new( salt, password, SHA512).digest())] = "hmac-sha512; key=salt" hashes[base64.b64encode(SHA.new(password).digest())] = "sha1" hashes[base64.b64encode(SHA224.new(password).digest())] = "sha224" hashes[base64.b64encode(SHA256.new(password).digest())] = "sha256" hashes[base64.b64encode(SHA512.new(password).digest())] = "sha512" hashes[base64.b64encode(SHA.new(password + salt).digest())] = "sha1+salt" hashes[base64.b64encode(SHA224.new(password + salt).digest())] = "sha224+salt" hashes[base64.b64encode(SHA256.new(password + salt).digest())] = "sha256+salt" hashes[base64.b64encode(SHA512.new(password + salt).digest())] = "sha512+salt" hashes[base64.b64encode(SHA.new(salt + password).digest())] = "salt+sha1" hashes[base64.b64encode(SHA224.new(salt + password).digest())] = "salt+sha224" hashes[base64.b64encode(SHA256.new(salt + password).digest())] = "salt+sha256" hashes[base64.b64encode(SHA512.new(salt + password).digest())] = "salt+sha512" hashes[base64.b64encode(MD4.new(password).digest())] = "md4" hashes[MD5.new(password).hexdigest()] = "md5" hashes[MD5.new(password + salt).hexdigest()] = "md5+salt" hashes[MD5.new(salt + password).hexdigest()] = "salt+md5" hashes[HMAC.new(password, salt, SHA).hexdigest()] = "hmac-sha1; key=password" hashes[HMAC.new(salt, password, SHA).hexdigest()] = "hmac-sha1; key=salt" hashes[HMAC.new(password, salt, SHA256).hexdigest()] = "hmac-sha256; key=password" hashes[HMAC.new(salt, password, SHA256).hexdigest()] = "hmac-sha256; key=salt" hashes[HMAC.new(password, salt, SHA512).hexdigest()] = "hmac-sha512; key=password" hashes[HMAC.new(salt, password, SHA512).hexdigest()] = "hmac-sha512; key=salt" hashes[SHA.new(password).hexdigest()] = "sha1" hashes[SHA224.new(password).hexdigest()] = "sha224" hashes[SHA256.new(password).hexdigest()] = "sha256" hashes[SHA512.new(password).hexdigest()] = "sha512" hashes[SHA.new(password + salt).hexdigest()] = "sha1+salt" hashes[SHA224.new(password + salt).hexdigest()] = "sha224+salt" hashes[SHA256.new(password + salt).hexdigest()] = "sha256+salt" hashes[SHA512.new(password + salt).hexdigest()] = "sha512+salt" hashes[SHA.new(salt + password).hexdigest()] = "salt+sha1" hashes[SHA224.new(salt + password).hexdigest()] = "salt+sha224" hashes[SHA256.new(salt + password).hexdigest()] = "salt+sha256" hashes[SHA512.new(salt + password).hexdigest()] = "salt+sha512" hashes[MD4.new(password).hexdigest()] = "md4" hashes[passlib.hash.mysql323.hash(password)] = "mysql323" hashes[passlib.hash.mysql41.hash(password)] = "mysql41" hashes[passlib.hash.mssql2005.hash(password).split("x")[1]] = "mssql2005" hashes[passlib.hash.mssql2000.hash(password).split("x")[1]] = "mssql2000" hashes[passlib.hash.md5_crypt.hash(password)] = "md5crypt (unix)" hashes[passlib.hash.nthash.hash(password)] = "nt" return hashes
def main(): server = False for arg in sys.argv: if arg == "-s": server = True print "" print " ==============================================" print " Multitun " + MT_VERSION print " By Joshua Davis (multitun -*- covert.codes)" print " http://covert.codes" print " Copyright(C) 2014" print " Released under the GNU General Public License" print " ==============================================" print "" config = INIConfig(open(configfile)) log_file = config.all.log_file serv_addr = config.all.serv_addr serv_port = config.all.serv_port ws_loc = config.all.ws_loc tun_nm = config.all.tun_nm tun_mtu = config.all.tun_mtu password = config.all.password log.startLogging(sys.stdout) log.startLogging(open(log_file, 'w+')) if len(password) == 0: log.msg("Edit the configuration file to include a password", logLevel=logging.WARN) sys.exit(EXIT_ERR) if len(password) > PW_LEN: password = password[:PW_LEN] password = password.ljust(PW_LEN, '0') key = SHA224.new(data=password).digest()[:KEYLEN] if server == True: tun_dev = config.server.tun_dev tun_addr = config.server.tun_addr tun_client_addr = config.client.tun_addr webdir = config.server.webdir log.msg("Starting multitun as a server", logLevel=logging.INFO) logstr = ("Server listening on port %s") % (serv_port) log.msg(logstr, logLevel=logging.INFO) server = Server(serv_addr, serv_port, ws_loc, tun_dev, tun_addr, tun_client_addr, tun_nm, tun_mtu, webdir, key) else: # server != True serv_addr = config.all.serv_addr serv_port = config.all.serv_port tun_dev = config.client.tun_dev tun_addr = config.client.tun_addr tun_serv_addr = config.server.tun_addr log.msg("Starting multitun as a client", logLevel=logging.INFO) logstr = ("Forwarding to %s:%s") % (serv_addr, int(serv_port)) log.msg(logstr, logLevel=logging.INFO) client = Client(serv_addr, serv_port, ws_loc, tun_dev, tun_addr, tun_serv_addr, tun_nm, tun_mtu, key)
def cmd_asydns(url, generate, revoke, verbose): if verbose: logging.basicConfig(level=logging.INFO, format='%(message)s') homedir = Path(pwd.getpwuid(os.getuid()).pw_dir) dotdir = homedir / '.asydns' dotdir.mkdir(exist_ok=True) pub_file = dotdir / 'rsa.pub' key_file = dotdir / 'rsa.key' if generate or not key_file.is_file(): logging.info('Generating RSA key ...') random_generator = Random.new().read key = RSA.generate(2048, random_generator) pub = key.publickey() with key_file.open('w') as k: k.write(key.exportKey('PEM').decode()) with pub_file.open('w') as p: p.write(pub.exportKey('PEM').decode()) logging.info('Loading RSA key ...') with key_file.open() as k: key = RSA.importKey(k.read()) with pub_file.open() as p: pub = RSA.importKey(p.read()) r = requests.get(url + '/api') if r.status_code != 200: logging.error('Error') logging.error(r.content.decode()) return False j = r.json() challenge = base64.b64decode(j['challenge']) signer = PKCS1_v1_5.new(key) response = signer.sign(SHA224.new(challenge)) response = base64.b64encode(response).decode() if revoke: r = requests.delete(url + '/api', json={ 'pub': pub.exportKey('PEM').decode(), 'challenge': j['challenge'], 'response': response }) else: r = requests.post(url + '/api', json={ 'pub': pub.exportKey('PEM').decode(), 'challenge': j['challenge'], 'response': response }) if r.status_code != 200: logging.error('Error') logging.error(r.content.decode()) return False print(json.dumps(r.json(), indent=4)) return True