Example #1
0
def main():
    with open('set6/c44data') as f:
        data = f.readlines()
        # Append ' ' to messages to get hash right
        msg = [(d[5:-1] + ' ').encode() for d in data[::4]]
        s = [int(d[3:-1]) for d in data[1::4]]
        r = [int(d[3:-1]) for d in data[2::4]]
        sig = [(i, j) for i, j in zip(r, s)]
        m = [d[3:-1] for d in data[3::4]]
        # Verify that messages are read correctly
        for i in range(len(msg)):
            if len(m[i]) == 39:  # Some hashes have left out leading zeros
                m[i] = '0' + m[i]
            assert sha1().digest(
                msg[i]).hex() == m[i], "Could not read data correctly"
            m[i] = int(m[i], 16)

    for i in range(len(m)):
        for j in range(i):
            k, x = priv_from_sig_pair(m[i], sig[i], m[j], sig[j])
            if x: break

    xh = sha1().digest(hex(x)[2:].encode()).hex()
    print('Messages %d and %d were signed using repeated nonce.' % (j, i))
    print('Nonce: ', k)
    print('Private key: ', x)
    print('Private key fingerprint: ', xh)
Example #2
0
def main():
    # Goal: forge a valid signature without using rsa_sign.sign(msg)
    # Create signature block, pad with a bunch of zeros, take cube root
    msg = b'hi mom'
    msghash = sha1().digest(msg)
    sig = b'\x00\x01\xff\x00' + rsa_pkcs1.sha1_asn1 + msghash
    sig += (128 - len(sig)) * b'\x00'
    sigint = cube_root(int.from_bytes(sig, 'big'))
    print(rsa_pkcs1().verify_unsafe(sigint, msg))
Example #3
0
def main():
    import numpy as np
    # We have MAC(key || msg), and we want to get MAC(key || msg || our_msg) without
    # knowing the key (only it's size).
    key = np.random.bytes(16)
    org_msg = (b'comment1=cooking%20MCs;userdata=foo;'
               b'comment2=%20like%20a%20pound%20of%20bacon')
    org_mac = sha1().auth(org_msg, key)

    # Using the sha-1 padding function, calculate the padded length of the input
    # used for the original MAC.
    prepend_len = len(sha1().pad_msg(bytes(16) + org_msg))
    # Derive the state of the sha-1 function from the MAC.
    state = [int.from_bytes(org_mac[i:i + 4], 'big') for i in range(0, 20, 4)]
    # Compute new mac
    m = sha1_append_msg(state, prepend_len)
    new_mac = m.digest(b';admin=true')
    print('Our MAC: ', new_mac)
    mac = sha1().digest(sha1().pad_msg(key + org_msg) + b';admin=true')
    print('Valid MAC: ', mac)
Example #4
0
def main():
    y = int(
        '84ad4719d044495496a3201c8ff484feb45b962e7302e56a392aee4'
        'abab3e4bdebf2955b4736012f21a08084056b19bcd7fee56048e004'
        'e44984e2f411788efdc837a0d2e5abb7b555039fd243ac01f0fb2ed'
        '1dec568280ce678e931868d23eb095fde9d3779191b8c0299d6e07b'
        'bb283e6633451e535c45513b2d33c99ea17', 16)
    msg = (
        b'For those that envy a MC it can be hazardous to your health\n'
        b'So be friendly, a matter of life and death, just like a etch-a-sketch\n'
    )
    sig = (548099063082341131477253921760299949438196259240,
           857042759984254168557880549501802188789837994940)
    for k in range(2**16):
        x = priv_from_k(sha1().intdigest(msg), sig, k)
        yt = pow(dsa.g, x, dsa.p)
        if yt == y:
            break
    print('Value of k: ', k)
    x = hex(x)[2:].encode()
    print('Private key fingerprint: ', sha1().digest(x).hex())
def handle_request():
    file = request.args.get('file')
    try:
        sig = bytes.fromhex(request.args.get('signature'))
    except:
        sig = None

    if not (file and sig):
        return "Provide valid filename and signature", 400

    realsig = sha1().auth(file.encode(), key)
    return ("Valid", 200) if insecure_compare(realsig, sig) else ("Invalid", 500)
Example #6
0
print "############### normal exchange"
##### normal exchange

Alice = c33.dh(random.randint(0,10000),p,g)

