コード例 #1
1
ファイル: test_RSA.py プロジェクト: shubhanus/taiga
    def _check_decryption(self, rsaObj):
        plaintext = bytes_to_long(a2b_hex(self.plaintext))
        ciphertext = bytes_to_long(a2b_hex(self.ciphertext))

        # Test plain decryption
        new_plaintext = rsaObj._decrypt(ciphertext)
        self.assertEqual(plaintext, new_plaintext)
コード例 #2
0
ファイル: test_RSA.py プロジェクト: shubhanus/taiga
    def _check_encryption(self, rsaObj):
        plaintext = a2b_hex(self.plaintext)
        ciphertext = a2b_hex(self.ciphertext)

        # Test encryption
        new_ciphertext2 = rsaObj._encrypt(bytes_to_long(plaintext))
        self.assertEqual(bytes_to_long(ciphertext), new_ciphertext2)
コード例 #3
0
ファイル: asn1.py プロジェクト: axray/dataware.dreamplug
def parse(data):
    things = []
    while data:
        t = ord(data[0])
        assert (t & 0xc0) == 0, 'not a universal value: 0x%02x' % t
        #assert t & 0x20, 'not a constructed value: 0x%02x' % t
        l = ord(data[1])
        assert data != 0x80, "shouldn't be an indefinite length"
        if l & 0x80: # long form
            ll = l & 0x7f
            l = number.bytes_to_long(data[2:2+ll])
            s = 2 + ll
        else:
            s = 2
        body, data = data[s:s+l], data[s+l:]
        t = t&(~0x20)
        assert t in (SEQUENCE, INTEGER), 'bad type: 0x%02x' % t
        if t == SEQUENCE:
            things.append(parse(body))
        elif t == INTEGER:
            #assert (ord(body[0])&0x80) == 0, "shouldn't have negative number"
            things.append(number.bytes_to_long(body))
    if len(things) == 1:
        return things[0]
    return things
コード例 #4
0
ファイル: josecrypto.py プロジェクト: bifurcation/pyjose
def decrypt(enc, key, iv, aad, ct, tag):
    """
    Decrypt JWE content.

    @type  enc: string
    @param enc: The JWE "enc" value specifying the encryption algorithm
    @type  key: bytes
    @param key: Key (CEK)
    @type  iv : bytes
    @param iv : Initialization vector
    @type  aad: bytes
    @param aad: Additional authenticated data
    @type  ct : bytes
    @param ct : Ciphertext
    @type  tag: bytes
    @param tag: Authentication tag
    @rtype: tuple
    @return: (ciphertext, tag), both as bytes
    """
    if enc in ["A128GCM", "A192GCM", "A256GCM"]:
        gcm = AES_GCM(bytes_to_long(key))
        try:
            pt = gcm.decrypt(bytes_to_long(iv), ct, bytes_to_long(tag), aad)
            return (pt, True)
        except InvalidTagException:
            return (None, False)
    elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]:
        return polyfills.AES_CBC_HMAC_decrypt( key, iv, aad, ct, tag )
    else: 
        raise Exception("Unsupported encryption algorithm {}".format(enc))
コード例 #5
0
ファイル: josecrypto.py プロジェクト: bifurcation/pyjose
def encrypt(enc, key, iv, aad, pt):
    """
    Encrypt JWE content.

    @type  enc: string
    @param enc: The JWE "enc" value specifying the encryption algorithm
    @type  key: bytes
    @param key: Key (CEK)
    @type  iv : bytes
    @param iv : Initialization vector
    @type  aad: bytes
    @param aad: Additional authenticated data
    @type  pt : bytes
    @param pt : Plaintext
    @rtype: tuple
    @return: (ciphertext, tag), both as bytes
    """
    if enc in ["A128GCM", "A192GCM", "A256GCM"]:
        gcm = AES_GCM(bytes_to_long(key))
        (ct, tag) = gcm.encrypt(bytes_to_long(iv), pt, aad)
        return (ct, long_to_bytes(tag, 16))
    elif enc in ["A128CBC-HS256", "A192CBC-HS384", "A256CBC-HS512"]:
        return polyfills.AES_CBC_HMAC_encrypt( key, iv, aad, pt )
    else: 
        raise Exception("Unsupported encryption algorithm {}".format(enc))
コード例 #6
0
ファイル: _ECDSA.py プロジェクト: paulswartz/pycrypto
def decode_point(bs, T):
    """
    Decode a string encoded version of a Point into a Point.
    """
    if not bs:
        raise error("can't decode a blank Point")
    if bord(bs[0]) == 0:
        return INFINITY
    elif bord(bs[0]) == 4:  # uncompressed point
        if len(bs) % 2 == 0:  # should be two even strings, plus 1 byte
            raise error('wrong length for uncompressed point')
        length = (len(bs) - 1) // 2 + 1
        x = number.bytes_to_long(bs[1:length])
        y = number.bytes_to_long(bs[length:])
    else:
        x = number.bytes_to_long(bs[1:])
        y_prime = (bord(bs[0]) == 3)
        alpha = (x ** 3 + T.a * x + T.b) % T.p
        beta = number.sqrt(alpha, T.p)
        if beta % 2 == y_prime:
            y = beta
        else:
            y = T.p - beta
    p = Point(x, y, T)
    if not p.verify():
        raise error("decoded an invalid point")
    return p
コード例 #7
0
def decodeRSAKeyPair(key):
    import base64

    l = key.split(',')
    n = number.bytes_to_long(base64.b64decode(l[0]))
    e = number.bytes_to_long(base64.b64decode(l[1]))
    return RSAKeyPair(n=n, e=e)
コード例 #8
0
ファイル: test_SPEKE.py プロジェクト: Brainiarc7/xpra
def test_SPEKE():
	password = "******"
	p = getStrongPrime(768)
	h = hashlib.sha1()
	#https://build.opensuse.org/package/view_file?file=pycrypto-2.6-elgamal.patch&package=python-crypto.openSUSE_11.4_Update&project=openSUSE%3AMaintenance%3A564&rev=1fe551f41425aa7d6cb7bca6de778168
	h.update(password)
	print("hash(%s)=%s=%s" % (password, h.hexdigest(), bytes_to_long(h.digest())))
	sq = bytes_to_long(h.digest())**2
	print("hash^2=%s" % sq)
	g = sq % p
	print("g=%s" % g)
	ga = 0
	#choose values sufficiently large, but not too large
	#as this would slow down calculations too much!
	MIN_I = 2**12
	MAX_I = 2**13
	while ga<=2 or ga>=p-2:
		a = random.randint(MIN_I, MAX_I)
		print("a=%s" % a)
		ga = (g**a) % p
		print("(g**a)%%p=%s" % ga)
	gb = 0
	while gb<=2 or gb>=p-2:
		b = random.randint(MIN_I, MAX_I)
		print("b=%s" % b)
		gb = (g**b) % p
		print("(g**b)%%p=%s" % gb)
	ak = (gb**a) % p
	print("aK=%s" % ak)
	bk = (ga**b) % p
	print("bK=%s" % bk)
	assert ak==bk
