예제 #1
0
파일: c11.py 프로젝트: kuzeygh/crypto
def encryption_oracle(plain):
    key_length = 16
    block_size = 16
    rng = SystemRandom()
    key = random_bytes(key_length)
    mode = rng.randrange(1, 3)
    iv = random_bytes(block_size)

    if mode == AES.MODE_ECB:
        aes = AES.new(key, mode)
    else:
        aes = AES.new(key, mode, iv=iv)

    prefix = random_bytes(rng.randrange(5, 11))
    suffix = random_bytes(rng.randrange(5, 11))
    plain = pad(prefix + plain + suffix, block_size)
    return aes.encrypt(plain)
예제 #2
0
파일: game.py 프로젝트: TeeKay18/WWTBAM
class Game:
    def __init__(self, guaranteed_questions: List[int]):
        self.guaranteed_questions = guaranteed_questions
        self.question_number = 1
        self.game_on = False
        self.question_shown = False
        self.question_answered = False
        self.current_question = []
        self.fifty_fifty = 0
        self.switch = 0
        self.double_dip = 0
        self.guaranteed_sum = 0
        self.rng = SystemRandom()

        self.questions_path = Path("app") / "questions" / "questions.txt"
        self.music_path = Path("app") / "music"

        common_symbols = ["q" + str(i) for i in range(5, 16)]
        common_symbols_two = ["q1-5", "q6-11", "q7-12", "q8-13", "q9-14"]

        question_theme_symbols = ["q1-5"] + common_symbols[1:]
        question_themes = [
            self.music_path / (symbol + "music.mp3")
            for symbol in question_theme_symbols
        ]

        final_ans_symbols = common_symbols_two[1:] + ["q10-15"]
        final_ans_themes = [
            self.music_path / (symbol + "final.mp3")
            for symbol in final_ans_symbols
        ]

        correct_ans_symbols = ["q1-4"] + common_symbols
        correct_ans_themes = [
            self.music_path / (symbol + "correct.mp3")
            for symbol in correct_ans_symbols
        ]

        wrong_ans_symbols = common_symbols_two + ["q10"] + ["q15"]
        wrong_ans_themes = [
            self.music_path / (symbol + "wrong.mp3")
            for symbol in wrong_ans_symbols
        ]

        lets_play_symbols = common_symbols_two + ["q10-15"]
        lets_play_symbols.remove("q6-11")
        lets_play_symbols.insert(1, "q6")
        lets_play_symbols.append("q11")
        lets_play_themes = [
            self.music_path / (symbol + "letsplay.mp3")
            for symbol in lets_play_symbols
        ]

        self.lifeline_themes = [
            self.music_path / "50-50.mp3",
            self.music_path / "doubledip1guess.mp3",
            self.music_path / "doubledip1ans.mp3",
            self.music_path / "doubledip2guess.mp3",
            self.music_path / "doubledip2ans.mp3",
            self.music_path / "switchthequestion.mp3"
        ]

        fst_guaranteed = guaranteed_questions[0]
        snd_guaranteed = guaranteed_questions[1]
        victory = guaranteed_questions[2]

        lp_indices = [0] + [-1] * (fst_guaranteed-1) +\
                     [(i-fst_guaranteed+1) % 7 for i in range(fst_guaranteed, snd_guaranteed+1)] +\
                     [(i-snd_guaranteed+1) % 7 for i in range(snd_guaranteed+1, victory)]
        q_indices = [0] * (fst_guaranteed) + [
            (i - fst_guaranteed + 1) % 11
            for i in range(fst_guaranteed, victory)
        ]
        fa_indices = [-1] * (fst_guaranteed) + [
            (i - fst_guaranteed) % 5 for i in range(fst_guaranteed, victory)
        ]
        ca_indices = [0] * (fst_guaranteed - 1) + [
            (i - fst_guaranteed + 1) % 12
            for i in range(fst_guaranteed, victory + 1)
        ]
        wa_indices = [0] * (fst_guaranteed) + [(i-fst_guaranteed+1) % 6
                                               for i in range(fst_guaranteed, snd_guaranteed)] +\
                                              [(i-snd_guaranteed+1) % 5
                                               for i in range(snd_guaranteed, victory-1)] + [6]

        self.music_settings = [[
            lets_play_themes[lp_indices[i]] if lp_indices[i] >= 0 else None,
            question_themes[q_indices[i]],
            final_ans_themes[fa_indices[i]] if fa_indices[i] >= 0 else None,
            correct_ans_themes[ca_indices[i]], wrong_ans_themes[wa_indices[i]]
        ] for i in range(victory)]

    def _get_questions_file_content(self) -> str:
        with codecs.open(self.questions_path, "r", "utf-8") as questions_file:
            file_content = questions_file.read()
            try:
                return decryption(file_content.encode())
            except (InvalidToken, Error):
                return file_content

        return None

    def get_questions(self) -> None:
        questions_data = self._get_questions_file_content().splitlines()
        self._questions = [[
            int(questions_data[i]), questions_data[i + 1],
            questions_data[i + 2], questions_data[i + 3],
            questions_data[i + 4], questions_data[i + 5]
        ] for i in range(0, int(len(questions_data)), 6)]
        self._questions = sorted(self._questions, key=lambda x: x[0])

    def choose_random_question(self) -> list:
        q_split = int(len(self._questions) / self.guaranteed_questions[-1])
        minimum = (self.question_number - 1) * q_split
        maximum = self.question_number * q_split
        if self.question_number == self.guaranteed_questions[-1]:
            maximum = len(self._questions) - 1
        rand_index = self.rng.randrange(minimum, maximum)
        question = self._questions[rand_index]
        self._questions.remove(question)
        self.current_question = question
        return question

    def answer_correct(self, answer: str, question: list) -> bool:
        return answer == question[2]

    def lifeline_fifty_fifty(self, question: list) -> list:
        self.fifty_fifty = self.question_number
        fst_wrong_answer = question[self.rng.randrange(3, 5)]
        question.remove(fst_wrong_answer)
        snd_wrong_answer = question[self.rng.randrange(3, 4)]
        question.remove(snd_wrong_answer)
        return [fst_wrong_answer, snd_wrong_answer]

    def lifeline_switch(self):
        self.switch = self.question_number
        return self.choose_random_question()

    def get_music_for_question(self):
        if self.question_number != self.guaranteed_questions[-1] + 1:
            return self.music_settings[self.question_number - 1]
        return None

    def reset_lifelines(self):
        self.fifty_fifty = 0
        self.switch = 0
        self.double_dip = 0
