Exemple #1
0
 def get_password_hash(self, password_hash, one_time_salt, data=None):
     password_hash = crypto.hash(
         crypto.from_string(password_hash),
         crypto.from_string(one_time_salt),
     )
     if data is not None:
         password_hash = crypto.hash(data, password_hash)
     return crypto.to_string(password_hash)
Exemple #2
0
 def authenticate(self, request, user, salt, one_time_salt, password_hash, data=None):
     password = crypto.parse_password(user.password)
     try:
         session_one_time_salt = request.session['one_time_salt']
     except KeyError:
         return
     if crypto.from_string(session_one_time_salt) == one_time_salt and password['salt'] == salt:
         valid_password_hash = crypto.hash(password['hash'], one_time_salt)
         if data:
             valid_password_hash = crypto.hash(data, valid_password_hash)
         if crypto.constant_time_compare(valid_password_hash, password_hash):
             request.user = user
             return user
def verifySignature(m, signature, publicKey):
    """
    Verify a type 0 signature over m

    @param m: binary message
    @type m: string
    @param signature: The OpenPGP signature over m.
    @type signature: SignatureMessage
    @param publicKey: The public key of the signer.
    @type publicKey: PublicKeyMessage
    @return: Returns true if the signature is valid.
    """

    data = (m + signature.packets[TAG_SIGNATURE].hashdata())
    plainhash = crypto.hash(
        data,
        signature.packets[TAG_SIGNATURE].hashAlgorithm.value)
    if signature.packets[TAG_SIGNATURE].hashLeftTwo != plainhash[0:2]:
        return False

    codedhash = encoding.pkcs15(
        plainhash,
        publicKey.packets[TAG_PUBKEY].n.bits(),
        signature.packets[TAG_SIGNATURE].hashAlgorithm.value)
    codedhashInt = elements.ScalarElement(codedhash).value
    
    rsaN = publicKey.packets[TAG_PUBKEY].n.value
    rsaE = publicKey.packets[TAG_PUBKEY].e.value
    return crypto.rsaVerify(signature.packets[TAG_SIGNATURE].sig.value,
                            codedhashInt, rsaE, rsaN)
Exemple #4
0
def calculate_hash(message):
	hash_type = None
	if HASH_TYPE in message:
		hash_type = message[HASH_TYPE]
	m = plain(message)
	h = crypto.hash(m, hash_type)
	return h
Exemple #5
0
    def report(self, reporting_user, send_user, ts, ctxt, fbtag, msg):
        fbtag = binascii.unhexlify(fbtag)
        assert fbtag == self._gen_fbtag(ctxt, send_user, reporting_user,
                                        int(ts)), "fake report"

        ctxt = binascii.unhexlify(ctxt)
        msg = binascii.unhexlify(msg)
        crypto.validate_outer_commitment(ctxt, msg)

        (mid, km, hcm, _) = crypto.split_outer_message(msg)
        cm = binascii.unhexlify(self.get_msg(mid))
        assert crypto.hash(cm) == hcm, "bad message hash"
        message = crypto.decrypt_inner(km, cm)

        # The actual abuse check:
        if b"abuse" in message.lower():
            if send_user == self._client:
                self._should_exit = True
                return b"You are banned for sending 'abuse'"

            return b"Thank you for reporting 'abuse'!"
        else:
            if reporting_user != self._client and send_user == self._client:
                with open('flag', 'rb') as f:
                    self._should_exit = True
                    return (b"You were erroneously reported for 'abuse', "
                            b"here's a consolation prize: %s" % f.read())
            return b"This message does not contain 'abuse'."
Exemple #6
0
    def send(self, msg, *users):
        km, cm = crypto.encrypt_inner(msg)
        mid = self.server.put_msg(binascii.hexlify(cm))
        hcm = crypto.hash(cm)

        for user in users:
            self._send_ctxt(mid, km, hcm, user)