コード例 #9
0
ファイル: dcnet.py プロジェクト: ineiti/prifi
    def process_ciphertext(self, ciphertexts):
        ciphertexts = self.accumulator.before(ciphertexts)

        cleartext = []
        for nym_texts in ciphertexts[0]:
            cleartext.append([0 for x in range(len(nym_texts))])

        # Merging client ciphertexts
        for cldx in range(len(ciphertexts)):
            client_texts = ciphertexts[cldx]
            for nymdx in range(len(client_texts)):
                nym_texts = client_texts[nymdx]
                for celldx in range(len(nym_texts)):
                    cell = nym_texts[celldx]
                    cleartext[nymdx][celldx] ^= bytes_to_long(cell)

        # Merging trustee ciphertexts
        for nymdx in range(len(cleartext)):
            nym_texts = cleartext[nymdx]
            offset = self.current_cell[nymdx]
            cells = len(nym_texts)
            for celldx in range(cells):
                for tidx in range(self.trustees):
                    cell = self.cells_for_nyms[tidx][nymdx][offset + celldx]
                    cleartext[nymdx][celldx] ^= bytes_to_long(cell)
                cell = long_to_bytes(cleartext[nymdx][celldx])
                cell = self.decoder.decode(cell)
                cleartext[nymdx][celldx] = cell
            self.current_cell[nymdx] += cells

        return self.accumulator.after(cleartext)
コード例 #10
0
ファイル: test_RSA.py プロジェクト: Magdno1/Arianrhod
    def _exercise_primitive(self, rsaObj):
        # Since we're using a randomly-generated key, we can't check the test
        # vector, but we can make sure encryption and decryption are inverse
        # operations.
        ciphertext = a2b_hex(self.ciphertext)

        # Test decryption
        plaintext = rsaObj.decrypt((ciphertext,))

        # Test encryption (2 arguments)
        (new_ciphertext2,) = rsaObj.encrypt(plaintext, b(""))
        self.assertEqual(b2a_hex(ciphertext), b2a_hex(new_ciphertext2))

        # Test blinded decryption
        blinding_factor = Random.new().read(len(ciphertext) - 1)
        blinded_ctext = rsaObj.blind(ciphertext, blinding_factor)
        blinded_ptext = rsaObj.decrypt((blinded_ctext,))
        unblinded_plaintext = rsaObj.unblind(blinded_ptext, blinding_factor)
        self.assertEqual(b2a_hex(plaintext), b2a_hex(unblinded_plaintext))

        # Test signing (2 arguments)
        signature2 = rsaObj.sign(ciphertext, b(""))
        self.assertEqual((bytes_to_long(plaintext),), signature2)

        # Test verification
        self.assertEqual(1, rsaObj.verify(ciphertext, (bytes_to_long(plaintext),)))
コード例 #11
0
ファイル: test_DSA.py プロジェクト: 4ZM/pycrypto
 def _test_signing(self, dsaObj):
     k = a2b_hex(self.k)
     m_hash = a2b_hex(self.m_hash)
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     (r_out, s_out) = dsaObj.sign(m_hash, k)
     self.assertEqual((r, s), (r_out, s_out))
コード例 #12
0
ファイル: blockalgo.py プロジェクト: webiumsk/WOT-0.9.15.1
 def _start_gcm(self, factory, key, *args, **kwargs):
     if self.block_size != 16:
         raise TypeError('GCM mode is only available for ciphers that operate on 128 bits blocks')
     self.nonce = _getParameter('nonce', 1, args, kwargs)
     if not self.nonce:
         raise TypeError('MODE_GCM requires a nonce')
     self._mac_len = kwargs.get('mac_len', 16)
     if not (self._mac_len and 4 <= self._mac_len <= 16):
         raise ValueError("Parameter 'mac_len' must not be larger than 16 bytes")
     self._next = [self.update,
      self.encrypt,
      self.decrypt,
      self.digest,
      self.verify]
     self._done_assoc_data = False
     self._msg_len = 0
     hash_subkey = factory.new(key).encrypt(bchr(0) * 16)
     if len(self.nonce) == 12:
         self._j0 = bytes_to_long(self.nonce + b('\x00\x00\x00\x01'))
     else:
         fill = (16 - len(self.nonce) % 16) % 16 + 8
         ghash_in = self.nonce + bchr(0) * fill + long_to_bytes(8 * len(self.nonce), 8)
         mac = _GHASH(hash_subkey, factory.block_size)
         mac.update(ghash_in)
         self._j0 = bytes_to_long(mac.digest())
     ctr = Counter.new(128, initial_value=self._j0 + 1, allow_wraparound=True)
     self._cipher = self._factory.new(key, MODE_CTR, counter=ctr)
     self._cipherMAC = _GHASH(hash_subkey, factory.block_size)
     ctr = Counter.new(128, initial_value=self._j0, allow_wraparound=True)
     self._tag_cipher = self._factory.new(key, MODE_CTR, counter=ctr)
コード例 #13
0
ファイル: utils.py プロジェクト: SkierPGP/python-pgp
def sign_hash(pub_algorithm_type, secret_key, hash_, k=None):
    if pub_algorithm_type in (1, 3):
        # RSA
        sig_string = PKCS1_v1_5.new(secret_key).sign(hash_)
        return (bytes_to_long(sig_string),)
    elif pub_algorithm_type == 20:
        # ELG
        # TODO: Should only be allowed for test purposes
        if k is None:
            while 1:
                # This can be pretty darn slow
                k = random.StrongRandom().randint(1, secret_key.p - 1)
                if GCD(k, secret_key.p - 1) == 1:
                    break
            print(k)
        # TODO: Remove dependence on undocumented method
        sig_string = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE(
                            hash_, secret_key.size())
        return secret_key.sign(sig_string, k)
    elif pub_algorithm_type == 17:
        q = secret_key.q
        qbits = int(math.floor(float(math.log(q, 2)))) + 1
        qbytes = int(math.ceil(qbits / 8.0))
        if k is None:
            k = random.StrongRandom().randint(1, q - 1)

        digest = hash_.digest()[:qbytes]
        return secret_key.sign(bytes_to_long(digest), k)
    else:
        # TODO: complete
        raise ValueError
コード例 #14
0
ファイル: gcm.py プロジェクト: hdknr/jose
    def encrypt(cls, cek, plaint, iv, aad, *args, **kwargs):
        assert cek and len(cek) == cls._KEY_LEN
        assert iv and len(iv) == cls._IV_LEN

        ci = AES_GCM(bytes_to_long(cek))
        ciphert, tag = ci.encrypt(bytes_to_long(iv), plaint,  aad)

        return ciphert, long_to_bytes(tag)
コード例 #15
0
ファイル: oldMiniNero.py プロジェクト: Coder420/MiniNero
def sc_mulsub(a, b, c):
    #takes in a, b, and c
    #This is used by the regular sig 
    #i.e. in generate_signature
    #returns c-ab mod l
    a = number.bytes_to_long(a[::-1])
    b = number.bytes_to_long(b[::-1])
    c = number.bytes_to_long(c[::-1])
    return (c - a * b) % CURVE_P