# A->B            Send "p", "g", "A"
Bob = c33.dh(random.randint(0,10000),p,g)
Bob_secret = Bob.shsecret(Alice.A)

# B->A            Send "B"
Alice_secret = Alice.shsecret(Bob.A)

# on Alice
Alice_msg = "Alice says Hi"
Alice_iv = open("/dev/urandom").read(16)
Alice_enc = c10.cbcencrypt(Alice_msg,Alice_iv,c28.sha1(str(Alice_secret)).digest()[:16])
print "msg Alice send: "+Alice_msg

# A->B            Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv

# on Bob
print "msg Bob received: "+c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(Bob_secret)).digest()[:16])
Bob_msg = "Bob says Hi"
Bob_iv = open("/dev/urandom").read(16)
Bob_enc = c10.cbcencrypt(Bob_msg,Bob_iv,c28.sha1(str(Bob_secret)).digest()[:16])
print "msg Bob send: "+Bob_msg
# B->A            Send AES-CBC(SHA1(s)[0:16], iv=random(16), A's msg) + iv

# on Alice
print "msg Alice received: "+c10.cbcdecrypt(Bob_enc,Bob_iv,c28.sha1(str(Alice_secret)).digest()[:16])
Example #7
0
 def __init__(self, p=None, q=None, g=None, hashfunc=sha1().intdigest):
     self.p = p if p else dsa.p
     self.q = q if q else dsa.q
     self.g = g if g else dsa.g
     self.H = hashfunc
     self.generate_keypair(True)
Example #8
0
print "\n\n========中间人攻击=======(g=1)"
print "中间人更改Alice和Bob的消息,使A=B=p="+str(p)
##### now Mallory comes into play
g = 1
Alice = c33.dh(random.randint(0,10000),p,g)
# A->M            Send "p", "g", "A"
# Mallory changes A to p # A^a mod p = p^a mod p = 0
# M->B            Send "p", "g", "p"
Bob = c33.dh(random.randint(0,10000),p,g)
Bob_secret = Bob.shsecret(Alice.A)
# B->M            Send "B"
# Mallory changes B to p # B^a mod p = p^a mod p = 0
# M->A            Send "p"
Alice_secret = Alice.shsecret(Bob.A)
print "shared key="+binascii.b2a_hex(c28.sha1(str(Alice_secret)).digest()[:16])
print "attack key="+binascii.b2a_hex(c28.sha1(str(1)).digest()[:16])
Alice_msg = "Alice hello OneA"
Alice_iv=''
for i in range(16):
    Alice_iv = Alice_iv+chr(random.randint(0,255))
Alice_enc = c10.cbcencrypt(Alice_msg,Alice_iv,c28.sha1(str(Alice_secret)).digest()[:16])
print "Alice发送: "+str(Alice_msg)

# A->M            Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv
# the secret is 0
print "攻击者解密出: "+c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(1)).digest()[:16])
# M->B            Relay that to B