예제 #3
0
from algorithms import sqm

#  USED FOR SECURE NUMBER GENERATION
crypto_gen = SystemRandom()

#  PUBLIC PARAMETERS
p = crypto_gen.getrandbits(128)
alpha = crypto_gen.getrandbits(128)

#  MAKE SURE ALPHA IS A GENERATOR AND SMALLER THAN p
while alpha > p and sqm(alpha, int((p - 1) / 2), p) != 1:
    if not sqm(alpha, p - 1, p) == 1:
        alpha = crypto_gen.getrandbits(128)

#  PRIVATE KEY GENERATING
a = crypto_gen.randrange(2, p - 2)  # KEY a
b = crypto_gen.randrange(2, p - 2)  # KEY b

#  PUBLIC KEYS
K_pub_A = sqm(alpha, a, p)  # KEY A
K_pub_B = sqm(alpha, b, p)  # KEY B

#  SHARED KEY (SECRET)
K_ab = sqm(K_pub_B, a, p)

#  CHECK SHARED KEY
if not K_ab == sqm(K_pub_A, b, p):
    print("[FATAL ERROR] Shared key's are not matching")
else:
    print(f"[PUBLIC] p = ({hex(p)}), alpha = ({hex(alpha)})")
    print(f"[PRIVATE EXCHANGED] {hex(K_ab)}")
예제 #4
0

def save_ans(ans):
    with open('/userans/' + sha256(ans.encode('ascii')).hexdigest() + '.cs',
              'w') as f:
        f.write(ans)