コード例 #16
0
def singleTag(w, block, g, d, n):
        h = SHA256.new()
        bLong = number.bytes_to_long(block.data.tobytes())
        powG = gmpy2.powmod(g,bLong,n)
        h.update(str(w))
        wHash = number.bytes_to_long(h.digest())
        wGmodN = gmpy2.powmod((wHash*powG),1, n)
        tag = gmpy2.powmod(wGmodN, d, n)
        return tag
コード例 #17
0
ファイル: 0727-073.py プロジェクト: baloo/sflvault-server
def unserial_elgamal_privkey(privkey):
    """Get a string, return a 4-elements tuple of long()

    This contains the private (two first elements) and the public key."""
    x = privkey.split(':')
    return (bytes_to_long(b64decode(x[0])),
            bytes_to_long(b64decode(x[1])),
            bytes_to_long(b64decode(x[2])),
            bytes_to_long(b64decode(x[3])))
コード例 #18
0
def proofWorkerTask(inputQueue, blkPbSz, blkDatSz, chlng, lost, T, lock, cVal, N, ibf, g, qSets, TT):
    
    
    
    pName = mp.current_process().name
    x = ExpTimer()
    x.registerSession(pName)
    x.registerTimer(pName, "qSet_proof")
    x.registerTimer(pName, "cSumKept")
    x.registerTimer(pName, "cTagKept")
    x.registerTimer(pName, "ibf_serv")
    
    
    while True:
        item = inputQueue.get()
        if item == "END":
            TT[pName+str("_qSet_proof")] = x.getTotalTimer(pName, "qSet_proof")
            TT[pName+str("_cSumKept")] = x.getTotalTimer(pName, "cSumKept") - x.getTotalTimer(pName, "ibf_serv")
            TT[pName+str("_cTagKept")] = x.getTotalTimer(pName, "cTagKept") - x.getTotalTimer(pName, "ibf_serv")
            TT[pName+str("_ibf_serv")] = x.getTotalTimer(pName, "ibf_serv")
            
            
            return
        for blockPbItem in BE.chunks(item,blkPbSz):
            block = BE.BlockDisk2Block(blockPbItem, blkDatSz)
            bIndex = block.getDecimalIndex()
            if bIndex in lost:
                x.startTimer(pName, "qSet_proof")
                binBlockIndex = block.getStringIndex()
                indices = ibf.getIndices(binBlockIndex, True)
                for i in indices:
                    with lock:
                        qSets.addValue(i, bIndex)
                
                x.endTimer(pName, "qSet_proof")    
                del block
                continue
            x.startTimer(pName, "cSumKept")
            x.startTimer(pName, "cTagKept")
            aI = pickPseudoRandomTheta(chlng, block.getStringIndex())
            aI = number.bytes_to_long(aI)
            bI = number.bytes_to_long(block.data.tobytes())
            
          
            
            
            with lock:
                x.startTimer(pName, "ibf_serv")
                ibf.insert(block, chlng, N, g, True)
                x.endTimer(pName, "ibf_serv")
                cVal["cSum"] += (aI*bI)
                x.endTimer(pName,"cSumKept")
                cVal["cTag"] *= gmpy2.powmod(T[bIndex], aI, N)
                cVal["cTag"] = gmpy2.powmod(cVal["cTag"],1,N)
                x.endTimer(pName,"cTagKept")
            del block    
コード例 #19
0
ファイル: test_import_ECC.py プロジェクト: shubhanus/taiga
def create_ref_keys():
    key_lines = load_file("ecc_p256.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:5]))
    public_key_xy = compact(key_lines[6:11])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:33])
    public_key_y = bytes_to_long(public_key_xy[33:])

    return (ECC.construct(curve="P-256", d=private_key_d),
            ECC.construct(curve="P-256", point_x=public_key_x, point_y=public_key_y))
コード例 #20
0
ファイル: crypt.py プロジェクト: ioerror/pure-python-otr
    def proof_equal_logs(self, v):
        r = bytes_to_long(RNG.read(192))
        temp1 = pow(self.g1, r, DH1536_MODULUS)
        temp2 = pow(self.qab, r, DH1536_MODULUS)

        cb = SHA256(chr(v) + toMpi(temp1) + toMpi(temp2))
        c = bytes_to_long(cb)
        temp1 = self.x3 * c % SM_ORDER
        d = (r - temp1) % SM_ORDER
        return c, d
コード例 #21
0
ファイル: DSA.py プロジェクト: Zer0ne83/sshconsole
def generate(bits, randfunc, progress_func=None):
    """generate(bits:int, randfunc:callable, progress_func:callable)

    Generate a DSA key of length 'bits', using 'randfunc' to get
    random data and 'progress_func', if present, to display
    the progress of the key generation.
    """

    if bits<160:
        raise error, 'Key length <160 bits'
    obj=DSAobj()
    # Generate string S and prime q
    if progress_func:
        progress_func('p,q\n')
    while (1):
        S, obj.q = generateQ(randfunc)
        n=(bits-1)/160
        C, N, V = 0, 2, {}
        b=(obj.q >> 5) & 15
        powb=pow(bignum(2), b)
        powL1=pow(bignum(2), bits-1)
        while C<4096:
            for k in range(0, n+1):
                V[k]=bytes_to_long(SHA.new(S+str(N)+str(k)).digest())
            W=V[n] % powb
            for k in range(n-1, -1, -1):
                W=(W<<160L)+V[k]
            X=W+powL1
            p=X-(X%(2*obj.q)-1)
            if powL1<=p and isPrime(p):
                break
            C, N = C+1, N+n+1
        if C<4096:
            break
        if progress_func:
            progress_func('4096 multiples failed\n')

    obj.p = p
    power=(p-1)/obj.q
    if progress_func:
        progress_func('h,g\n')
    while (1):
        h=bytes_to_long(randfunc(bits)) % (p-1)
        g=pow(h, power, p)
        if 1<h<p-1 and g>1:
            break
    obj.g=g
    if progress_func:
        progress_func('x,y\n')
    while (1):
        x=bytes_to_long(randfunc(20))
        if 0 < x < obj.q:
            break
    obj.x, obj.y = x, pow(g, x, p)
    return obj
コード例 #22
0
def apply_f(block, N, secret_key, g):
	index = block.getStringIndex()
	a = pickPseudoRandomTheta(secret_key, index)
	
	
	aLong = number.bytes_to_long(a)
	#print aLong
	bLong = number.bytes_to_long(block.data.tobytes())
	
	abExp = aLong*bLong
	return gmpy2.powmod(g, abExp, N)
コード例 #23
0
def create_ref_keys_p521():
    key_len = 66
    key_lines = load_file("ecc_p521.txt").splitlines()
    private_key_d = bytes_to_long(compact(key_lines[2:7]))
    public_key_xy = compact(key_lines[8:17])
    assert bord(public_key_xy[0]) == 4  # Uncompressed
    public_key_x = bytes_to_long(public_key_xy[1:key_len+1])
    public_key_y = bytes_to_long(public_key_xy[key_len+1:])

    return (ECC.construct(curve="P-521", d=private_key_d),
            ECC.construct(curve="P-521", point_x=public_key_x, point_y=public_key_y))