Exemple #7
0
def getpswd(DB, site, mpswd):
	if crypto.hash(mpswd) == DB.mpswd:
		login , pswd = DB.DB[site]
		return (login, crypto.decrypt(pswd, mpswd))
	else:
		raise PasswordError("Password didn't math!")
		return 0
 def generateKey(self, passphrase, algorithm):
     if self.specifier == 0:
         raise Exception('not implemented')
     elif self.specifier == 1:
         raise Exception('not implemented')
     elif self.specifier == 3:
         hashdata = ''
         m = self.salt + passphrase
         bytes = 0
         while bytes < self.count:
             for i in range(0, len(m)):
                 hashdata += m[i]
                 bytes += 1
                 if bytes == self.count:
                     break
         self.key = crypto.hash(hashdata, self.hashalgorithm)
         if len(self.key) < crypto.SYMALGORITHM_KEYSIZE[algorithm]:
             self.key += crypto.hash('\x00' + hashdata, self.hashalgorithm)
     else:
         raise Exception('invalid s2k specifier')
     return self.key[:crypto.SYMALGORITHM_KEYSIZE[algorithm]]
Exemple #9
0
 def authenticate(self,
                  request,
                  user,
                  salt,
                  one_time_salt,
                  password_hash,
                  data=None):
     password = crypto.parse_password(user.password)
     try:
         session_one_time_salt = request.session['one_time_salt']
     except KeyError:
         return
     if crypto.from_string(session_one_time_salt
                           ) == one_time_salt and password['salt'] == salt:
         valid_password_hash = crypto.hash(password['hash'], one_time_salt)
         if data:
             valid_password_hash = crypto.hash(data, valid_password_hash)
         if crypto.constant_time_compare(valid_password_hash,
                                         password_hash):
             request.user = user
             return user
Exemple #10
0
    def compute_merkle_root(self):
        n = len(self.transactions)
        depth = math.ceil(math.log2(n))
        s = self.transactions
        q = queue.SimpleQueue()
        for x in s:
            q.put(hash(x))

        for _ in range(depth):
            length = q.qsize()
            width = math.floor(length / 2) + (length % 2)
            for _ in range(width):
                if length == 1:
                    a = q.get()
                    q.put(a)
                    length -= 1
                else:
                    a = q.get()
                    b = q.get()
                    q.put(hash(str(a) + str(b)))
                    length -= 2

        return q.get()
Exemple #11
0
 def mint(self, Node, lastBlock, stop):
     tx = chr(random.randint(1, 100))
     mroot = hashlib.sha256(tx).hexdigest()
     timestamp = str(datetime.datetime.now())
     c_header = str(lastBlock.hash) + mroot + timestamp
     keys = Node.keys()
     signature = crypto.sign(
         str(lastBlock.index + 1) + str(lastBlock.hash), keys)
     hash_result = crypto.hash(str(c_header))
     if stop.is_set():
         return False, False, False, False
     elected = self.election(Node, lastBlock)
     if elected:
         return block.Block(lastBlock.index + 1, lastBlock.hash, keys,
                            signature, hash_result)
Exemple #12
0
 def execute(self, args, debug=False):
     print "ARRRGHS",args
     self.args = copy.deepcopy(args)
     signature  = args.pop()
     print signature
     if crypto.hash("".join(map(str, args))) != signature.hash():
         self.nextTxn = Invalid()
         return
     # args[0] - prooflist for mRootHash
     # args[1] - list of branches to Execute
     ret = merkleVerifyExec(signature, self.mRootHash, args, self.amt, debug=debug) # defines ret when executing, pass all args
     if not ret:
         raise ValueError("Invalid ret")
     print ret
     self._nextTxn = self.verify(ret)
