def test3(self): for keylen, taglen, result in self.tv3: key = bchr(0) * (keylen // 8 - 1) + bchr(taglen) C = b("") for i in range(128): S = bchr(0) * i N = long_to_bytes(3 * i + 1, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) cipher.update(S) C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest() N = long_to_bytes(3 * i + 2, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) C += cipher.encrypt(S) + cipher.encrypt() + cipher.digest() N = long_to_bytes(3 * i + 3, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) cipher.update(S) C += cipher.encrypt() + cipher.digest() N = long_to_bytes(385, 12) cipher = AES.new(key, AES.MODE_OCB, nonce=N, mac_len=taglen // 8) cipher.update(C) result2 = cipher.encrypt() + cipher.digest() self.assertEqual(unhexlify(b(result)), result2)
def ModExp(a, b, c): """Uses openssl, if available, to do a^b mod c where a,b,c are longs.""" if not _FOUND_SSL: return pow(a, b, c) # convert arbitrary long args to bytes bytes_a = number.long_to_bytes(a) bytes_b = number.long_to_bytes(b) bytes_c = number.long_to_bytes(c) # convert bytes to (pointer to) Bignums. bn_a = ssl.BN_bin2bn(bytes_a, len(bytes_a), 0) bn_b = ssl.BN_bin2bn(bytes_b, len(bytes_b), 0) bn_c = ssl.BN_bin2bn(bytes_c, len(bytes_c), 0) bn_result = ssl.BN_new() ctx = ssl.BN_CTX_new() # exponentiate and convert result to long ssl.BN_mod_exp(bn_result, bn_a, bn_b, bn_c, ctx) num_bytes_in_result = _NumBytesBn(bn_result) bytes_result = ctypes.create_string_buffer(num_bytes_in_result) ssl.BN_bn2bin(bn_result, bytes_result) long_result = number.bytes_to_long(bytes_result.raw) # clean up ssl.BN_CTX_free(ctx) ssl.BN_free(bn_a) ssl.BN_free(bn_b) ssl.BN_free(bn_c) ssl.BN_free(bn_result) return long_result
def _encode_simi_request(self, message): str_n = long_to_bytes(message.payload.key_n, 128) str_prefs = [long_to_bytes(preference, 128) for preference in message.payload.preference_list] fmt = "!H128s" + "128s"*len(str_prefs) packet = pack(fmt, message.payload.identifier, str_n, *str_prefs) return packet,
def _start_ccm(self, assoc_len = None, msg_len = None): if self._cipherMAC.can_reduce(): return else: if assoc_len is not None: self._assoc_len = assoc_len if msg_len is not None: self._msg_len = msg_len if None in (self._assoc_len, self._msg_len): return q = 15 - len(self.nonce) flags = 64 * (self._assoc_len > 0) + 8 * divmod(self._mac_len - 2, 2)[0] + (q - 1) b_0 = bchr(flags) + self.nonce + long_to_bytes(self._msg_len, q) assoc_len_encoded = b('') if self._assoc_len > 0: if self._assoc_len < 65536 - 256: enc_size = 2 elif self._assoc_len < 4294967296L: assoc_len_encoded = b('\xff\xfe') enc_size = 4 else: assoc_len_encoded = b('\xff\xff') enc_size = 8 assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size) self._cipherMAC._ignite(b_0 + assoc_len_encoded) prefix = bchr(q - 1) + self.nonce ctr = Counter.new(128 - len(prefix) * 8, prefix, initial_value=0) self._cipher = self._factory.new(self._key, MODE_CTR, counter=ctr) self._s_0 = self._cipher.encrypt(bchr(0) * 16) return
def decrypt(self, init_value, ciphertext, auth_tag, auth_data=b''): if init_value >= (1 << 96): raise InvalidInputException('IV should be 96-bit') if auth_tag >= (1 << 128): raise InvalidInputException('Tag should be 128-bit') if auth_tag != self.__ghash(auth_data, ciphertext) ^ \ bytes_to_long(self.__aes_ecb.encrypt( long_to_bytes((init_value << 32) | 1, 16))): raise InvalidTagException len_ciphertext = len(ciphertext) if len_ciphertext > 0: counter = Counter.new( nbits=32, prefix=long_to_bytes(init_value, 12), initial_value=2, allow_wraparound=True) aes_ctr = AES.new(self.__master_key, AES.MODE_CTR, counter=counter) if 0 != len_ciphertext % 16: padded_ciphertext = ciphertext + \ b'\x00' * (16 - len_ciphertext % 16) else: padded_ciphertext = ciphertext plaintext = aes_ctr.decrypt(padded_ciphertext)[:len_ciphertext] else: plaintext = b'' return plaintext
def add_event(self, s=''): """add_event(s:string) Add an event to the random pool. The current time is stored between calls and used to estimate the entropy. The optional 's' parameter is a string that will also be XORed into the pool. Returns the estimated number of additional bits of entropy gain. """ event = time.time()*1000 delta = self._noise() s = (s + long_to_bytes(event) + 4*chr(0xaa) + long_to_bytes(delta) ) self._addBytes(s) if event==self._event1 and event==self._event2: # If events are coming too closely together, assume there's # no effective entropy being added. bits=0 else: # Count the number of bits in delta, and assume that's the entropy. bits=0 while delta: delta, bits = delta>>1, bits+1 if bits>8: bits=8 self._event1, self._event2 = event, self._event1 self._updateEntropyEstimate(bits) return bits
def _start_mac(self): assert(self._mac_status == MacStatus.NOT_STARTED) assert(None not in (self._assoc_len, self._msg_len)) assert(isinstance(self._cache, list)) # Formatting control information and nonce (A.2.1) q = 15 - len(self.nonce) # length of Q, the encoded message length flags = (64 * (self._assoc_len > 0) + 8 * ((self._mac_len - 2) // 2) + (q - 1)) b_0 = struct.pack("B", flags) + self.nonce + long_to_bytes(self._msg_len, q) # Formatting associated data (A.2.2) # Encoded 'a' is concatenated with the associated data 'A' assoc_len_encoded = b'' if self._assoc_len > 0: if self._assoc_len < (2 ** 16 - 2 ** 8): enc_size = 2 elif self._assoc_len < (2 ** 32): assoc_len_encoded = b'\xFF\xFE' enc_size = 4 else: assoc_len_encoded = b'\xFF\xFF' enc_size = 8 assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size) # b_0 and assoc_len_encoded must be processed first self._cache.insert(0, b_0) self._cache.insert(1, assoc_len_encoded) # Process all the data cached so far first_data_to_mac = b"".join(self._cache) self._cache = b"" self._mac_status = MacStatus.PROCESSING_AUTH_DATA self._update(first_data_to_mac)
def __init__(self, x, y, curve="p256"): try: self._curve = _curves[curve] except KeyError: raise ValueError("Unknown curve name %s" % str(curve)) self._curve_name = curve modulus_bytes = self.size_in_bytes() context = self._curve.context xb = long_to_bytes(x, modulus_bytes) yb = long_to_bytes(y, modulus_bytes) if len(xb) != modulus_bytes or len(yb) != modulus_bytes: raise ValueError("Incorrect coordinate length") self._point = VoidPointer() result = _ec_lib.ec_ws_new_point(self._point.address_of(), c_uint8_ptr(xb), c_uint8_ptr(yb), c_size_t(modulus_bytes), context.get()) if result: if result == 15: raise ValueError("The EC point does not belong to the curve") raise ValueError("Error %d while instantiating an EC point" % result) # Ensure that object disposal of this Python object will (eventually) # free the memory allocated by the raw library for the EC point self._point = SmartPointer(self._point.get(), _ec_lib.ec_free_point)
def _start_mac(self): assert(self._mac_status == MacStatus.NOT_STARTED) assert(None not in (self._assoc_len, self._msg_len)) assert(isinstance(self._cache, list)) # Formatting control information and nonce (A.2.1) q = 15 - len(self.nonce) # length of Q, the encoded message length flags = (64 * (self._assoc_len > 0) + 8 * ((self._mac_len - 2) // 2) + (q - 1)) b_0 = bchr(flags) + self.nonce + long_to_bytes(self._msg_len, q) # Formatting associated data (A.2.2) # Encoded 'a' is concatenated with the associated data 'A' assoc_len_encoded = b('') if self._assoc_len > 0: if self._assoc_len < (2 ** 16 - 2 ** 8): enc_size = 2 elif self._assoc_len < (2L ** 32): assoc_len_encoded = b('\xFF\xFE') enc_size = 4 else: assoc_len_encoded = b('\xFF\xFF') enc_size = 8 assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size)
def create_user(handler, username, email): if username == 'remote': raise tornado.web.HTTPError(400) user = handler.models.users() user.username = username user.name = username user.email = email user.superuser = False user.author = False user.theme = 'css/themes/pixel/_compiled_pixel.css' user.theme_title = 'pixel' user.theme_link = 'http://nightlight.ws' user.theme_author = 'nightlight' user.theme_author_link = 'http://nightlight.ws' key = RSA.generate(1024, os.urandom) n = base64.urlsafe_b64encode(number.long_to_bytes(key.n)) e = base64.urlsafe_b64encode(number.long_to_bytes(key.e)) d = base64.urlsafe_b64encode(number.long_to_bytes(key.d)) user.magic_key = 'RSA.' + n + '.' + e user.private_key = d user.save() create_empty_content(handler, user.username, 'main', 'home', 'Hello, world.', template="feed", translate=True) create_empty_content(handler, user.username, 'main', 'photos', 'photos', template='album', translate=True) create_empty_content(handler, user.username, 'main', 'microblog', 'microblog', template='feed', translate=True) create_empty_content(handler, user.username, 'main', 'reblogged', 'reblogged', template='feed', translate=True) create_empty_content(handler, user.username, 'main', 'links', 'links', template='album', translate=True) create_empty_content(handler, user.username, 'main', 'about', 'about', view="I like turtles.", translate=True) create_empty_content(handler, user.username, 'main', 'comments', 'comments', translate=True, hidden=True) create_empty_content(handler, user.username, 'microblog', 'first', "first!", view="Hello, world.", translate=True) os.makedirs(os.path.join(handler.application.settings["private_path"], username)) os.makedirs(os.path.join(os.path.join( handler.application.settings["resource_path"], username), 'themes')) # give a blog to follow user_remote = get_remote_user_info(handler, "http://kottke.org", username) user_remote.following = 1 user_remote.save() # get some content, yo feed_response = urllib2.urlopen(user_remote.feed_url) content_remote.parse_feed(handler.models, user_remote, feed_response.read(), max_days_old=handler.constants['feed_max_days_old']) return user
def GetModulusExponentInBase64(key): """Return the public modulus and exponent for the key in bas64 encoding.""" mod = long_to_bytes(key.n) exp = long_to_bytes(key.e) modulus = base64.b64encode(mod) exponent = base64.b64encode(exp) return modulus, exponent
def serial_elgamal_privkey(privkey): """Get a 4-elements tuple of long(), return a string. This contains the private (two first elements) *and* the public key.""" ns = b64encode(long_to_bytes(privkey[0])) + ':' + \ b64encode(long_to_bytes(privkey[1])) + ':' + \ b64encode(long_to_bytes(privkey[2])) + ':' + \ b64encode(long_to_bytes(privkey[3])) return ns
def stringPrivate(self): if self.hasPrivate(): key = self.key try: return ','.join([base64.b64encode(number.long_to_bytes(i)) for i in [key.n,key.e,key.d,key.p,key.q]]) except AttributeError: return ','.join([base64.b64encode(number.long_to_bytes(i)) for i in [key.n,key.e,key.d]]) else: return ''
def exportSSHKey(self): eb = long_to_bytes(self.e) nb = long_to_bytes(self.n) if bord(eb[0]) & 0x80: eb = bchr(0x00) + eb if bord(nb[0]) & 0x80: nb = bchr(0x00) + nb keyparts = ['ssh-rsa', eb, nb] keystring = ''.join([struct.pack(">I", len(kp)) + kp for kp in keyparts]) return 'ssh-rsa ' + binascii.b2a_base64(keystring)[:-1]
def _encode_sums(self, message): str_sum = long_to_bytes(message.payload._sum, 256) sums = [] for candidate_mid, address_sum in message.payload.sums: sums.append(candidate_mid) sums.append(long_to_bytes(address_sum, 256)) fmt = "!H256s" + "20s256s" * len(message.payload.sums) packet = pack(fmt, message.payload.identifier, str_sum, *sums) return packet,
def encode_signature(cls, signature, block_size=None): ''' :param cls: :param tuple signature: signagure tuple (r, s) :param int block_size: Key block size to pad "\00"s ''' r, s = signature sig = "".join([ long_to_bytes(r, block_size), long_to_bytes(s, block_size), ]) return sig
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]
def sign(self, message): p, q, g, y, x = self.private_key dsa_obj = DSA.construct( (y, g, p, q, x) ) message_hash = hashlib.sha1(message).digest() # Get a random number that is greater than 2 and less than q. random_number = random.get_random_number_from_range(2, q) random_data = number.long_to_bytes(random_number) r, s = dsa_obj.sign(message_hash, random_data) signature = number.long_to_bytes(r, 20) + number.long_to_bytes(s, 20) return packet.pack_payload(DSS_SIG_PAYLOAD, ('ssh-dss', signature))
def create_forge_signature(msg, pub_key): # based on paper: # "Bleichenbacher's RSA-Signature Forgery" - Solving Prof. Stamp's Challenge Number 21 # Steffen Rumpf assert pub_key.e == 3, "Works only for public key 3" # input parameters l = 384 # length of the signature EB in bytes nff = 50 Data = b'\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14' # DER code Data += b'\x92\x5a\x89\xb4\x3f\x3c\xaf\xf5\x07\xdb\x0a\x86\xd2\x0a\x24\x28\x00\x7f\x10\xb6' # hash of string 'hi mom' # derived values from input parameters D = number.bytes_to_long(Data) Dlen = len(Data) de = (l-2-nff)*8 # position (in bytes) where the padding block (\xff) ens ds = (l-3-nff-Dlen)*8 # position (in bytes) where the data block starts n = l * 8 # length of the signature EB in bites x = n - 15 assert(x % 3 == 0) assert(ds > 2*x//3) N = 2**(de-ds) - D assert (N % 3 == 0) # compute G A = 2**(x//3) B = N*2**(ds-2*x//3)//3 LS7 = (A-B)**3 # left side of equation 7 on page 8 from paper RS7 = A**3 - 3*A*A*B + 3*A*B*B - B**3 # right side of equation 7 on page 8 from paper assert(RS7 == LS7) G = 3*A*B*B-B**3 # computed garbage # dpl('G:', G) EB4 = (2**x)-(2**de)+(D*2**ds)+G # EB based on equation 4 on page 6 # problem if G is too big and is mixed with data # pok = (2**x)-(2**de) # pok2 = (D*2**ds) # pok3 = pok + pok2 # dpl('pok', pok) # dpl('pok2', pok2) # dpl('pok3', pok3) # dpl('pok3+G', pok3+G) # print('len(G):', len(number.long_to_bytes(G))) # print('n-Dlen-nff:', l - Dlen - nff) assert l - Dlen - nff > len(number.long_to_bytes(G)) EB5 = 2**x - N*(2**ds) + G # EB based on equation 5.3 on page 6 assert(EB5 == EB4) assert(EB5**3 == RS7**3) assert(pow(EB5, 3, pub_key.n) == pow(RS7, 3, pub_key.n)) assert(EB5 == RS7) S = A - B # encrypted signature assert(EB4 == S**3) dpl('dec(S):', S**3) if debug: dpl('Sign. :', S) return number.long_to_bytes(S)
def encode(self, compress=True): if self.x is None: # INFINITY: return bchr(0) x_encoded = number.long_to_bytes(self.x) if not compress: y_encoded = number.long_to_bytes(self.y) return bchr(4) + x_encoded + y_encoded else: odd = self.y % 2 if odd: return bchr(3) + x_encoded else: return bchr(2) + x_encoded
def _encode_introduction_request(self, message): data = BinaryConversion._encode_introduction_request(self, message) if message.payload.preference_list: fmt = '128s'* (len(message.payload.preference_list) + 1) if message.payload.key_n: str_n = long_to_bytes(message.payload.key_n, 128) else: str_n = long_to_bytes(-1l, 128) str_prefs = [long_to_bytes(preference, 128) for preference in message.payload.preference_list] data.append(pack('!'+fmt, str_n, *str_prefs)) return data
def __init__(self): # seed: string of random bytes self._outlen = 128 self._outlen_bytes = self._outlen / 8 self._keylen = 128 self._keylen_bytes = self._keylen / 8 self._seedlen = self._keylen+self._outlen self._seedlen_bytes = self._seedlen / 8 self._biggest=2L ** self._keylen self._reseedinterval = 1000 # Internal state consists of key, vector, counter (which shows how many outputs were generated without reseed) (self.key,self.v,self.counter)=(number.long_to_bytes(0L,self._keylen_bytes),number.long_to_bytes(0L,self._keylen_bytes),0) return
def inplace_pow(self, exponent, modulus=None): exp_value = int(exponent) if exp_value < 0: raise ValueError("Exponent must not be negative") # No modular reduction if modulus is None: self._value = pow(self._value, exp_value) return self # With modular reduction mod_value = int(modulus) if mod_value < 0: raise ValueError("Modulus must be positive") if mod_value == 0: raise ZeroDivisionError("Modulus cannot be zero") # C extension only works with odd moduli if (mod_value & 1) == 0: self._value = pow(self._value, exp_value, mod_value) return self # C extension only works with bases smaller than modulus if self._value >= mod_value: self._value %= mod_value max_len = len(long_to_bytes(max(self._value, exp_value, mod_value))) base_b = long_to_bytes(self._value, max_len) exp_b = long_to_bytes(exp_value, max_len) modulus_b = long_to_bytes(mod_value, max_len) out = create_string_buffer(max_len) error = _raw_montgomery.monty_pow( out, base_b, exp_b, modulus_b, c_size_t(max_len), c_ulonglong(getrandbits(64)) ) if error: raise ValueError("monty_pow failed with error: %d" % error) result = bytes_to_long(get_raw_buffer(out)) self._value = result return self
def _start_ccm(self, assoc_len=None, msg_len=None): # CCM mode. This method creates the 2 ciphers used for the MAC # (self._cipherMAC) and for the encryption/decryption (self._cipher). # # Member _assoc_buffer may already contain user data that needs to be # authenticated. if self._cipherMAC.can_reduce(): # Already started return if assoc_len is not None: self._assoc_len = assoc_len if msg_len is not None: self._msg_len = msg_len if None in (self._assoc_len, self._msg_len): return # q is the length of Q, the encoding of the message length q = 15 - len(self.nonce) ## Compute B_0 flags = ( 64 * (self._assoc_len > 0) + 8 * divmod(self._mac_len - 2, 2)[0] + (q - 1) ) b_0 = bchr(flags) + self.nonce + long_to_bytes(self._msg_len, q) # Start CBC MAC with zero IV assoc_len_encoded = b('') if self._assoc_len > 0: if self._assoc_len < (2 ** 16 - 2 ** 8): enc_size = 2 elif self._assoc_len < (2 ** 32): assoc_len_encoded = b('\xFF\xFE') enc_size = 4 else: assoc_len_encoded = b('\xFF\xFF') enc_size = 8 assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size) self._cipherMAC._ignite(b_0 + assoc_len_encoded) # Start CTR cipher prefix = bchr(q - 1) + self.nonce ctr = Counter.new(128 - len(prefix) * 8, prefix, initial_value=0) self._cipher = self._factory.new(self._key, MODE_CTR, counter=ctr) # Will XOR against CBC MAC self._s_0 = self._cipher.encrypt(bchr(0) * 16)
def extractSecretKey(self, globalSalt, masterPassword, entrySalt): (globalSalt, masterPassword, entrySalt) = self.is_masterpassword_correct(masterPassword) if unhexlify('f8000000000000000000000000000001') not in self.key3: return None privKeyEntry = self.key3[ unhexlify('f8000000000000000000000000000001') ] saltLen = ord( privKeyEntry[1] ) nameLen = ord( privKeyEntry[2] ) privKeyEntryASN1 = decoder.decode( privKeyEntry[3+saltLen+nameLen:] ) data = privKeyEntry[3+saltLen+nameLen:] self.printASN1(data, len(data), 0) #see https://github.com/philsmd/pswRecovery4Moz/blob/master/pswRecovery4Moz.txt entrySalt = privKeyEntryASN1[0][0][1][0].asOctets() privKeyData = privKeyEntryASN1[0][1].asOctets() privKey = self.decrypt3DES( globalSalt, masterPassword, entrySalt, privKeyData ) self.printASN1(privKey, len(privKey), 0) privKeyASN1 = decoder.decode( privKey ) prKey= privKeyASN1[0][2].asOctets() self.printASN1(prKey, len(prKey), 0) prKeyASN1 = decoder.decode( prKey ) id = prKeyASN1[0][1] key = long_to_bytes( prKeyASN1[0][3] ) print_debug('DEBUG', 'key: %s' % repr(key)) return key
def _Dynamic_SignForApp(self, request, response): """Implementation of AppIdentityService::SignForApp.""" bytes_to_sign = request.bytes_to_sign() if RSA_LIB_INSTALLED: signature_bytes = rsa.pkcs1.sign( bytes_to_sign, rsa.key.PrivateKey(N, E, D, 3, 5), 'SHA-256') elif CRYPTO_LIB_INSTALLED: rsa_obj = RSA.construct((N, E, D)) hash_obj = SHA256.new() hash_obj.update(bytes_to_sign) padding_length = MODULUS_BYTES - LEN_OF_PREFIX - LENGTH_OF_SHA256_HASH - 3 emsa = (HEADER1 + (PADDING * padding_length) + HEADER2 + PREFIX + hash_obj.hexdigest()) sig = rsa_obj.sign(binascii.a2b_hex(emsa), '') signature_bytes = number.long_to_bytes(sig[0]) else: raise NotImplementedError("""Unable to import the pycrypto module, SignForApp is disabled.""") response.set_signature_bytes(signature_bytes) response.set_key_name(SIGNING_KEY_NAME)
def MGF1(mgfSeed, maskLen, hash_gen): """Mask Generation Function, described in `B.2.1 of RFC8017 <https://tools.ietf.org/html/rfc8017>`_. :param mfgSeed: seed from which the mask is generated :type mfgSeed: byte string :param maskLen: intended length in bytes of the mask :type maskLen: integer :param hash_gen: A module or a hash object from :mod:`Crypto.Hash` :type hash_object: :return: the mask, as a *byte string* """ T = b"" for counter in iter_range(ceil_div(maskLen, hash_gen.digest_size)): c = long_to_bytes(counter, 4) hobj = hash_gen.new() hobj.update(mgfSeed + c) T = T + hobj.digest() assert(len(T) >= maskLen) return T[:maskLen]
def sign(self, msg_hash): """Create the PKCS#1 v1.5 signature of a message. This function is also called ``RSASSA-PKCS1-V1_5-SIGN`` and it is specified in `section 8.2.1 of RFC8017 <https://tools.ietf.org/html/rfc8017#page-36>`_. :parameter msg_hash: This is an object from the :mod:`Crypto.Hash` package. It has been used to digest the message to sign. :type msg_hash: hash object :return: the signature encoded as a *byte string*. :raise ValueError: if the RSA key is not long enough for the given hash algorithm. :raise TypeError: if the RSA key has no private half. """ # See 8.2.1 in RFC3447 modBits = Crypto.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 em = _EMSA_PKCS1_V1_5_ENCODE(msg_hash, k) # Step 2a (OS2IP) em_int = bytes_to_long(em) # Step 2b (RSASP1) m_int = self._key._decrypt(em_int) # Step 2c (I2OSP) signature = long_to_bytes(m_int, k) return signature
def main(): import array from Crypto.PublicKey import RSA from Crypto.Util.number import long_to_bytes args = get_args(); f = open(args.key, 'r') key = RSA.importKey(f.read()) f.close f = open(args.out, 'w') f.write("#include <stdint.h>\n"); f.write("#include <stddef.h>\n\n"); f.write("const uint32_t " + args.prefix + "_exponent = " + str(key.publickey().e) + ";\n\n") f.write("const uint8_t " + args.prefix + "_modulus[] = {\n") i = 0; for x in array.array("B", long_to_bytes(key.publickey().n)): f.write("0x" + '{0:02x}'.format(x) + ",") i = i + 1; if i % 8 == 0: f.write("\n"); else: f.write(" "); f.write("};\n"); f.write("const size_t " + args.prefix + "_modulus_size = sizeof(" + \ args.prefix + "_modulus);\n") f.close()
def verify_hash(pub_algorithm_type, public_key, hash_, values): if pub_algorithm_type in (1, 3): # RSA s = long_to_bytes(values[0]) return PKCS1_v1_5.new(public_key).verify(hash_, s) elif pub_algorithm_type == 20: # ELG # TODO: Remove dependence on undocumented method sig_string = PKCS1_v1_5.EMSA_PKCS1_V1_5_ENCODE( hash_, public_key.size()) return public_key.verify(sig_string, values) elif pub_algorithm_type == 17: # DSA q = public_key.q qbits = int(math.floor(float(math.log(q, 2)))) + 1 qbytes = int(math.ceil(qbits / 8.0)) digest = hash_.digest() # Discard empty leading bytes start = 0 while digest[start] == b'\x00': start += 1 digest = digest[start:start + qbytes] return public_key.verify(bytes_to_long(digest), values) else: # TODO: complete this raise ValueError
def aes_encrypt(s): iv = long_to_bytes(random.getrandbits(BLOCK_SIZE * 8), 16) aes = AES.new(aeskey, AES.MODE_CBC, iv) return iv + aes.encrypt(pad(s))
def int2string(n): # return (n.to_bytes(((n.bit_length() + 7) //8), byteorder = "big")).decode("utf-8") return number.long_to_bytes(n)
def encrypt(key, pt): key = long_to_bytes(key) return _xor_bytes(pt, key)
# This file was *autogenerated* from the file solve.sage from sage.all_cmdline import * # import sage library _sage_const_0 = Integer(0); _sage_const_1 = Integer(1) from Crypto.Util.number import long_to_bytes import json with open('weak_rsa.json', 'r') as enonce: challenge = json.loads(enonce.read()) N = challenge['N'] ct = challenge['ct'] e = challenge['e'] F = factor(N) print(F) p = F[_sage_const_0 ][_sage_const_0 ] q = F[_sage_const_1 ][_sage_const_0 ] totient = (p-_sage_const_1 )*(q-_sage_const_1 ) d = inverse_mod(e, totient) M = long_to_bytes(pow(ct, d, N)) print(M)
from Crypto.Util.number import bytes_to_long, getPrime, inverse, long_to_bytes f = open("output.txt", "r") p = int(f.readline()[2:]) q = int(f.readline()[2:]) e = int(f.readline()[2:]) c = int(f.readline()[2:]) n = p * q phi = (p - 1) * (q - 1) d = inverse(e, phi) print(long_to_bytes(pow(c, d, n)))
from base64 import b64encode from base64 import b64decode from Crypto.Util.number import long_to_bytes # read the public key in: pubkey = RSA.importKey(open('pubkey.pem', 'r').read()) n = pubkey.n e = pubkey.e print(n, e) ct = int(open('message.txt', 'r').read()) print(ct) for d in range(0, 2**0xff): pt = pow(ct, d, n) if b"CSCG{" in long_to_bytes(pt): print(long_to_bytes(pt)) break exit() p = 0 for i in sympy.primerange(2, 1000000000): if n % i == 0: print(i) p = i break print(n % p) q = n // p #exit()
def decrypt(self, ciphertext, sentinel): """Decrypt a PKCS#1 v1.5 ciphertext. This function is named ``RSAES-PKCS1-V1_5-DECRYPT``, and is specified in `section 7.2.2 of RFC8017 <https://tools.ietf.org/html/rfc8017#page-29>`_. :param ciphertext: The ciphertext that contains the message to recover. :type ciphertext: byte string/array :param sentinel: The object to return whenever an error is detected. :type sentinel: any type :Returns: A byte string. It is either the original message or the ``sentinel`` (in case of an error). :Raises ValueError: If the ciphertext length is incorrect :Raises TypeError: If the RSA key has no private half (i.e. it cannot be used for decyption). .. warning:: You should **never** let the party who submitted the ciphertext know that this function returned the ``sentinel`` value. Armed with such knowledge (for a fair amount of carefully crafted but invalid ciphertexts), an attacker is able to recontruct the plaintext of any other encryption that were carried out with the same RSA public key (see `Bleichenbacher's`__ attack). In general, it should not be possible for the other party to distinguish whether processing at the server side failed because the value returned was a ``sentinel`` as opposed to a random, invalid message. In fact, the second option is not that unlikely: encryption done according to PKCS#1 v1.5 embeds no good integrity check. There is roughly one chance in 2\ :sup:`16` for a random ciphertext to be returned as a valid message (although random looking). It is therefore advisabled to: 1. Select as ``sentinel`` a value that resembles a plausable random, invalid message. 2. Not report back an error as soon as you detect a ``sentinel`` value. Put differently, you should not explicitly check if the returned value is the ``sentinel`` or not. 3. Cover all possible errors with a single, generic error indicator. 4. Embed into the definition of ``message`` (at the protocol level) a digest (e.g. ``SHA-1``). It is recommended for it to be the rightmost part ``message``. 5. Where possible, monitor the number of errors due to ciphertexts originating from the same party, and slow down the rate of the requests from such party (or even blacklist it altogether). **If you are designing a new protocol, consider using the more robust PKCS#1 OAEP.** .. __: http://www.bell-labs.com/user/bleichen/papers/pkcs.ps """ # See 7.2.1 in RFC3447 modBits = Crypto.Util.number.size(self._key.n) k = ceil_div(modBits, 8) # Convert from bits to bytes # Step 1 if len(ciphertext) != k: raise ValueError("Ciphertext with incorrect length.") # Step 2a (O2SIP) ct_int = bytes_to_long(bstr(ciphertext)) # Step 2b (RSADP) m_int = self._key._decrypt(ct_int) # Complete step 2c (I2OSP) em = long_to_bytes(m_int, k) # Step 3 sep = em.find(bchr(0x00), 2) if not em.startswith(b('\x00\x02')) or sep < 10: return sentinel # Step 4 return em[sep + 1:]
p = 158159478878761530015480734596710635728851979459825262315584221254998635498371273604436610427414896331113518324187833743447179637289023975068908646073000396079074167858011113898197876202540464207413407825023363690931058178635079121324438475400371872824929009648448615823482151882125509270703057803445176823343 q = 111042069916815988715000482866794094862821090937833039810186309959432941864367826000858242284135238021862076916117522427937922681473180939435174154091870953125012567774551178328260877731359363159686278415952833297758240205525159136161381235914502698651455762300671246905122463562104907216508756977378745564981 n = 17562355911662619453405570925068270432703852898336822669760131673647056178200323849549783403908678936145139505519916799703915437002684256115362515013208250307874876856722795442219717278385232954544796246286548686927201742395272493617063721632231017896398255662601685885447030305102692295041381094155828469526264943978232324678937271552022644862107714679939399684542729724913722218186401992976472659127291106115088838751530710239692665962681411584676256202789630089405539608544875836042970616648716573702036672309755706272831472405157224418128838750024870610510055087037359498281578113552449187812592058327491364151483 e = 65537 c = 4649741919214445766275522931504844475998095575434101369750761956476938451808159368526732637298226434680313166004167140476885185659921120194210679239880876127975899769317271739082623022623581368754657513239359972634849357036043473190422543867666301821955949297216919484694491681816982957215262667270833401035991704072193414784773508500306176736260837552553902124417378366163788960582948157059651620917621461708927844590014224170032003385655440557339175872023609706049680927495916313202145254231775778494745611504693882053546500273561453621600843722227740852914095112852058259514778419308284754879080766260231999487998 from Crypto.Util.number import long_to_bytes #phi, dの計算 phi = (p-1)*(q-1) d = pow(e, -1, phi) #decryption m = pow(c, d, n) print(long_to_bytes(m))
def ecdsa_sign(msg, privkey): hsh = md5(msg).digest() nonce = md5(hsh + long_to_bytes(privkey.secret_multiplier)).digest() * 2 sig = privkey.sign(bytes_to_long(msg), bytes_to_long(nonce)) return msg, sig.r, sig.s
def encode(self): """Return a complete INTEGER DER element, fully encoded as a TLV.""" self.payload = long_to_bytes(self.value) if bord(self.payload[0]) > 127: self.payload = bchr(0x00) + self.payload return DerObject.encode(self)
Klen = 128 mode = sys.argv[1] infile = sys.argv[2] outfile = sys.argv[3] key = long(sys.argv[4]) mod = long(sys.argv[5]) M = long(sys.argv[6]) if mode == "e": f = open(infile, "r") msg = f.read() f.close() keyP = urandom(keylen) nonce = urandom(noncelen) KP = number.bytes_to_long(keyP) K = number.long_to_bytes(encrypt(number.bytes_to_long(keyP), key, mod, M)) print len(K) ctxt = crypt(msg, keyP, nonce) f = open(outfile, "w") f.write(K + nonce + ctxt) f.close() elif mode == "d": f = open(infile, "r") data = f.read() f.close() K = data[:Klen] nonce = data[Klen:Klen + noncelen] msg = data[noncelen + Klen:len(data) - 1] KP = decrypt(number.bytes_to_long(K), key, mod) keyP = number.long_to_bytes(decrypt(number.bytes_to_long(K), key, mod, M)) ptxt = crypt(msg, keyP, nonce)
def _shift_bytes(bs, xor_lsb=0): num = (bytes_to_long(bs) << 1) ^ xor_lsb return long_to_bytes(num, len(bs))[-len(bs):]
#!/usr/bin/python from Crypto.Util.number import long_to_bytes line = open("../translation/lights.txt", "r").read().split('\n') print(line[0]) num_normal = line[0].replace('\t', '').replace(' ', '') num_xor = line[0].replace('\t', '').replace(' ', '').replace('0', 'a').replace( '1', '0').replace('a', '1') print(int(num_normal, 2)) print(int(num_xor, 2)) print(str(long_to_bytes(int(num_normal, 2)))) print(str(long_to_bytes(int(num_xor, 2))))
#!/usr/bin/env python3 # from https://blog.cryptohack.org/cryptoctf2020#decent-rsa from Crypto.PublicKey import RSA from Crypto.Util.number import long_to_bytes, bytes_to_long flag = bytes_to_long(open("flag.enc","rb").read()) key = RSA.import_key(open("mykey.pem").read()) n = Integer(key.n) poly = sum(e * x^i for i,e in enumerate(Integer(key.n).digits(11))) (p, _), (q, _) = poly.factor_list() p, q = p(x=11), q(x=11) assert p*q == n d = inverse_mod(key.e, (p-1)*(q-1)) print(long_to_bytes(pow(flag, d, n)))
from Crypto.Util.number import long_to_bytes,inverse p_msb = 10782851882643568436690840861500470716392138950798808847901800880356088489358510127370728036479767973147003063168467186230765513438172292951359505497400115 q_lsb = 156706242812597368863822639576094365104687347205289704754937898429597824385199919052246554900504787988024439652223718201546746425116946202916886816790677 n = 20478919136950514294245372495162786227530374921935352984649681539174637614643555669008696530509252361041808530044811858058082236333967101803171893140577890580969033423481448289254067496901793538675705761458273359594646496576699260837347827885664785268524982706033238656594857347183110547622966141595910495419030633639738370191942836112347256795752107944630943134049527588823032184661809251580638724245630054912896260630873396364113961677176216533916990437967650967366883162620646560056820169862154955001597314689326441684678064934393012107591102558185875890938130348512800056137808443281706098125326248383526374158851 e = 65537 ct = 19386365681911176116962673929966212779218446893629616096165535479988405148285413619761557889189211704676408056225729231312267774666516067344628902420462860500796694348719854753450503310214423075716290790730397428257808016249943644108687242803494660111203848028946883397960407526446222857172233473980414880412616288479351174943750112131566288658840674793729931330990659775746679427920973741044231239820653713719744056152497641552948891194509604049453065742204369183052918461477609558512635361757334304706673378249269583497003794274869298361016417188996692715520035544727779966978038114830108861813134381830342160591600 n_lsb = n%pow(2,512) p_lsb = (n_lsb * inverse(q_lsb,pow(2,512)))%pow(2,512) p = pow(2,512)*p_msb + p_lsb q = n//p assert p*q == n phi = (p-1)*(q-1) d = inverse(e,phi) pt = long_to_bytes(pow(ct,d,n)) print(pt)
def crypt(message, exponent, modulus): return number.long_to_bytes( pow(Integer(number.bytes_to_long(message)), exponent, modulus))
from pwn import * from Crypto.Util.number import long_to_bytes,bytes_to_long p = remote("47.97.215.88",10001) p.recvuntil('c:') p.sendline(("A"*0x20).encode('hex')) c = p.recv(64) # print c p0 = c[:32] p1 = c[32:] iv = bytes_to_long(p0.decode('hex'))^bytes_to_long(p1.decode('hex'))^bytes_to_long("A"*0x10) print long_to_bytes(iv) p.interactive()
for test_data in test_cases: test_gcm = AES_GCM(test_data['master_key']) encrypted, tag = test_gcm.encrypt(test_data['init_value'], test_data['plaintext'], test_data['auth_data']) states = [] tags = [] ivs = [] aads = [] # extra encryptions s = encrypted for i in range(1000): iv = getrandbits(96) a = long_to_bytes(getrandbits(1024)) s, t = test_gcm.encrypt(iv, s, a) states.append(s) tags.append(t) ivs.append(iv) aads.append(a) # extra decryptions for i in range(999, -1, -1): assert s == states[i] iv = ivs[i] t = tags[i] a = aads[i] s = test_gcm.decrypt(iv, s, t, a) encrypted = s
tG = (0, 2) io.sendlineafter(b"tG = ", str(tG).encode()) inp = (b"\x00" * 64).hex() io.sendline(inp.encode()) msg = b'\x00' * 31 send_output = bytes.fromhex(io.recvline().strip().decode()) share = xor(pad(msg, 64), send_output) stG = from_bytes(share) s = discrete_log(Mod(stG[1], p), Mod(2, p)) inp = (b"flag\x00").hex() io.sendline(inp.encode()) send_output = bytes.fromhex(io.recvline().strip().decode()) ct = unpad(xor(send_output, share)) aes = AES.new(key=sha256(long_to_bytes(s)).digest(), mode=AES.MODE_ECB) FLAG = aes.decrypt(ct) except: io.close() continue if FLAG.startswith(b"zer0pts{"): print(FLAG) break # zer0pts{edwards_what_the_hell_is_this}
def main(): ### Solutions: Encoding print('--- ENCODING ---') # 1 a = [ 99, 114, 121, 112, 116, 111, 123, 65, 83, 67, 73, 73, 95, 112, 114, 49, 110, 116, 52, 98, 108, 51, 125 ] sol_1 = "".join([chr(i) for i in a]) print(sol_1) # 2 b = '63727970746f7b596f755f77696c6c5f62655f776f726b696e675f776974685f6865785f737472696e67735f615f6c6f747d' print(bytes.fromhex(b).decode('ascii')) # 3 c = '72bca9b68fc16ac7beeb8f849dca1d8a783e8acf9679bf9269f7bf' print(base64.b64encode(bytes.fromhex(c)).decode('ascii')) # 4 d = 11515195063862318899931685488813747395775516287289682636499965282714637259206269 print(long_to_bytes(d).decode('ascii')) # encoding_challenge() ### Solutions: XOR print('--- XOR ---') # 1 a = "label" b = 13 c = "" for i in a: c += chr(b ^ ord(i)) print("crypto{" + c + "}") #2 KEY1 = 0xa6c8b6733c9b22de7bc0253266a3867df55acde8635e19c73313 KEY2KEY1 = 0x37dcb292030faa90d07eec17e3b1c6d8daf94c35d4c9191a5e1e KEY2KEY3 = 0xc1545756687e7573db23aa1c3452a098b71a7fbf0fddddde5fc1 FLAGKEY1KEY3KEY2 = 0x04ee9855208a2cd59091d04767ae47963170d1660df7f56f5faf res = FLAGKEY1KEY3KEY2 ^ KEY2KEY3 ^ KEY1 print(dec(res)) #3 a = hex( 0x73626960647f6b206821204f21254f7d694f7624662065622127234f726927756d) for i in range(128): current = '' for j in range(2, len(a), 2): current += chr(int(a[j:j + 2], 16) ^ i) if current.find("crypto") != -1: print(current) break #4 a = '0' + hex( 0x0e0b213f26041e480b26217f27342e175d0e070a3c5b103e2526217f27342e175d0e077e263451150104 )[2:] start = "crypto{1" keys = [] for i in range(len(start)): # print(a[2*i:2*i + 2], start[i]) keys.append(ord(start[i]) ^ int(a[2 * i:2 * i + 2], 16)) ret = "" # print(keys) for i in range(0, len(a), 2): ret += chr(keys[(i // 2) % len(keys)] ^ int(a[i:i + 2], 16)) print(ret) #5 lemur_xor() print('--- MATH ---') # Math # 1 a = 66528 b = 52920 print(gmpy2.gcd(a, b)) # 2 p = 26513 q = 32321 res = base_solution_linear(1, p, q) # x, y = symbols("x, y") # print(diophantine(p*x + q*y - 1)) print("crypto{" + str(res[0]) + "," + str(res[1]) + "}") # 3 print(8146798528947 % 17) # 4 print(pow(273246787654, 65536, 65537)) # 5 print(gmpy2.invert(3, 13)) # Data Formats print('--- DATA FORMATS ---') # https://www.cryptologie.net/article/260/asn1-vs-der-vs-pem-vs-x509-vs-pkcs7-vs/ # private key: # -----BEGIN RSA PRIVATE KEY----- # MIIEowIBAAKCAQEAzvKDt+EO+A6oE1LItSunkWJ8vN6Tgcu8Ck077joGDfG2NtxD # 4vyQxGTQngr6jEKJuVz2MIwDcdXtFLIF+ISX9HfALQ3yiedNS80n/TR1BNcJSlzI # uqLmFxddmjmfUvHFuFLvxgXRga3mg3r7olTW+1fxOS0ZVeDJqFCaORRvoAYOgLgu # d2/E0aaaJi9cN7CjmdJ7Q3m6ryGuCwqEvZ1KgVWWa7fKcFopnl/fcsSecwbDV5hW # fmvxiAUJy1mNSPwkf5YhGQ+83g9N588RpLLMXmgt6KimtiWnJsqtDPRlY4Bjxdpu # V3QyUdo2ymqnquZnE/vlU/hn6/s8+ctdTqfSCwIDAQABAoIBAHw7HVNPKZtDwSYI # djA8CpW+F7+Rpd8vHKzafHWgI25PgeEhDSfAEm+zTYDyekGk1+SMp8Ww54h4sZ/Q # 1sC/aDD7ikQBsW2TitVMTQs1aGIFbLBVTrKrg5CtGCWzHa+/L8BdGU84wvIkINMh # CtoCMCQmQMrgBeuFy8jcyhgl6nSW2bFwxcv+NU/hmmMQK4LzjV18JRc1IIuDpUJA # kn+JmEjBal/nDOlQ2v97+fS3G1mBAaUgSM0wwWy5lDMLEFktLJXU0OV59Sh/90qI # Jo0DiWmMj3ua6BPzkkaJPQJmHPCNnLzsn3Is920OlvHhdzfins6GdnZ8tuHfDb0t # cx7YSLECgYEA7ftHFeupO8TCy+cSyAgQJ8yGqNKNLHjJcg5t5vaAMeDjT/pe7w/R # 0IWuScCoADiL9+6YqUp34RgeYDkks7O7nc6XuABi8oMMjxGYPfrdVfH5zlNimS4U # wl93bvfazutxnhz58vYvS6bQA95NQn7rWk2YFWRPzhJVkxvfK6N/x6cCgYEA3p21 # w10lYvHNNiI0KBjHvroDMyB+39vD8mSObRQQuJFJdKWuMq+o5OrkC0KtpYZ+Gw4z # L9DQosip3hrb7b2B+bq0yP7Izj5mAVXizQTGkluT/YivvgXcxVKoNuNTqTEgmyOh # Pn6w+PqRnESsSFzjfWrahTCrVomcZmnUTFh0rv0CgYBETN68+tKqNbFWhe4M/Mtu # MLPhFfSwc8YU9vEx3UMzjYCPvqKqZ9bmyscXobRVw+Tf9llYFOhM8Pge06el74qE # IvvGMk4zncrn8LvJ5grKFNWGEsZ0ghYxJucHMRlaU5ZbM6PEyEUQqEKBKbbww65W # T3i7gvuof/iRbOljA9yzdwKBgQDT9Pc+Fu7k4XNRCon8b3OnnjYztMn4XKeZn7KY # GtW81eBJpwJQEj5OD3OnYQoyovZozkFgUoKDq2lJJuul1ZzuaJ1/Dk+lR3YZ6Wtz # ZwumCHnEmSMzWyOT4Rp2gEWEv1jbPbZl6XyY4wJG9n/OulqDbHy4+dj5ITb/r93J # /yLCBQKBgHa8XYMLzH63Ieh69VZF/7jO3d3lZ4LlMEYT0BF7synfe9q6x7s0ia9b # f6/QCkmOxPC868qhOMgSS48L+TMKmQNQSm9b9oy2ILlLA0KDsX5O/Foyiz1scwr7 # nh6tZ+tVQCRvFviIEGkaXdEiBN4eTbcjfc5md/u9eA5N21Pzgd/G # -----END RSA PRIVATE KEY----- # d = '7C:3B:1D:53:4F:29:9B:43:C1:26:08:76:30:3C:0A:95:BE:17:BF:91:A5:DF:2F:1C:AC:DA:7C:75:A0:23:6E:4F:81:E1:21:0D:27:C0:12:6F:B3:4D:80:F2:7A:41:A4:D7:E4:8C:A7:C5:B0:E7:88:78:B1:9F:D0:D6:C0:BF:68:30:FB:8A:44:01:B1:6D:93:8A:D5:4C:4D:0B:35:68:62:05:6C:B0:55:4E:B2:AB:83:90:AD:18:25:B3:1D:AF:BF:2F:C0:5D:19:4F:38:C2:F2:24:20:D3:21:0A:DA:02:30:24:26:40:CA:E0:05:EB:85:CB:C8:DC:CA:18:25:EA:74:96:D9:B1:70:C5:CB:FE:35:4F:E1:9A:63:10:2B:82:F3:8D:5D:7C:25:17:35:20:8B:83:A5:42:40:92:7F:89:98:48:C1:6A:5F:E7:0C:E9:50:DA:FF:7B:F9:F4:B7:1B:59:81:01:A5:20:48:CD:30:C1:6C:B9:94:33:0B:10:59:2D:2C:95:D4:D0:E5:79:F5:28:7F:F7:4A:88:26:8D:03:89:69:8C:8F:7B:9A:E8:13:F3:92:46:89:3D:02:66:1C:F0:8D:9C:BC:EC:9F:72:2C:F7:6D:0E:96:F1:E1:77:37:E2:9E:CE:86:76:76:7C:B6:E1:DF:0D:BD:2D:73:1E:D8:48:B1' # d = int(d.replace(":", "").lower(),16) # print(d) # 1 f = open( '/Users/Kvothe/Downloads/privacy_enhanced_mail_1f696c053d76a78c2c531bb013a92d4a.pem', 'r') key = RSA.importKey(f.read()) print(key.d) # 2 f = open( '/Users/Kvothe/Downloads/2048b-rsa-example-cert_3220bd92e30015fe4fbeb84a755e7ca5.der', 'rb') cert = Certificate.load(f.read()) n = cert.public_key.native["public_key"]["modulus"] print(n) # 3 # from openssh -> openssl, the command is: # ssh-keygen -f ~/Downloads/bruce_rsa_6e7ecd53b443a97013397b1a1ea30e14.pub -e -m pem pub_key = ''' -----BEGIN RSA PUBLIC KEY----- MIIBigKCAYEArTy6m2vhhbwx3RVbNVb3ZOenCqqsOXHaJpbtN+OuulLKBSKpIoPB +ZDbDXn0qWkf4lOxtGSgolkUbgG07Lhzfgs+dul4UL84CkwZExmF3Rf1nRv+v7pq Lt2dPsCb02YLxJnhHJb4rQaz2ZM4QCtTOcqYDUeKfLHCaZU4Ekm/OApKrpfw4/0o fn8KOrFN0t4/dqnNuwVRgoaUIhsI47reApB2rs0AP4CggSIi8s6BXCxB4YzgThBK 5760T1giACYQC5MFdq1Gw+INSFmu0CNqt5wdJ5Z4z5448Gke06R+IMtjUiGDQ3Qt T2fK3gWhZxk14M4UNrdETgTW/mQ4B/BcvikxvoBGpKbttG0agfOjTen6wyzpGfcd 8N9rSbaqqyUwC8uDotzFtFzzutVAU9d91TagGzWBhNoMfplwVTns27GOOgv1dn5s QSSSmP0hTbPMDlThysKkR9BiOVbBtWGQpV936pPBgyWERGqMqC9xykLdVHv2Vu05 T0WMwKCAetgtAgMBAAE= -----END RSA PUBLIC KEY----- ''' f = open('/Users/exodia/Downloads/temp.pub', 'rb') key = RSA.importKey(f.read()) print(key.n)
g = 2 h = 5923777823209700421469794715930707999603487655981898449422357892842755521580568679804163539045179031106270014117273256138784597448478681230177860742155126020891697304006323076401490928335945940433914000224942851432511054551297211008666155463440349151664091937182131690171219715116514941592010447430791360540405344375229764599137242861289702073288011925063924328894521058436970565773435861877845797623536121104737287522040686798356660172000949381134222388515860802189384620507145354577028032863068824932528242026641123078630467060464312266151210808593836663684389223953685674628245634895912216995332139498891675729412 c1 = 15841669642799513382703370925818603902178481700840923545161934033100321146503868084900588927217114442984665667118577460536333117230632804458376545287474648588544547729069115731250096936465515738625518450188268415821956969922852821647959850165919691407147865613743286785729203868402483239513506078001926659569565849700817814912100477836551259556302047076140353950038140029083836368974735448112871859247145645453893923391402871253724681937402767600197890986879062368248591021917068730257429951826927119347881638519929753889728430033506371881478198610975214380168432419330014512081038469904388307938017575601466078331 c2 = 20980308195739585388840251875894742881015221885545911313167621997395787966965548427206821550213656074368310837496870246619475986341470484218595157539041479851684547924269518062835988910911073116548655352026577430899732878513271956656411255378657274224370632108816250357258256150126995560372349572226592270801770838453129888601424824757605125058051809002236802317316196644553976816559756081413743782144333098102299253043861839609099043946460148665729842204444861357854613348892896741322096121717577094380240894407806459966780100562260797920508366840383783646472267409058679509229807645391852867935100760134156182491258 c3 = 8768904047563298886677169490168966918289414985832644718096574517784880975022962509795321763779973065822432474276416651649440365959257898194342877431868745294123297870605865108493631284726686261522659805830253900535747398181168941751180447773297778677873767229967190043047685579392976663195267795930621740348638971638706010381180768233144807436468668964440515306883051182948872274265210980201579370835434913930464144976209730794967147771068759981878121882251813678009953937372758046102350807904409198972406766754752805360940861853628252305581781137391990429572312294938928362179624036117073389171261150785030059942700 c4 = 12419488730698545222115481492826327418183847269300030422995155223415630809493624190775635185379251633065966549409377646355800112282055135265736181220902815799724890425646572569790421862882454912487390159481544401843947443811007638547710771538442363518838542263860684960530576719043710264783536000942502727944917408604286626500621436987817454054231149361731578883237987166673909936148875055293359385883081052143807370574958268369136151036900599962029346106705537504388285348786707027659284707274236386361322674190379777320389067182303351999598272876640517896042738583060420187081299052833129083724447908208591843475415 c5 = 893080780847029308274368681626396600544552126739521651988181136070723657543202683032261498325901020944475593266721439986252726873062695009497285774781273260130239745474015391340529247148058595404619391551322915025208509283875397114215549153709849346098436514795077421458424610465081882068973513047489507486230979086379409741932617830527701505914453068243484824842279321520744845448756056173897047235145941395998598944605479721007044142742978104184434880292930861342829032141972304138117176917850956879325010172288994354786300970756893134182379388928648735221668466326903408032033190979181535192541717780216521755417 c6 = 16868695083816857505525800089097271185876848841301707567306597144688987136931134316383219718073977930675156941799554672612516843000698040756468634987830778172726733979425034239197711544850508187314268912664964061281971223339500805558570744831427221658098395054065010277234268617177911315906985931860998693904334148966175585880156089003987558061775469386726909446851603579135820201969656107310555594055598854138027941045512761491606258593138818466535674945168236687421754609812862791737412954920661002572895863532056545967733591085239242214334504365106259154818608898010639219811488029915088258497107896046238832347974 c7 = 22543584088396321036073704741445732833828615255896626993147692913487656144433571133095290179136895878897238887141815210840825558830460205527234325755110105928898100245676528580333428166430746940888021117427553444598761941676787745543364106259403320365964432467548035442914745962224237417711706291287705848283463556371649405099933235392590179601260277033799092945753465987657230794701991995662276994641370874513661340530682820867275088497184726551556455147601774549402576858090182373407319790496781367229552096246168860656650524710278724322125643710412050513128777805707934506977056497817567835653483582997260528950451 # enc : msg, h -> g^y, h^y * msg # dec : r, c, x -> c * r^-x v1 = c1 f1 = long_to_bytes(v1) v3 = (c1 * c3 * inverse(c2, p)) % p f3 = long_to_bytes(v3) # f3 = c4 * ? # f5 = c5 * ?^2 v5 = ((c5 * v3 * v3 * inverse(c4**2, p))) % p f5 = long_to_bytes(v5) # f6 = c6 * ? # f7 = c7 * ? / h v7 = (c7 * v5 * inverse(c6, p) * inverse(h, p)) % p f7 = long_to_bytes(v7)
import math from Crypto.Util.number import inverse, long_to_bytes, isPrime def getModInverse(a, m): if math.gcd(a, m) != 1: return None u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % m p = 115502906812186413716028212900548735990904256575141882752425616464266991765240920703188618324966988373216520827723741484031611192826120314542453727041306942082909556327966471790487878679927202639569020757238786152140574636623998668929044300958627146625246115304479897191050159379832505990011874114710868929959 q = 151086174643947302290817794140091756798645765602409645643205831091644137498519425104335688550286307690830177161800083588667379385673705979813357923016141205953591742544325170678167010991535747769057335224460619777264606691069942245683132083955765987513089646708001710658474178826337742596489996782669571549253 msg = 0x50fb0b3f17315f7dfa25378fa0b06c8d955fad0493365669bbaa524688128ee9099ab713a3369a5844bdd99a5db98f333ef55159d3025630c869216889be03120e3a4bd6553d7111c089220086092bcffc5e42f1004f9888f25892a7ca007e8ac6de9463da46f71af4c8a8f806bee92bf79a8121a7a34c3d564ac7f11b224dc090d97fdb427c10867ad177ec35525b513e40bef3b2ba3e6c97cb31d4fe3a6231fdb15643b84a1ce704838d8b99e5b0737e1fd30a9cc51786dcac07dcb9c0161fc754cda5380fdf3147eb4fbe49bc9821a0bcad98d6df9fbdf63cf7d7a5e4f6cbea4b683dfa965d0bd51f792047e393ddd7b7d99931c3ed1d033cebc91968d43f e = 65537 n = p * q phi = (p - 1) * (q - 1) d = getModInverse(e, phi) pt = pow(msg, d, n) print(long_to_bytes(pt))
return bytes(out) def decrypt(cipher: bytes, key: bytes) -> bytes: blocks = to_blocks(cipher) out = bytearray() key = expand_key(key, len(blocks)) for idx, block in enumerate(blocks): for _ in range(ROUNDS): block = bytearray(block) for i in range(len(block)): block[i] ^= key[idx] block = dec_perm(block) block = dec_sub(block) out.extend(block) return bytes(out) flag_enc = b64decode( b'hQWYogqLXUO+rePyWkNlBlaAX47/2dCeLFMLrmPKcYRLYZgFuqRC7EtwX4DRtG31XY4az+yOvJJ/pwWR0/J9gg==' ) key_set = { expand_key(long_to_bytes(i), 8): long_to_bytes(i) for i in range(65536) } for key in key_set.values(): a = decrypt(flag_enc, key) if a.startswith(b'rgb'): print(a, key)
print(r.recvline()) print(r.recvline()) print(r.recvline()) print(r.recvline()) print(r.recvline()) print(r.recvline()) T = r.recvline().strip().decode() print(r.recvline()) V = r.recvline().strip().decode() print(r.recvline()) print(r.recvline()) print(r.recvline()) print(r.recvline()) print(r.recvline()) return T, V print(r.recvline()) print(r.recvline()) print(r.recvline()) T, V = FLAG() print(r.recvline()) print(r.recvline()) RES = TALK(V) A = int(T, 16) B = int(RES, 16) print(long_to_bytes(A ^ B))
def decrypt(key, ct): key = long_to_bytes(key) return _xor_bytes(ct, key)
def bytes(self, a): return long_to_bytes(a)
def decode(self, a): data = long_to_bytes(a) assert data[0] == 0xff and data[-1] == 0xff return data[1:-2]
enc_secret = Integer(int(f.readline().strip()[2:], 16)) N = GCD(ENC2 - enc2, ENC3 - enc3) for j in range(2, 1 << 16): while N % j == 0: N = N // j assert 1022 <= int(N).bit_length() <= 1024 res.append(enc_secret) mod.append(N) while len(res) != 1: print(len(res)) nxtres = [] nxtmod = [] for i in tqdm(range(0, len(res), 2)): cc = crt(res[i], res[i + 1], mod[i], mod[i + 1]) md = mod[i] * mod[i + 1] // GCD(mod[i], mod[i + 1]) nxtres.append(cc) nxtmod.append(md) res = nxtres mod = nxtmod res = res[0] master_secret = inthroot(Integer(res), 65537) assert master_secret**65537 == res print(master_secret) secret = long_to_bytes(int(master_secret), 8) cipher = AES.new(secret, AES.MODE_CBC, b'\x00' * 16) print(cipher.decrypt(enc_flag))
def extractSecretKey(masterPassword, keyData): # 3DES # see http://www.drh-consultancy.demon.co.uk/key3.html pwdCheck = keyData[b'password-check'] entrySaltLen = pwdCheck[1] entrySalt = pwdCheck[3: 3 + entrySaltLen] encryptedPasswd = pwdCheck[-16:] globalSalt = keyData[b'global-salt'] if args.verbose: print('password-check=%s' % hexlify(pwdCheck)) print('entrySalt=%s' % hexlify(entrySalt)) print('globalSalt=%s' % hexlify(globalSalt)) cleartextData = decryptMoz3DES(globalSalt, masterPassword, entrySalt, encryptedPasswd) if cleartextData != b'password-check\x02\x02': print('password check error, Master Password is certainly used, please provide it with -p option') sys.exit() if CKA_ID not in keyData: return None privKeyEntry = keyData[CKA_ID] saltLen = privKeyEntry[1] nameLen = privKeyEntry[2] # print 'saltLen=%d nameLen=%d' % (saltLen, nameLen) privKeyEntryASN1 = decoder.decode(privKeyEntry[3 + saltLen + nameLen:]) data = privKeyEntry[3 + saltLen + nameLen:] printASN1(data, len(data), 0) # see https://github.com/philsmd/pswRecovery4Moz/blob/master/pswRecovery4Moz.txt ''' SEQUENCE { SEQUENCE { OBJECTIDENTIFIER 1.2.840.113549.1.12.5.1.3 pbeWithSha1AndTripleDES-CBC SEQUENCE { OCTETSTRING entrySalt INTEGER 01 } } OCTETSTRING privKeyData } ''' entrySalt = privKeyEntryASN1[0][0][1][0].asOctets() privKeyData = privKeyEntryASN1[0][1].asOctets() privKey = decryptMoz3DES(globalSalt, masterPassword, entrySalt, privKeyData) print('decrypting privKeyData') if args.verbose: print('entrySalt=%s' % hexlify(entrySalt)) print('privKeyData=%s' % hexlify(privKeyData)) print('decrypted=%s' % hexlify(privKey)) printASN1(privKey, len(privKey), 0) ''' SEQUENCE { INTEGER 00 SEQUENCE { OBJECTIDENTIFIER 1.2.840.113549.1.1.1 pkcs-1 NULL 0 } OCTETSTRING prKey seq } ''' privKeyASN1 = decoder.decode(privKey) prKey = privKeyASN1[0][2].asOctets() print('decoding %s' % hexlify(prKey)) printASN1(prKey, len(prKey), 0) ''' SEQUENCE { INTEGER 00 INTEGER 00f8000000000000000000000000000001 INTEGER 00 INTEGER 3DES_private_key INTEGER 00 INTEGER 00 INTEGER 00 INTEGER 00 INTEGER 15 } ''' prKeyASN1 = decoder.decode(prKey) id = prKeyASN1[0][1] key = long_to_bytes(prKeyASN1[0][3]) if args.verbose: print('key=%s' % (hexlify(key))) return key
def encryptFlag(privkey, flag): key = md5(long_to_bytes(privkey.secret_multiplier)).digest() iv = urandom(16) cipher = AES.new(key, AES.MODE_CBC, iv) ciphertext = cipher.encrypt(pad(flag, 16)) return ciphertext, iv