コード例 #24
0
ファイル: spki.py プロジェクト: danieljohnlewis/pisces
    def _sexp_to_impl(self):
	for obj in self.args:
            # XXX don't think the for loop is necessary
	    if obj.name == 'e':
		e = bytes_to_long(obj.args[0])
	    elif obj.name == 'n':
		n = bytes_to_long(obj.args[0])
	    else:
		raise ValueError, "unknown part: %s" % `obj`
	# order of args defined by RSA impl
	self.impl = pkcs1.RSA_pkcs1((n, e))
コード例 #25
0
ファイル: ECC.py プロジェクト: Legrandin/pycryptodome
    def xy(self):
        modulus_bytes = self.size_in_bytes()
        xb = bytearray(modulus_bytes)
        yb = bytearray(modulus_bytes)
        result = _ec_lib.ec_ws_get_xy(c_uint8_ptr(xb),
                                      c_uint8_ptr(yb),
                                      c_size_t(modulus_bytes),
                                      self._point.get())
        if result:
            raise ValueError("Error %d while encoding an EC point" % result)

        return (Integer(bytes_to_long(xb)), Integer(bytes_to_long(yb)))
コード例 #26
0
ファイル: DSS.py プロジェクト: dongweigogo/pycryptodome
    def verify(self, msg_hash, signature):
        """Verify that a certain DSS signature is authentic.

        This function checks if the party holding the private half of the key
        really signed the message.

        :Parameters:
          msg_hash : hash object
            The hash that was carried out over the message.
            This is an object belonging to the `Crypto.Hash` module.

            Under mode *'fips-186-3'*, the hash must be a FIPS
            approved secure hash (SHA-1 or a member of the SHA-2 family).

          signature : byte string
            The signature that needs to be validated.

        :Raise ValueError:
            If the signature is not authentic.
        """

        if not self._deterministic:
            if self._n > msg_hash.digest_size * 8:
                raise ValueError("Hash is not long enough")

            if not hash_is_shs(msg_hash):
                raise ValueError("Hash does not belong to SHS")

        if self._encoding == 'binary':
            if len(signature) != (2 * self._n):
                raise ValueError("The signature is not authentic")
            r_prime, s_prime = [bytes_to_long(x)
                                for x in (signature[:self._n],
                                          signature[self._n:])]
        else:
            try:
                der_seq = DerSequence()
                der_seq.decode(signature)
            except (ValueError, IndexError):
                raise ValueError("The signature is not authentic")
            if len(der_seq) != 2 or not der_seq.hasOnlyInts():
                raise ValueError("The signature is not authentic")
            r_prime, s_prime = der_seq[0], der_seq[1]

        if not (0 < r_prime < self._key.q) or not (0 < s_prime < self._key.q):
            raise ValueError("The signature is not authentic")

        z = bytes_to_long(msg_hash.digest()[:self._n])
        result = self._key._verify(z, (r_prime, s_prime))
        if not result:
            raise ValueError("The signature is not authentic")
        # Make PyCrypto code to fail
        return False
コード例 #27
0
ファイル: AllOrNothing.py プロジェクト: 0xPr0xy/blogger-cli
    def undigest(self, blocks):
        """undigest(blocks : [string]) : string

        Perform the reverse package transformation on a list of message
        blocks.  Note that the ciphermodule used for both transformations
        must be the same.  blocks is a list of strings of bit length
        equal to the ciphermodule's block_size.
        """

        # better have at least 2 blocks, for the padbytes package and the hash
        # block accumulator
        if len(blocks) < 2:
            raise ValueError, "List must be at least length 2."

        # blocks is a list of strings.  We need to deal with them as long
        # integers
        blocks = map(bytes_to_long, blocks)

        # Calculate the well-known key, to which the hash blocks are
        # encrypted, and create the hash cipher.
        K0 = self.__K0digit * self.__key_size
        hcipher = self.__newcipher(K0)

        # Since we have all the blocks (or this method would have been called
        # prematurely), we can calcualte all the hash blocks.
        hashes = []
        for i in range(1, len(blocks)):
            mticki = blocks[i-1] ^ i
            hi = hcipher.encrypt(long_to_bytes(mticki))
            hashes.append(bytes_to_long(hi))

        # now we can calculate K' (key).  remember the last block contains
        # m's' which we don't include here
        key = blocks[-1] ^ reduce(operator.xor, hashes)

        # and now we can create the cipher object
        mcipher = self.__newcipher(long_to_bytes(key))
        block_size = self.__ciphermodule.block_size

        # And we can now decode the original message blocks
        parts = []
        for i in range(1, len(blocks)):
            cipherblock = mcipher.encrypt(long_to_bytes(i, block_size))
            mi = blocks[i-1] ^ bytes_to_long(cipherblock)
            parts.append(mi)

        # The last message block contains the number of pad bytes appended to
        # the original text string, such that its length was an even multiple
        # of the cipher's block_size.  This number should be small enough that
        # the conversion from long integer to integer should never overflow
        padbytes = int(parts[-1])
        text = string.join(map(long_to_bytes, parts[:-1]), '')
        return text[:-padbytes]
コード例 #28
0
ファイル: gcm.py プロジェクト: hdknr/jose
    def decrypt(cls, cek, ciphert, iv, aad, tag, *args,  **kwargs):
        assert cek and len(cek) == cls._KEY_LEN
        assert iv and len(iv) == cls._IV_LEN
        assert tag and len(tag) == cls._TAG_LEN

        ci = AES_GCM(bytes_to_long(cek))
        try:
            plaint = ci.decrypt(bytes_to_long(iv), ciphert,
                                bytes_to_long(tag), aad)
            return plaint, True
        except InvalidTagException:
            return (None, False)
コード例 #29
0
ファイル: sollution.py プロジェクト: PKlimo/CryptoChallenge
    def sign(self, h, priv_key=None, nonce=None):
        x = self.__x if priv_key is None else priv_key

        while True:
            k = random.StrongRandom().randint(1, q - 1) if nonce is None else nonce
            r = pow(g, k, p) % q
            s2 = number.inverse(k, q) * (number.bytes_to_long(h) + x * r)
            s = pow(k, q - 2, q) * (number.bytes_to_long(h) + x * r)
            assert s2 == s
            s = s % q
            if r != 0 and s != 0:
                self.k = k
                return (r, s)
コード例 #30
0
 def verify(self, message, signature):
     p, q, g, y = self.public_key
     dss, blob = packet.unpack_payload(DSS_SIG_PAYLOAD, signature)
     if dss != 'ssh-dss':
         raise ValueError, dss
     # blob is the concatenation of r and s
     # r and s are 160-bit (20-byte) integers in network-byte-order
     assert( len(blob) == 40 )
     r = number.bytes_to_long(blob[:20])
     s = number.bytes_to_long(blob[20:])
     dsa_obj = DSA.construct( (y, g, p, q) )
     hash_of_message = hashlib.sha1(message).digest()
     return dsa_obj.verify(hash_of_message, (r, s))
コード例 #31
0
ファイル: chall.py プロジェクト: kreelsama/ctf-solutions
import os
from Crypto.Util import number
from secret import flag

p = number.getPrime(1024)
q = number.getPrime(1024)
n = p * q
e = 65537

flag = os.urandom(255 - len(flag)) + flag
flag = number.bytes_to_long(flag)
data = number.bytes_to_long(b"0ops")