print "Bob收到: "+c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(Bob_secret)).digest()[:16])
Bob_msg = "Bob HELLO OneA"
Example #9
0
def exchange(p,g,Mallory=False,mg=0):

  # A->B            Send "p", "g"
  # B->A            Send ACK

  # with Mallory, M would send NACK to Alice suggesting new p and g values
  # and would send the same weak values to Bob, assuming there is no
  # check on weak values, the communications would be screwed

  if Mallory:
    g = mg

  Alice = c33.dh(random.randint(0,10000),p,g)

  # A->B            Send "p", "g", "A"
  Bob = c33.dh(random.randint(0,10000),p,g)
  Bob_secret = Bob.shsecret(Alice.A)

  # B->A            Send "B"
  Alice_secret = Alice.shsecret(Bob.A)

  # on Alice
  Alice_msg = "Alice says Hi"
  Alice_iv = open("/dev/urandom").read(16)
  Alice_enc = c10.cbcencrypt(Alice_msg,Alice_iv,c28.sha1(str(Alice_secret)).digest()[:16])
  print "msg Alice send: "+Alice_msg

  # A->B            Send AES-CBC(SHA1(s)[0:16], iv=random(16), msg) + iv
  if Mallory:
    print "Mallory intercepts:",
    if g == 1:
      print c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(1)).digest()[:16])
    elif g == p:
      print c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(0)).digest()[:16])
    elif g == p - 1:
      try:
        msg = c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(1)).digest()[:16])
      except:
        msg = c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(p-1)).digest()[:16])
      print msg
    else:
      print ""

  # on Bob
  print "msg Bob received: "+c10.cbcdecrypt(Alice_enc,Alice_iv,c28.sha1(str(Bob_secret)).digest()[:16])
  Bob_msg = "Bob says Hi"
  Bob_iv = open("/dev/urandom").read(16)
  Bob_enc = c10.cbcencrypt(Bob_msg,Bob_iv,c28.sha1(str(Bob_secret)).digest()[:16])
  print "msg Bob send: "+Bob_msg
  # B->A            Send AES-CBC(SHA1(s)[0:16], iv=random(16), A's msg) + iv

  if Mallory:
    print "Mallory intercepts:",
    if g == 1:
      print c10.cbcdecrypt(Bob_enc,Bob_iv,c28.sha1(str(1)).digest()[:16])
    elif g == p:
      print c10.cbcdecrypt(Bob_enc,Bob_iv,c28.sha1(str(0)).digest()[:16])
    elif g == p - 1:
      try:
        msg = c10.cbcdecrypt(Bob_enc,Bob_iv,c28.sha1(str(1)).digest()[:16])
      except:
        msg = c10.cbcdecrypt(Bob_enc,Bob_iv,c28.sha1(str(p-1)).digest()[:16])
      print msg
    else:
      print ""

  # on Alice
  print "msg Alice received: "+c10.cbcdecrypt(Bob_enc,Bob_iv,c28.sha1(str(Alice_secret)).digest()[:16])
Example #10
0
 def __init__(self, **kwargs):
     self.asn1 = kwargs.pop('asn1', rsa_pkcs1.sha1_asn1)
     self.hashfunc = kwargs.pop('hashfunc', sha1().digest)
     super().__init__(**kwargs)
     self.k = (self.n.bit_length() + 7) // 8
Example #11
0
def random_line(afile):
    line = next(afile)
    for num, aline in enumerate(afile):
        if random.randrange(num + 2): continue
        line = aline
    return line.strip() + "::"


if __name__ == "__main__":
   

    try:
        key = random_line(open("words.txt"))  # 词库中随机随机取出一个单词
    except:
        print "can't open words will use secret word \"secret\""
        key = "secret"  # 打开文件失败默认给key赋值

    msg = "comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"  # 构建扩展攻击的信息
    orghash = c28.sha1(key + msg).hexdigest()  # 对消息进行加密
    print "初始值: key+msg"
    print orghash + " => " + key + msg

    msg2add = ";admin=true"
    att = sha1ext()
    add = att.extlen(orghash, len(key + msg), msg2add)
    print "不知道key得到hash "
    print att.hexdigest()
    print "与使用key进行加密的对比"
    print c28.sha1(key + msg + add).hexdigest() + " => " + key + msg + add.encode('string_escape')
Example #12
0
    self.h4 = hs[4]

    self.mesg = imsg
    tempmsg = c28.padding(msglen)+imsg
    self.lmsg = msglen + len(tempmsg)
    return tempmsg

def random_line(afile):
  line = next(afile)
  for num, aline in enumerate(afile):
    if random.randrange(num + 2): continue
    line = aline
  return line.strip()+"::"

if __name__ == "__main__":
  if not c28.sha1().test():
    print "tests failed"
  else:

    try:
      key = random_line(open("/usr/share/dict/words"))
    except:
      print "can't open /usr/share/dict/words will use secret word \"secret\""
      key = "secret"

    msg = "comment1=cooking%20MCs;userdata=foo;comment2=%20like%20a%20pound%20of%20bacon"
    orghash = c28.sha1(key+msg).hexdigest()
    print "original hash: key+msg"
    print orghash+" => "+key+msg

    print "now lets extend this hash, we assume knowledge of only the hashed value ("+orghash+")\
Example #13
0
def encrypt_msg(s, msg):
    key = sha1().digest(s)[:16]
    iv = random.getrandbits(128).to_bytes(16, 'big')
    return (cbc_cipher.encrypt_cbc(msg, key=key, iv=iv) + iv).hex()
Example #14
0
def decrypt_msg(s, msg):
    msg = bytes.fromhex(msg)
    iv = msg[-16:]
    msg = msg[:-16]
    key = sha1().digest(s)[:16]
    return cbc_cipher.decrypt_cbc(msg, key=key, iv=iv).decode()