Exemple #13
0
 def execute(self, args, debug=False):
     print "ARRRGHS", args
     self.args = copy.deepcopy(args)
     signature = args.pop()
     print signature
     if crypto.hash("".join(map(str, args))) != signature.hash():
         self.nextTxn = Invalid()
         return
     # args[0] - prooflist for mRootHash
     # args[1] - list of branches to Execute
     ret = merkleVerifyExec(
         signature, self.mRootHash, args, self.amt, debug=debug
     )  # defines ret when executing, pass all args
     if not ret:
         raise ValueError("Invalid ret")
     print ret
     self._nextTxn = self.verify(ret)
Exemple #14
0
    def recv(self):
        lines = self.server.recv(self.uid)
        msgs = []
        for line in lines:
            who, ts, msg, fbtag = line.split(b" ")
            msgs.append(
                (who, int(ts), binascii.unhexlify(msg), binascii.unhexlify(fbtag))
            )
        out = []
        for (who, ts, ctxt, fbtag) in msgs:
            msg = crypto.decrypt_outer(ctxt, self._priv_key)

            (mid, km, hcm, _) = crypto.split_outer_message(msg)
            cm = binascii.unhexlify(self.server.get_msg(mid))
            assert crypto.hash(cm) == hcm, "bad message hash"
            m = crypto.decrypt_inner(km, cm)

            self._all_messages[who].append((mid, ts, ctxt, msg, fbtag))
            out.append((who, mid, m))

        return out
Exemple #15
0
def blind(publicKey, sigTime, data):
    keyID = publicKey.packets[TAG_PUBKEY].keyID()
    n = publicKey.packets[TAG_PUBKEY].n
    e = publicKey.packets[TAG_PUBKEY].e

    if sigTime is None:
        sigTime = _randomTime(publicKey.creationTime(), publicKey.expirationTime())

    sigPacket = _prepareSignature(crypto.HASH_SHA256, sigTime, keyID)
    sigdata = data + sigPacket.hashdata()
    plainhash = crypto.hash(sigdata, sigPacket.hashAlgorithm.value)
    codedhash = encoding.pkcs15(plainhash, n.bits(), sigPacket.hashAlgorithm.value)
    m = elements.ScalarElement(codedhash).value

    while True:
        r = elements.ScalarElement(crypto.randomBytes(n.octets())).value
        if r > 1 and r < n.value and crypto.gcd(n.value, r) == 1:
            break

    packet = packets.BlindMessagePacket()
    packet.m = elements.MPIElement(crypto.rsaBlind(m, r, e.value, n.value))
    return r, plainhash[0:2], sigTime, messages.BlindMessageMessage.fromPackets((packet,))
Exemple #16
0
def computeSignature(m, secretKey):
    """
    Compute a type 0 signature.

    @param m: Message of binary data to sign.
    @type m: string
    @param secretKey: Key used for signature.
    @type secretKey: SecretKeyMessage
    @return: An OpenPGP signature message.
    """
    sigPacket = packets.SignaturePacket()
    sigPacket.version = elements.ScalarElement(4)
    sigPacket.signatureType = elements.ScalarElement(0)
    sigPacket.pubAlgorithm = elements.ScalarElement(1)
    sigPacket.hashAlgorithm = elements.ScalarElement(crypto.HASH_SHA256)
    sigPacket.hashedSubpackets.add(subpackets.CreationTimeSubpacket(
            elements.TimeElement.now()))
    sigPacket.subpackets.add(
        subpackets.IssuerSubpacket(secretKey.packets[TAG_SECKEY].keyID()))
    data = (m + sigPacket.hashdata())
    plainhash = crypto.hash(data, sigPacket.hashAlgorithm.value)
    sigPacket.hashLeftTwo = plainhash[0:2]

    codedhash = encoding.pkcs15(
        plainhash,
        secretKey.packets[TAG_SECKEY].n.bits(),
        sigPacket.hashAlgorithm.value)
    codedhashInt = elements.ScalarElement(codedhash).value

    rsaN = secretKey.packets[TAG_SECKEY].n.value
    rsaD = secretKey.packets[TAG_SECKEY].d.value
    s = crypto.rsaSign(codedhashInt, rsaD, rsaN)
    sigPacket.sig = elements.MPIElement(s)

    pgpMessage = messages.SignatureMessage.fromPackets((sigPacket,))
    return pgpMessage
 def _mix_seed(self, for_epoch):
     epoch_number_bytes = for_epoch.to_bytes(32, config.ENDIANNESS)
     mixer = int.from_bytes(crypto.hash(epoch_number_bytes),
                            config.ENDIANNESS)
     return (self.initial_seed * mixer) % crypto.order