enc_flag = pow(flag, e, n)
enc_data = pow(data, p, n)

print(f"n = {n}")
print(f"enc_flag = {enc_flag}")
print(f"enc_data = {enc_data}")
コード例 #32
0
ファイル: solve.py プロジェクト: zihuocc/public-writeup
            yield chinese_remainder([p, q], [s1, s2])
            yield chinese_remainder([p, q], [p - s1, s2])
            yield chinese_remainder([p, q], [s1, q - s2])
            yield chinese_remainder([p, q], [p - s1, q - s2])


# This is a *pseudoinverse* since gcd(e, (p-1)*(q-1)) == 16.
d = inverse(e, (p - 1) * (q - 1))

for m in reversed(list(power2roots(pow(c, d, n), 4))):
    assert pow(m, e, n) == c

    # OH NO! They left out a bunch of bits :(
    flagfmt = 'hitcon{' + ' ' * 42 + '}'
    assert len(flagfmt) == 50
    curm = bytes_to_long(flagfmt) // n * n + m
    while curm % 256 != ord('}'):
        curm += n

    assert curm % n == m
    assert pow(curm, e, n) == c

    import re
    valid_flag_re = re.compile(r'^[\x20-\x7e]+$')

    increment = n * 256  # leave the last byte (}) unchanged
    for i in xrange(1000000000):
        s = long_to_bytes(curm, 50)
        if s > 'hitcon{\x7f':
            break
        if valid_flag_re.match(s):
コード例 #33
0
# From the m, we can deduce the shares:
# x = 1, a    + b   + c = m1 [prime]
# x = 2, a*4  + b*2 + c = m2 [prime]
# x = 3, a*9  + b*3 + c = m3 [prime]
# x = 4, a*16 + b*4 + c = m4 [prime]
# x = 5, a*25 + b*5 + c = m5 [prime]


def make_shares(secret, k, shares, prime=PRIME):
    PR, x = PolynomialRing(GF(prime), name='x').objgen()
    f = PR([secret] + [ZZ.random_element(prime) for _ in range(k - 1)])
    xy = []
    pubkey = []
    # Loop of length five
    for x in range(1, shares + 1):
        noise = prng.rand()
        n, g, y = paillier_enc(f(x) + noise, prime, noise)
        pubkey.append([n, g])
        # x is the polynomial parameter and c the ciphertext
        xy.append([x, y])
    return pubkey, xy


secret = bytes_to_long(flag)
pubkey, shares = make_shares(secret, 3, 5)

print("[+] len(flag):", len(flag))
print("[+] pubkey:", pubkey)
print("[+] shares:", shares)
コード例 #34
0
 def _gen_next_key(self):
     #эти данные хэшируются и формуют ключ AES
     k = str(platform.uname())
     c = str(self._rnd_bytes)
     return long_to_bytes(bytes_to_long(' '.join((k, c))) + self._count)
コード例 #35
0
def Bleichenbacher(ciphertext, RSA_Cipher):
    # Initialize variables
    bits = RSA_Cipher.Bits()
    public_key = RSA_Cipher.PublicKey()
    e = public_key.e
    n = public_key.n
    i = 1
    calls_to_oracle = 0
    start_time = time.time()

    # Compute constant variable B and initial interval M_0 = [a,b]
    B = pow(2, 8 * (bits // 8 - 2))
    a = 2 * B
    b = 3 * B - 1
    M_i_1 = I.closed(a, b)

    # Step 1: Calculate c, s_0
    c = bytes_to_long(ciphertext)
    s_i_1 = 1

    #  Printing
    print("\n\n======================================================\n",
          "Bleichenbacher Attack on RSA PKCS v1.5",
          "\n======================================================\n",
          "\nPublic Key\ne =", e, "\nn =", n, "  (", bits,
          "bits )\n\nCiphertext")
    print(ciphertext)
    print("\n\nIteration 0\n---------------------------------------------")
    print("\nStep 1: find ciphertext c in integer form\nc =", c)
    print("\nConfirm Call Oracle on Given Ciphertext:",
          CallOracle(c, RSA_Cipher))  # Check that CallOracle works
    print("\nM_0 =", M_i_1)

    # Repeat until you M_i a single interval with one element
    while M_i_1.lower != M_i_1.upper:
        print("\n\nIteration ", i,
              "\n---------------------------------------------")

        # Step 2 : Find s_i
        # Step 2a: Calculate s_i, smallest int >= n/3B that conforms
        if i == 1:
            print(
                "\nStep 2a: find smallest s_1 >= n/3B such that plaintext corresponding to c(s_1^e) mod n conforms"
            )
            s_i, calls_to_oracle = CalculateC_i(c, e, n, ceil(n, 3 * B), n - 1,
                                                calls_to_oracle, RSA_Cipher)
            print("s_" + str(i), " = ", s_i, "\n")

        # Step 2b: If M_i-1 has multiple disjoint intervals,
        # Calculate smallest s_i > s_i_1 that conforms
        elif len(M_i_1) > 1:
            print(
                "\nStep 2b: find smallest s_i > s_(i-1) such that plaintext corresponding to c(s_i^e) mod n conforms\ns_i_1 = ",
                s_i_1)
            s_i, calls_to_oracle = CalculateC_i(c, e, n, s_i_1 + 1, n - 1,
                                                calls_to_oracle,
                                                RSA_Cipher)  #change to s_i + 1
            print("s_" + str(i), " = ", s_i, "\n")

        # Step 2c: Number of intervals = 1 -> find s_i
        else:
            print(
                "\nStep 2c: vary integer r_i and s_i until find s_i such that plaintext corresponding to c(s_i^e) mod n conforms"
            )
            a, b = M_i_1.lower, M_i_1.upper
            r_i = ceil(2 * b * s_i_1 - 2 * B, n)
            s_i = 0
            # While s_i corresponding plaintext to c(s_i)^e mod n does not conform
            while s_i == 0:
                lower = ceil(2 * B + r_i * n, b)
                upper = ceil(3 * B + r_i * n, a) - 1
                s_i, calls_to_oracle = CalculateC_i(c, e, n, lower, upper,
                                                    calls_to_oracle,
                                                    RSA_Cipher)
                r_i += 1
            print("s_" + str(i), " = ", s_i, "\n")

        # Step 3: Reduce M_i_1 to M_i and store
        # Initialize M_i
        print("\nStep 3: after s_i found, reduce set M_(i-1) to M_i")
        M_i = I.empty()
        # For each disjoint interval [a,b] in M_(i-1)
        for interval in M_i_1:
            a, b = interval.lower, interval.upper
            low_r = ceil(a * s_i - 3 * B + 1, n)
            high_r = ceil(b * s_i - 2 * B, n)
            for r in range(low_r, high_r):
                i_low = max(a, ceil(2 * B + r * n, s_i))
                i_high = min(b, floor(3 * B - 1 + r * n, s_i))
                M_new = I.closed(i_low, i_high)
                M_i = M_i | M_new
        print("M_" + str(i), " = ", M_i)
        # Reset variables for next round
        M_i_1 = M_i
        s_i_1 = s_i
        i += 1

    # Step 4: single remaining element (M_i.lower = M_i.upper) * (s_0 ^-1 mod n)
    print("Calls to Oracle: ", calls_to_oracle)
    print("\nStep 4: M_i.lower = M_i.higher = m, the message in integer form")
    m = M_i.lower
    print("\nRecovered Message Integer = ", m)
    sbytes = long_to_bytes(m)
    print("\nMessage Converted to Bytes", sbytes)
    message = PKCS1_decode(sbytes)
    elapsed_time = time.time() - start_time
    print("\n---------------------------------------------\nTime Elapsed:",
          elapsed_time / 60, " minutes\n")
    return message
コード例 #36
0
def s2n(s):
    return bytes_to_long(bytearray(s, 'latin-1'))
コード例 #37
0
 def bytes2int(x):
     return bytes_to_long(x)
コード例 #38
0
ファイル: jws.py プロジェクト: astagi/pyjwkest
 def verify(self, msg, sig, key):
     h = bytes_to_long(self.digest.new(msg).digest())
     return self._sign.verify(h, sig, key)
コード例 #39
0
])

