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

    Security and Cryptography in Python - Block Cipher(2)

    Double DES
    from pyDes import *
    import random
    
    message = "01234567"
    key_11 = random.randrange(0, 256)
    key_1 = bytes([key_11, 0, 0, 0, 0, 0, 0, 0])
    key_21 = random.randrange(0, 256)
    key_2 = bytes([key_21, 0, 0, 0, 0, 0, 0, 0])
    iv = bytes([0]*8)
    
    k1 = des(key_1, ECB, iv, pad=None, padmode=PAD_PKCS5)
    k2 = des(key_2, ECB, iv, pad=None, padmode=PAD_PKCS5)
    
    # Alice sending the encrypted message
    cipher = k1.encrypt(k2.encrypt(message))
    print("Key 11:", key_11)
    print("Key 21:", key_21)
    print("Encrypted:", cipher)
    
    # This is Bob
    message = k2.decrypt(k1.decrypt(cipher))
    print("Decrypted:", message)
    
    # Eve's attack on Double DES
    lookup = {}
    for i in range(256):
        key = bytes([i, 0, 0, 0, 0, 0, 0, 0])
        k = des(key, ECB, iv, pad=None, padmode=PAD_PKCS5)
        lookup[k.encrypt(message)] = i
    
    for i in range(256):
        key = bytes([i, 0, 0, 0, 0, 0, 0, 0])
        k = des(key, ECB, iv, pad=None, padmode=PAD_PKCS5)
        if k.decrypt(cipher) in lookup:
            print("Key 11:", i)
            print("Key 21:", lookup[k.decrypt(cipher)])
            key_1 = bytes([i, 0, 0, 0, 0, 0, 0, 0])
            key_2 = bytes([lookup[k.decrypt(cipher)], 0, 0, 0, 0, 0, 0, 0])
            k1 = des(key_1, ECB, iv, pad=None, padmode=PAD_PKCS5)
            k2 = des(key_2, ECB, iv, pad=None, padmode=PAD_PKCS5)
            print("Eve break double DES", k2.decrypt(k1.decrypt(cipher)))
            break
    

    Running result:

    image-20210210101022590

    相信未来 - 该面对的绝不逃避,该执著的永不怨悔,该舍弃的不再留念,该珍惜的好好把握。
  • 相关阅读:
    Cocos2d-js官方完整项目教程翻译:六、添加Chipmunk物理引擎在我们的游戏世界里
    linux coreseek-4.1安装
    8个必备的PHP功能开发
    LINUX 下mysql导出数据、表结构
    PHP缩略图类
    PHP文件上传类
    PHP抓取页面的几种方式
    MySQL性能优化的最佳20+条经验
    zend studio9.0.3破解及汉化 windons版
    【转载】【面试经验】PHP中级面试题
  • 原文地址:https://www.cnblogs.com/keepmoving1113/p/14395078.html
Copyright © 2011-2022 走看看