Exemple #18
0
def generate_prime(l, r):
    n = random.randint(l, r)
    while not is_prime(n):
        n = random.randint(l, r)
    return n


def generate_keys():
    p = generate_prime(1000, 2000)
    q = generate_prime(2000, 3000)
    assert p != q
    n = p * q
    phi = (p - 1) * (q - 1)
    e = 101
    d = 1
    while (d * e) % phi != 1:
        d += 1
    return PublicKey(e, n), PrivateKey(d, n)


public, private = generate_keys()
wallet = {
    'public_key': public.dumps(),
    'private_key': private.dumps(),
    'address': hash(str(public))
}
o = open('wallet.json', 'w')
print(json.dumps(wallet), file=o)
o.close()
Exemple #19
0
 def verify(self):
     return hash(str(self))[0:4] == "0000"
Exemple #20
0
def testPhase(s):

    print "#" * (len(s) + 12)
    print "#     %s     #" % s
    print "#" * (len(s) + 12)


if __name__ == "__main__":
    testPhase("Verifying Content Behavior")
    IO = io.__IO__()
    IO.push(10)
    IO.push(100)
    IO.heap[1] = 100
    print "Verifying Content Execution"
    __Content__(crypto.hash("IO.heap[100] = 10"),
                'run').verifyAdd("IO.heap[100] = 10").execute(IO)
    assert IO.heap[100] == 10
    print "...Content Executed"
    print "Verifying bad Content Rejection"
    try:
        __Content__("Fail", 'run').verifyAdd("IO.heap[100] = 10").execute(IO)
        raise Exception("Should have failed to verifyAdd")
    except ValueError:
        print "... Bad Content Rejected"
    a = Mast('compile', "print 10")
    a.addBr('print 10').addBr('print 100')
    b = a.addBr('print 10').addBr('print 100')
    b.addBr('print 1000')
    b.addBr('print 1')
    testPhase("Printing Tree from MAST")
Exemple #21
0
 def test_hash(self):
     h = hash(_msg)
     self.assertEqual(h, _hash,
                      'hash does not equal: ' + h + ' != ' + _hash)
Exemple #22
0
        return self._hash
    def __str__(self):
        return "Hash: %s\nMode:%s\nCode:\n\"\"\"\n%s\n\"\"\""%(self.hash().encode('hex'),self.mode, self.code)
def testPhase(s):

    print "#"*(len(s)+12)
    print "#     %s     #"%s
    print "#"*(len(s)+12)
if __name__ == "__main__":
    testPhase("Verifying Content Behavior")
    IO = io.__IO__()
    IO.push(10)
    IO.push(100)
    IO.heap[1] = 100
    print "Verifying Content Execution"
    __Content__(crypto.hash("IO.heap[100] = 10"), 'run').verifyAdd("IO.heap[100] = 10").execute(IO)
    assert IO.heap[100] == 10
    print "...Content Executed"
    print "Verifying bad Content Rejection"
    try:
        __Content__("Fail", 'run').verifyAdd("IO.heap[100] = 10").execute(IO)
        raise Exception("Should have failed to verifyAdd")
    except ValueError:
        print "... Bad Content Rejected"
    a = Mast('compile', "print 10")
    a.addBr('print 10').addBr('print 100')
    b = a.addBr('print 10').addBr('print 100')
    b.addBr('print 1000')
    b.addBr('print 1')
    testPhase("Printing Tree from MAST")
    print a