# pubkey of the CA which signs controller keys
jedi_CA_pubkey = RSA.construct((bytes_to_long(
    bytes([
        0x8E, 0xD7, 0xF9, 0xE4, 0xAA, 0x5C, 0xC5, 0xD2, 0x31, 0x96, 0xF0, 0xDE,
        0x79, 0x7D, 0xFE, 0xAC, 0xF6, 0x3E, 0xDE, 0x7B, 0xC9, 0x67, 0x16, 0xF1,
        0x3C, 0xF5, 0x2A, 0xDE, 0xF8, 0xDA, 0xCF, 0xA8, 0xE2, 0x33, 0xDC, 0x65,
        0x57, 0x17, 0x34, 0x7D, 0x4C, 0x8C, 0x82, 0x6E, 0xAB, 0x90, 0x36, 0x16,
        0xFF, 0x9F, 0xB8, 0xF9, 0x73, 0x36, 0x17, 0xFB, 0xD4, 0x4E, 0xC8, 0x10,
        0x78, 0xAD, 0x6E, 0x24, 0xB0, 0x62, 0x61, 0x9F, 0x5A, 0x17, 0xEE, 0x2F,
        0x55, 0x72, 0xB4, 0x27, 0xC0, 0x34, 0xA9, 0x49, 0x36, 0x3E, 0x86, 0xD3,
        0xB2, 0x13, 0x35, 0x1F, 0x89, 0x04, 0xA4, 0x99, 0xF8, 0x62, 0x40, 0x1F,
        0x4E, 0x60, 0xAC, 0x21, 0x31, 0xCD, 0x4B, 0xB9, 0xFD, 0xDF, 0xD5, 0x90,
        0xC8, 0xE2, 0x2B, 0x7D, 0xF9, 0x6D, 0x01, 0x5A, 0x41, 0xC5, 0x49, 0xF3,
        0xEA, 0x0D, 0xED, 0xFC, 0x32, 0xCE, 0xC3, 0x2D, 0x72, 0xC5, 0x34, 0x93,
        0x4A, 0xEF, 0x3D, 0xD1, 0x2B, 0x58, 0xDB, 0x35, 0x7D, 0xD0, 0x4D, 0x9A,
        0x93, 0x11, 0xA3, 0x83, 0x3F, 0xF8, 0x55, 0x7A, 0x0B, 0x85, 0xB4, 0x54,
        0xCD, 0x21, 0xDA, 0xB9, 0x0D, 0x71, 0x4A, 0xEA, 0x2D, 0xEC, 0x42, 0xE6,
        0xF4, 0xEF, 0x20, 0x45, 0x3C, 0xF6, 0xDB, 0xF3, 0x95, 0x4E, 0x73, 0xA8,
        0x76, 0x91, 0xCF, 0xA0, 0x3F, 0x47, 0x59, 0x45, 0x5C, 0x8B, 0x96, 0xF1,
        0xD0, 0xB6, 0x9D, 0xD3, 0xDD, 0x62, 0x62, 0xE9, 0x43, 0x8D, 0xCC, 0x26,
        0x96, 0xCF, 0xE6, 0x4B, 0x93, 0x0C, 0x6E, 0x7D, 0x4E, 0x01, 0x51, 0xF6,
        0xD1, 0xB1, 0x5D, 0x1A, 0x4B, 0xE2, 0xE6, 0x0F, 0x0B, 0x36, 0x11, 0x8C,
        0x60, 0xF2, 0x53, 0xFD, 0xBC, 0xE2, 0x27, 0xA8, 0xA4, 0xC9, 0xCD, 0xF2,
        0x26, 0x08, 0x58, 0x58, 0x4A, 0xB8, 0xD7, 0x1C, 0x62, 0x9C, 0xD4, 0x21,
        0xEC, 0x66, 0x60, 0x59
    ])), 0x10001))


def get_hw_binding():
コード例 #40
0
 def from_bytes(cls, byte_string):
     return cls(bytes_to_long(byte_string))
