zoukankan      html  css  js  c++  java
  • Security and Cryptography in Python

    Security and Cryptography in Python - Substitution Cipher

    A Substitution Cipher has

    [26! = 403291461126605635584000000 ]

    possible permutations / possible keys.

    [26! = 403291461126605635584000000 ]

    [2^88 = 309485009821345068724781056 ]

    Hence a 88 bit security.

    Encryption

    import random
    
    def generate_key():
        letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        cletters = list(letters)
        key = {}
        for c in letters:
            key[c] = cletters.pop(random.randint(0,len(cletters) - 1))
        return key
    
    key = generate_key()
    print(key)
    

    First Running Result:

    image-20210203200048320

    Second Running Result:

    image-20210203200117372

    import random
    
    def generate_key():
        letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        cletters = list(letters)
        key = {}
        for c in letters:
            key[c] = cletters.pop(random.randint(0,len(cletters) - 1))
        return key
    
    def encrypt(key, message):
        cipher = ""
        for c in message:
            if c in key:
                cipher += key[c]
            else:
                cipher += c
        return cipher
    
    key = generate_key()
    print(key)
    message = "YOU ARE AWESOME"
    cipher = encrypt(key, message)
    print(cipher)
    

    First Running Result:

    image-20210203200823746

    Second Running Result:

    image-20210203201000900

    Decryption

    import random
    
    def generate_key():
        letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        cletters = list(letters)
        key = {}
        for c in letters:
            key[c] = cletters.pop(random.randint(0,len(cletters) - 1))
        return key
    
    def encrypt(key, message):
        cipher = ""
        for c in message:
            if c in key:
                cipher += key[c]
            else:
                cipher += c
        return cipher
    
    def get_decrypt_key(key):
        dkey = {}
        for k in key:
            dkey[key[k]] = k
        return dkey
    
    key = generate_key()
    print(key)
    message = "YOU ARE AWESOME"
    cipher = encrypt(key, message)
    print(cipher)
    dkey = get_decrypt_key(key)
    message = encrypt(dkey, cipher)
    print(message)
    

    First Running Result:

    image-20210203201743085

    Second Running Result:

    image-20210203201850066

    相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。
  • 相关阅读:
    HDU 2852 KiKi's K-Number (主席树)
    HDU 2089 不要62
    Light oj 1140 How Many Zeroes?
    Bless You Autocorrect!
    HDU 6201 transaction transaction transaction
    HDU1561 The more ,The better (树形背包Dp)
    CodeForces 607B zuma
    POJ 1651 Mulitiplication Puzzle
    CSUOJ 1952 合并石子
    Uva 1599 Ideal path
  • 原文地址:https://www.cnblogs.com/keepmoving1113/p/14369539.html
Copyright © 2011-2022 走看看