Exemple #23
0
 def isGood(self):
     return hash(str(self))[0:4] == "0000"
Exemple #24
0
 def get_hash(self, prev_hash):
     return hash(prev_hash + self.transactions_hash + str(self.nonce))
Exemple #25
0
def test():
    b = Block()
    for i in range(13):
        b.add_transaction(i)
    b.mine()
    print(hash(str(b)), b.nonce)
Exemple #26
0
	def __init__(self, mpswd):
		self.mpswd = crypto.hash(mpswd)
		self.DB = {}
Exemple #27
0
def addpswd(DB, site, login, pswd, mpswd):
	if crypto.hash(mpswd) == DB.mpswd:
		DB.DB[site] = (login, crypto.encrypt(pswd, mpswd))
	else:
		raise PasswordError("Password didn't math!")
Exemple #28
0
 def transactions_hash(self):
     input = ''
     for transaction in self.transactions:
         # hash(transaction)
         input += str(transaction)
     return hash(input)
Exemple #29
0
,(OP_RSHIFT,lambda:(InvalidOpcode.rz("OP_RSHIFT"),inst.next()))
,(OP_BOOLAND,lambda:(stack.append(1 if stack.pop() != 0 and stack.pop() != 0 else 0),inst.next()))
,(OP_BOOLOR,lambda:(stack.append(0 if stack.pop() == 0 and stack.pop() == 0 else 1),inst.next()))
,(OP_NUMEQUAL,lambda:(stack.append(1 if stack.pop() == stack.pop() else 0,inst.next())))
,(OP_NUMEQUALVERIFY,lambda:(stack.append(1 if stack.pop() == stack.pop() else 0),OP_VERIFY))
,(OP_NUMNOTEQUAL,lambda:(stack.append(0 if stack.pop() == stack.pop() else 1),inst.next()))
,(OP_LESSTHAN,lambda:(stack.append( 1 if stack.pop() > stack.pop() else 0),inst.next()))
,(OP_GREATERTHAN,lambda:(stack.append(1 if stack.pop() < stack.pop() else 0),inst.next()))
,(OP_LESSTHANOREQUAL,lambda:(stack.append(1 if stack.pop() >= stack.pop() else 0),inst.next()))
,(OP_GREATERTHANOREQUAL,lambda:(stack.append( 1 if stack.pop() <= stack.pop() else 0),inst.next()))
,(OP_MIN,lambda:(stack.append(min(stack.pop(), stack.pop())),inst.next()))
,(OP_MAX,lambda:(stack.append(min(stack.pop(), stack.pop()),inst.next())))
,(OP_WITHIN,lambda:(stack.append( 1 if stack[-2] <= stackstack[-1] < stack[-3] else 0   ), stack.pop(), stack.pop(), stack.pop(),inst.next()))
,(OP_RIPEMD160,lambda:(stack.append(crypto.ripemd160(stack.pop())),inst.next()))
,(OP_SHA1,lambda:(stack.append(crypto.sha1(stack.pop())),inst.next()))
,(OP_SHA256,lambda:(stack.append(crypto.hash(stack.pop())),inst.next()))
,(OP_HASH160,lambda:(stack.append(crypto.ripemd160(crypto.sha256(stack.pop()))),inst.next()))
,(OP_HASH256,lambda:(stack.append(crypto.hash(crypto.hash(stack.pop()))),inst.next()))
,(OP_CODESEPARATOR,lambda:(InvalidOpcode.rz("Implement this plz",inst.next()))) #TODO what does this do?
,(OP_CHECKSIG,lambda:( stack.append(1 if  signed(stack.pop(),stack.pop()) else 0),inst.next()))
,(OP_CHECKSIGVERIFY,lambda:( stack.append(1 if  signed(stack.pop(),stack.pop()) else 0),OP_VERIFY))
,(OP_CHECKMULTISIG,lambda:(None,inst.next())) #TODO
,(OP_CHECKMULTISIGVERIFY,lambda:(None,inst.next())) #TODO
]
# OP_NA
,genHandler(lambda num: lambda: (stack.append("".join([chr(inst.next()) for _ in xrange(num)])), inst.next()), 1, 75)
# OP_int
,genHandler(lambda num: lambda: (stack.append(num-80), inst.next()), 82, 96)
# OP_NOP
,genHandler(lambda _: lambda: (inst.next(),) , 176, 186)))
Exemple #30
0
def test_hash():
    original_data = 'Chainium'
    expected = 'Dp6vNLdUbRTc1Y3i9uSBritNqvqe4es9MjjGrVi1nQMu'
    actual = crypto.hash(original_data.encode())
    assert expected == actual