コード例 #41
0
ファイル: task.py プロジェクト: TearsJin/Crypto
def getrandbits(n):
    return bytes_to_long(os.urandom(n // 8 + 1)) >> (8 - n % 8)
コード例 #42
0
ファイル: _mode_ocb.py プロジェクト: Kobot7/D-Crypt
    def __init__(self, factory, nonce, mac_len, cipher_params):

        if factory.block_size != 16:
            raise ValueError("OCB mode is only available for cipher"
                             " that operate on 128 bits blocks")

        self.block_size = 16
        """The block size of the underlying cipher, in bytes."""

        self.nonce = _copy_bytes(None, None, nonce)
        """Nonce used for this session."""
        if len(nonce) not in range(1, 16):
            raise ValueError("Nonce must be at most 15 bytes long")
        if not is_buffer(nonce):
            raise TypeError("Nonce must be bytes, bytearray or memoryview")

        self._mac_len = mac_len
        if not 8 <= mac_len <= 16:
            raise ValueError("MAC tag must be between 8 and 16 bytes long")

        # Cache for MAC tag
        self._mac_tag = None

        # Cache for unaligned associated data
        self._cache_A = b""

        # Cache for unaligned ciphertext/plaintext
        self._cache_P = b""

        # Allowed transitions after initialization
        self._next = [
            self.update, self.encrypt, self.decrypt, self.digest, self.verify
        ]

        # Compute Offset_0
        params_without_key = dict(cipher_params)
        key = params_without_key.pop("key")
        nonce = (struct.pack('B', self._mac_len << 4 & 0xFF) + b'\x00' *
                 (14 - len(nonce)) + b'\x01' + self.nonce)

        bottom_bits = bord(nonce[15]) & 0x3F  # 6 bits, 0..63
        top_bits = bord(nonce[15]) & 0xC0  # 2 bits

        ktop_cipher = factory.new(key, factory.MODE_ECB, **params_without_key)
        ktop = ktop_cipher.encrypt(struct.pack('15sB', nonce[:15], top_bits))

        stretch = ktop + strxor(ktop[:8], ktop[1:9])  # 192 bits
        offset_0 = long_to_bytes(
            bytes_to_long(stretch) >> (64 - bottom_bits), 24)[8:]

        # Create low-level cipher instance
        raw_cipher = factory._create_base_cipher(cipher_params)
        if cipher_params:
            raise TypeError("Unknown keywords: " + str(cipher_params))

        self._state = VoidPointer()
        result = _raw_ocb_lib.OCB_start_operation(raw_cipher.get(), offset_0,
                                                  c_size_t(len(offset_0)),
                                                  self._state.address_of())
        if result:
            raise ValueError("Error %d while instantiating the OCB mode" %
                             result)

        # Ensure that object disposal of this Python object will (eventually)
        # free the memory allocated by the raw library for the cipher mode
        self._state = SmartPointer(self._state.get(),
                                   _raw_ocb_lib.OCB_stop_operation)

        # Memory allocated for the underlying block cipher is now owed
        # by the cipher mode
        raw_cipher.release()
コード例 #43
0
 def __init__(self):
     self._count = 0
     self._rnd = Random.new()
     self._rnd_bytes = bytes_to_long(self._rnd.read(32))
     self._rsa = self._import_pk()
コード例 #44
0
def pad(s):
    assert (len(s) < N.bit_length() / 8)
    padded = bytes_to_long(s.ljust(N.bit_length() / 8, padchar))
    while decrypt(padded, p, q) == None:
        padded += 1
    return padded
コード例 #45
0
ファイル: hub.py プロジェクト: Silentsoul04/CTFs-2
    0xd1450d67: 'fun_abf_putchar',
    0x8ea45b38: 'fun_b46',
    0xf00bb6c1: 'fun_b03',
    0x5991ba22: 'fun_b89',
    0x43ae1f53: 'fun_724',
    0x8960888a: 'fun_be5',
    0x1f0a8e6f: 'fun_c41',
    0x466a54d9: 'fun_c8e_exit',
    0xfb521a9c: 'fun_ca4',
    0xc650f15d: 'fun_cf7'
}

b64 = open('b64strings/2.decoded', 'rb').read()
step = 4
chunks = [b64[i:i + step][::-1] for i in range(0, len(b64), step)]
chunks = [bytes_to_long(chunks[i]) for i in range(len(chunks))]

for i in range(0, len(chunks), 2):
    chunk = chunks[i]
    associated_chunk = chunks[i + 1]
    if chunk not in hub:
        print(f'chunk {hex(chunk)} not in chunks')
        continue
    fun = hub[chunk]
    print(
        f'chunk {hex(chunk)} -> {fun} | associated chunk = {hex(associated_chunk)}'
    )
'''
[2*14] => 0xadc52d => changes
never reaches 0x795bf373
'''
コード例 #46
0
def string2int(s):
    # return int.from_bytes(s.encode("utf-8"), byteorder = "big")
    return fmpz(number.bytes_to_long(s.encode("utf-8")))
コード例 #47
0
def get_query():
    s = r.recvline()
    u = s.split()[-1]
    u.decode()
    c = binascii.unhexlify(u)
    if len(c) % 16 != 0:
        c = c + bytes([0]) * (16 - len(c) % 16)
    return c


def get_enc(x):
    ret = tot
    for i in range(0, 128):
        if ((x >> i) & 1) == 1:
            ret -= (tot - ff[i])
    return ret


r.sendline(b"2")

for i in range(10):
    ret = ''
    c = get_query()
    for j in range(0, len(c), 16):
        vv = get_enc(bytes_to_long(c[j:j + 16]))
        ret += hex(vv)[2:].rjust(32, "0")
    r.sendline(ret)
print(r.recvline())
print(r.recvline())
コード例 #48
0
#!/usr/bin/env python3

from Crypto.Util.number import bytes_to_long, isPrime

flag = 'TWCTF{F4k3_fL4GG_'
flag += "A" * (42 - len(flag) - 1) + '}'
p = 6722156186149423473586056936189163112345526308304739592548269432948561498704906497631759731744824085311511299618196491816929603296108414569727189748975204102209646335725406551943711581704258725226874414399572244863268492324353927787818836752142254189928999592648333789131233670456465647924867060170327150559233


def encrypt(pt, k, p):
    return pow(pt, 1 << k, p)


assert flag.startswith("TWCTF{")
assert len(flag) == 42
assert isPrime(p)

k = 64
pt = bytes_to_long(flag.encode())
ct = encrypt(pt, k, p)

print('[+] pt: {}'.format(pt))
print('[+] 1 << k: {}'.format(1 << k))
print('[+] p: {}'.format(p))
print('[+] ct: {}'.format(ct))

# ct = pt ^ (1<<k) % p
# ct = pt ^ (2^64) % p
コード例 #49
0
ファイル: decrypt.py プロジェクト: pombredanne/mitra
	success = False
	try:
		invalidkey = b'\x07'*16
		plaintxt1 = gcm_decrypt(invalidkey, nonce, ciphertext, tag, adata)
	except Exception:
		success = True
	if not success:
		print("Decryption with other key failed didn't fail as expected")

	hash = hashlib.sha256(ciphertext).hexdigest()[:8].lower()

	fname = os. path.splitext(fname)[0] # remove file extension

	exts = exts.split(" ")[-2:]
	with open("%s.%s.%s" % (fname, hash, exts[0]), "wb") as file1:
		file1.write(plaintxt1)

	with open("%s.%s.%s" % (fname, hash, exts[1]), "wb") as file2:
		file2.write(plaintxt2)

	print("key1:", key1.rstrip(b"\0"))
	print("key1:", key2.rstrip(b"\0"))
	print("ad:", adata.rstrip(b"\0"))
	print("nonce:", bytes_to_long(nonce))
	print("tag:", binascii.hexlify(tag))
	print("Success!")
	print()
	print("plaintext1:", binascii.hexlify(plaintxt1[:16]),"...")
	print("plaintext2:", binascii.hexlify(plaintxt2[:16]),"...")
コード例 #50
0
 def __init__(self, randomness):
     length = len(randomness)
     self._idx = 0
     # Fix required to get the right K (see how randint() works!)
     self._randomness = long_to_bytes(bytes_to_long(randomness) - 1, length)
コード例 #51
0
_sage_const_500 = Integer(500)
_sage_const_200 = Integer(200)
_sage_const_22 = Integer(22)
from io import IncrementalNewlineDecoder
from multiprocessing import Pool
from random import randint
from Crypto.Util.number import bytes_to_long, long_to_bytes
from sage.all import *
size = _sage_const_2**_sage_const_7

flag = b'flag{1234123412341234}'
assert len(flag) == _sage_const_22
assert flag[:_sage_const_5] == b"flag{"
assert flag[-_sage_const_1:] == b"}"
seed = flag[_sage_const_5:-_sage_const_1]  # 128 bit
seed = (bytes_to_long(seed) << _sage_const_104) + (
    randint(_sage_const_0, _sage_const_2**_sage_const_80) <<
    (_sage_const_128 + _sage_const_104))  # 312 bit
ub = seed + _sage_const_2**_sage_const_104
lb = seed

threads = _sage_const_64


def f(i):
    p = random_prime(ub, lbound=lb, proof=False)
    q = random_prime(_sage_const_2**_sage_const_200, proof=False)
    N = p * q
    return N

コード例 #52
0
# Il y avait 2^8^3 resultats possibles.

# Question 2

print("\nQuestion 2")

#  Une clé est constitué de 128 bits si on considère qu'une seule clé peut donner les caractères
#  ILOVEYOU au début du message chiffré alors on a 1 chance sur 2^128 d'avoir la bonne clé.
#  Il existe environ 3.4*10^38 clés possible, ce qui serait beaucoup trop long à chercher.

key = Crypto.Random.get_random_bytes(16)
chiffrement = AES.new(key, AES.MODE_ECB)
m_chiffre = chiffrement.encrypt(b"message_128nbits")

while not m_chiffre.hex().endswith("4c4f4c"):
    key = number.bytes_to_long(key)
    key += 1
    key = number.long_to_bytes(key)
    chiffrement = AES.new(key, AES.MODE_ECB)
    m_chiffre = chiffrement.encrypt(b"message_128nbits")

print("message" + str(m_chiffre))
print("key for bob = " + str(key.hex()))
print("message descrypt = " + chiffrement.decrypt(m_chiffre).decode("utf8"))

# Taille de l'espace des clés :
#  ILOVEYOU est constitué de 8 lettres, LOL est constitué de 3 lettres.
#  Les bits variables sont plus nombreux dans les clés pour finir un
#  message par LOL. Il peut apparaître dans beaucoup de combinaisons de ces bits variables
#  car il "prend moins de place" que ILOVEYOU
#  Place pour les autres bits dans LOL : (128bits de clé - 3 (caractères) * 8 bits)
コード例 #53
0
ファイル: jws.py プロジェクト: astagi/pyjwkest
 def sign(self, msg, key):
     # verify the key
     h = bytes_to_long(self.digest.new(msg).digest())
     return self._sign.sign(h, key)
コード例 #54
0
 def _test_verification(self, dsaObj):
     m_hash = bytes_to_long(a2b_hex(self.m_hash))
     r = bytes_to_long(a2b_hex(self.r))
     s = bytes_to_long(a2b_hex(self.s))
     self.failUnless(dsaObj._verify(m_hash, (r, s)))
     self.failIf(dsaObj._verify(m_hash + 1, (r, s)))
コード例 #55
0
from Crypto.PublicKey import RSA
from Crypto.Util.number import bytes_to_long, long_to_bytes
import os

privkey = RSA.generate(1024)
pubkey = privkey.publickey()
aeskey = bytes_to_long(os.urandom(16))
print "aeskey:", hex(aeskey)[:-1]
aeskey_enc = pubkey.encrypt(aeskey, 0)[0]
print "aeskey_enc:", hex(aeskey_enc)

i = 0
x = 0
C = aeskey_enc
N = pubkey.n
for j in range(800):
    C = (C * (2**65537) % N)
    x = 2 * x
    i += 1

while N >> i:
    print i
    C = (C * (2**65537) % N)
    res = (privkey.decrypt(C) & 1)
    if res:
        x = 2 * x + 1
    else:
        x = 2 * x
    i += 1
print hex((x + 1) * N / 2**i)
print "aeskey:", hex(aeskey)[:-1]
コード例 #56
0
ファイル: test_RSA.py プロジェクト: lisarosalina/App
    def _check_signing(self, rsaObj):
        signature = bytes_to_long(a2b_hex(self.plaintext))
        message = a2b_hex(self.ciphertext)

        # Test signing (2 argument)
        self.assertEqual((signature, ), rsaObj.sign(message, ""))
コード例 #57
0
ファイル: testgcm.py プロジェクト: zakybstrd21215/basicRAT
server.bind(host)
server.listen(5)

client.connect(host)
conn, addr = server.accept()

IV = 0
for i in range(10):
	try:
		plain = os.urandom(1024*1024*10) # 10MB
		while plain:
			cipher, tag = encryptor.encrypt(IV, plain[:4096])
			conn.send(cipher+long_to_bytes(tag, 16))

			x = client.recv(4096+16)
			cipher2 = x[:-16]
			tag2 = bytes_to_long(x[-16:])
			plain2 = decryptor.decrypt(IV, cipher2, tag2)
			assert plain[:4096] == plain2
			plain = plain[4096:]
			IV += 1
		print "10MB done!"
	except AssertionError:
		if len(plain) != len(plain2):
			print "lengths dont match!\nOrig:{}\nNew:{}".format(len(plain), len(plain2))

		print "{} out of {} are incorrect!".format(hamming(plain, plain2), len(plain2))

print "Done!"
コード例 #58
0

try:
    with open(sys.argv[1], 'rb') as fp:
        data = fp.read()
except:
    print("ERROR: Cannot read %d" % sys.argv[1])
    exit(-1)


'''
data = b"aaa"
srand(time())

key = bytes([random.randint(0,0xff) for _ in range(16)])
iv = bytes([random.randint(0,0xff) for _ in range(16)])
print(number.bytes_to_long(iv))
enc = encrypt(data, key, iv)
decrypt(enc, key)


'''
try:
    with open(sys.argv[2], 'wb') as fp:
        data = fp.write(enc)
except:
    print("ERROR: Cannot write %d" % sys.argv[2])
    exit(-1)

'''
コード例 #59
0
def sha_hash(a):
    m = hashlib.sha256()
    m.update(a)
    return bytes_to_long(m.digest()[::-1])
コード例 #60
0
                b'\x2f\xcf\x0e\x24\x49\xa6\xb5\x25' + \
                b'\xb1\x6a\xed\xf5\xaa\x0d\xe6\x57' + \
                b'\xba\x63\x7b\x39'
    auth_data = b'\xfe\xed\xfa\xce\xde\xad\xbe\xef' + \
                b'\xfe\xed\xfa\xce\xde\xad\xbe\xef' + \
                b'\xab\xad\xda\xd2'
    init_value = 0xcafebabefacedbaddecaf888
    ciphertext = b'\x42\x83\x1e\xc2\x21\x77\x74\x24' + \
                 b'\x4b\x72\x21\xb7\x84\xd0\xd4\x9c' + \
                 b'\xe3\xaa\x21\x2f\x2c\x02\xa4\xe0' + \
                 b'\x35\xc1\x7e\x23\x29\xac\xa1\x2e' + \
                 b'\x21\xd5\x14\xb2\x54\x66\x93\x1c' + \
                 b'\x7d\x8f\x6a\x5a\xac\x84\xaa\x05' + \
                 b'\x1b\xa3\x0b\x39\x6a\x0a\xac\x97' + \
                 b'\x3d\x58\xe0\x91'
    auth_tag = 0x5bc94fbc3221a5db94fae95ae7121a47

    print('plaintext:', hex(bytes_to_long(plaintext)))

    my_gcm = AES_GCM(master_key)
    encrypted, new_tag = my_gcm.encrypt(init_value, plaintext, auth_data)
    print('encrypted:', hex(bytes_to_long(encrypted)))
    print('auth tag: ', hex(new_tag))

    try:
        decrypted = my_gcm.decrypt(init_value, encrypted, new_tag + 1,
                                   auth_data)
    except InvalidTagException:
        decrypted = my_gcm.decrypt(init_value, encrypted, new_tag, auth_data)
        print('decrypted:', hex(bytes_to_long(decrypted)))