if __name__ == '__main__':
    template_txt = ""
    user_input = ""
    password = ""
    session = ""

    for i in range(60):
        password += chr(randgen.randrange(ord('a'), ord('z') + 1))

    for i in range(60):
        session += chr(randgen.randrange(ord('a'), ord('z') + 1))

    template_path = "./template.cs"
    with open(template_path, 'r') as f:
        template_txt = f.read()
    print(hello_output)
    tmp = ""
    while tmp != "END":
        user_input += tmp + '\n'
        tmp = input()
        if len(user_input) > PROGRAM_MAX_LEN:
            print("too long!!")
            sys.exit()
예제 #5
0
item = input("What are you giving away? ")
n = int(input("How many {} are you giving away? ".format(item)))
participants = int(input("How many people are participating? "))

print("To start, participants 0 through {} get one of the {} (for now...)".format(n - 1, item))
bus = list(range(n))
print()
print("List anyone who was gone, end with a blank line...")
s = n
while True:
    line = input()
    if line == '':
        break
    print("Participant {} gets one of the {} (for now) then.".format(s, item))
    bus[bus.index(int(line))] = s
    s += 1

j = n
for e in range(s, participants):
    here = input("Is participant {} here (y/n)? ".format(e)) == 'y'
    if not here:
        continue
    j = j + 1
    if rng.random() < n / j:
        i = rng.randrange(0, n)
        print("Participant {} steals one of the {} from participant {}!".format(e, item, bus[i]))
        bus[i] = e
    else:
        print("Nothing happened.")

예제 #6
0
class RPSAgent(object):
    def __init__(self, configuration):
        self.obs = None
        self.config = configuration
        self.history = pd.DataFrame(
            columns=["step", "action", "opponent_action"])
        self.history.set_index("step", inplace=True)
        self.history = self.history.astype({
            "action": np.int,
            "opponent_action": np.int
        })
        # How the game would have happened if we always chose the actions selected by our agent
        self.alternate_history = pd.DataFrame(
            columns=["step", "action", "opponent_action"])
        self.alternate_history.set_index("step", inplace=True)
        self.history = self.history.astype({
            "action": np.int,
            "opponent_action": np.int
        })

        self.step = 0
        self.score = 0
        self.random = SystemRandom()

    def agent(self,
              observation,
              configuration=None,
              history=None) -> Tuple[int, pd.DataFrame]:
        if self.random.randint(0, 10) == 7:
            # Change the random seed
            self.random = SystemRandom()
        if configuration is not None:
            self.config = configuration
        if history is not None:
            self.history = history
        self.obs = observation

        self.step = self.obs.step

        # Append the last action of the opponent to the history
        if self.step > 0:
            self.history.loc[self.step - 1,
                             "opponent_action"] = self.obs.lastOpponentAction
            self.alternate_history.loc[
                self.step - 1, "opponent_action"] = self.obs.lastOpponentAction
            self.score = get_score(self.history)

        if self.score - 20 > (1000 - self.step):
            # Don't waste computation time
            action = self.random.randint(0, 2)
            if self.random.randint(0, 10) <= 3:
                action = (action + 1) % SIGNS
            return action, history

        # Choose an action and append it to the history
        action = self.act()
        self.alternate_history.loc[self.step] = {
            "action": action,
            "opponent_action": None,
        }
        # Calculate the probability of a win for random play
        # Taken from https://www.kaggle.com/c/rock-paper-scissors/discussion/197402
        win_prob = 0.5 + 0.5 * math.erf(
            ((observation.reward - 20) + 1) / math.sqrt(
                (2 / 3) * (1000 - observation.step)))
        if (win_prob >= 0.92 and get_score(self.history, 10) < 5
                and self.random.randrange(0, 100) <= win_prob * 100):
            # Try to secure the win with random play
            action = self.random.randint(0, 2)
            if self.random.randint(0, 10) <= 3:
                action = (action + 2) % SIGNS
        elif get_score(self.alternate_history, 15) < -4:
            # If we got outplayed in the last 15 steps, play the counter of the chosen action´s counter with a
            # certain probability
            if self.random.randint(0, 100) <= 20:
                action = (action + 2) % SIGNS
            else:
                # Play randomly
                action = self.random.randint(0, 2)
                if self.random.randint(0, 10) <= 3:
                    action = (action + 1) % SIGNS

        self.history.loc[self.step] = {
            "action": action,
            "opponent_action": None
        }
        return action, self.history

    def act(self) -> int:
        pass