Exemple #31
0
      (stack.append(1 if stack.pop() <= stack.pop() else 0), inst.next(
      ))),
     (OP_MIN, lambda:
      (stack.append(min(stack.pop(), stack.pop())), inst.next())),
     (OP_MAX, lambda:
      (stack.append(min(stack.pop(), stack.pop()), inst.next()))),
     (OP_WITHIN, lambda:
      (stack.append(1
                    if stack[-2] <= stackstack[-1] < stack[-3] else 0),
       stack.pop(), stack.pop(), stack.pop(), inst.next())),
     (OP_RIPEMD160, lambda:
      (stack.append(crypto.ripemd160(stack.pop())), inst.next())),
     (OP_SHA1, lambda:
      (stack.append(crypto.sha1(stack.pop())), inst.next())),
     (OP_SHA256, lambda:
      (stack.append(crypto.hash(stack.pop())), inst.next())),
     (OP_HASH160, lambda: (stack.append(
         crypto.ripemd160(crypto.sha256(stack.pop()))), inst.next())),
     (OP_HASH256, lambda: (stack.append(
         crypto.hash(crypto.hash(stack.pop()))), inst.next())),
     (OP_CODESEPARATOR, lambda: (InvalidOpcode.rz(
         "Implement this plz", inst.next())))  #TODO what does this do?
     ,
     (OP_CHECKSIG, lambda: (stack.append(1 if signed(
         stack.pop(), stack.pop()) else 0), inst.next())),
     (OP_CHECKSIGVERIFY, lambda: (stack.append(1 if signed(
         stack.pop(), stack.pop()) else 0), OP_VERIFY)),
     (OP_CHECKMULTISIG, lambda: (None, inst.next()))  #TODO
     ,
     (OP_CHECKMULTISIGVERIFY, lambda: (None, inst.next()))  #TODO
 ]
sys.path.append(os.path.join(base, '../src'))

import collide  # type: ignore
import crypto  # type: ignore
import client  # type: ignore

assert len(sys.argv) == 3, f"Usage: {sys.argv[0]} host port"

c = client.Client(client.RemoteServer(sys.argv[1], int(sys.argv[2])))
target = c.list()[1]

msg = b"abuse"
pad = b"a" * (collide.BLOCK_SIZE - len(msg))

k1, k2, iv, n, ctxt, t = collide.collide_encrypt(pad + msg)
cm = iv + ctxt + t

mid = c.server.put_msg(binascii.hexlify(cm))
hcm = crypto.hash(cm)  # type: ignore

c._send_ctxt(mid, k2, hcm, target)
print('sent first message')

flag = None
try:
    c._send_ctxt(mid, k1, hcm, target)
except AssertionError as e:
    flag = str(e)

print(flag)
Exemple #33
0
 def validate(self):
     ok = hash(str(self.public_key)) == self.from_addr
     return ok and check_sign(self.message(), self.sign, self.public_key)