MCMC 破译密码 http://mlwhiz.com/blog/2015/08/21/MCMC_Algorithms_Cryptography/

# AIM: To Decrypt a text using MCMC approach. i.e. find decryption key which we will call cipher from now on.
import string
import math
import random

# This function takes as input a decryption key and creates a dict for key where each letter in the decryption key
# maps to a alphabet For example if the decryption key is "DGHJKL...." this function will create a dict like {D:A,G:B,H:C....}
def create_cipher_dict(cipher):
    cipher_dict = {}
    alphabet_list = list(string.ascii_uppercase)
    for i in range(len(cipher)):
        cipher_dict[alphabet_list[i]] = cipher[i]
    return cipher_dict

# This function takes a text and applies the cipher/key on the text and returns text.
def apply_cipher_on_text(text,cipher):
    cipher_dict = create_cipher_dict(cipher)
    text = list(text)
    newtext = ""
    for elem in text:
        if elem.upper() in cipher_dict:
            newtext+=cipher_dict[elem.upper()]
        else:
            newtext+=" "
    return newtext

# This function takes as input a path to a long text and creates scoring_params dict which contains the
# number of time each pair of alphabet appears together
# Ex. {‘AB‘:234,‘TH‘:2343,‘CD‘:23 ..}
def create_scoring_params_dict(longtext_path):
    scoring_params = {}
    alphabet_list = list(string.ascii_uppercase)
    with open(longtext_path) as fp:
        for line in fp:
            data = list(line.strip())
            for i in range(len(data)-1):
                alpha_i = data[i].upper()
                alpha_j = data[i+1].upper()
                if alpha_i not in alphabet_list and alpha_i != " ":
                    alpha_i = " "
                if alpha_j not in alphabet_list and alpha_j != " ":
                    alpha_j = " "
                key = alpha_i+alpha_j
                if key in scoring_params:
                    scoring_params[key]+=1
                else:
                    scoring_params[key]=1
    return scoring_params

# This function takes as input a text and creates scoring_params dict which contains the
# number of time each pair of alphabet appears together
# Ex. {‘AB‘:234,‘TH‘:2343,‘CD‘:23 ..}

def score_params_on_cipher(text):
    scoring_params = {}
    alphabet_list = list(string.ascii_uppercase)
    data = list(text.strip())
    for i in range(len(data)-1):
        alpha_i =data[i].upper()
        alpha_j = data[i+1].upper()
        if alpha_i not in alphabet_list and alpha_i != " ":
            alpha_i = " "
        if alpha_j not in alphabet_list and alpha_j != " ":
            alpha_j = " "
        key = alpha_i+alpha_j
        if key in scoring_params:
            scoring_params[key]+=1
        else:
            scoring_params[key]=1
    return scoring_params

# This function takes the text to be decrypted and a cipher to score the cipher.
# This function returns the log(score) metric

def get_cipher_score(text,cipher,scoring_params):
    cipher_dict = create_cipher_dict(cipher)
    decrypted_text = apply_cipher_on_text(text,cipher)
    scored_f = score_params_on_cipher(decrypted_text)
    cipher_score = 0
    for k,v in scored_f.iteritems():
        if k in scoring_params:
            cipher_score += v*math.log(scoring_params[k])
    return cipher_score

# Generate a proposal cipher by swapping letters at two random location
def generate_cipher(cipher):
    pos1 = random.randint(0, len(list(cipher))-1)
    pos2 = random.randint(0, len(list(cipher))-1)
    if pos1 == pos2:
        return generate_cipher(cipher)
    else:
        cipher = list(cipher)
        pos1_alpha = cipher[pos1]
        pos2_alpha = cipher[pos2]
        cipher[pos1] = pos2_alpha
        cipher[pos2] = pos1_alpha
        return "".join(cipher)

# Toss a random coin with robability of head p. If coin comes head return true else false.
def random_coin(p):
    unif = random.uniform(0,1)
    if unif>=p:
        return False
    else:
        return True

# Takes as input a text to decrypt and runs a MCMC algorithm for n_iter. Returns the state having maximum score and also
# the last few states
def MCMC_decrypt(n_iter,cipher_text,scoring_params):
    current_cipher = string.ascii_uppercase # Generate a random cipher to start
    state_keeper = set()
    best_state = ‘‘
    score = 0
    for i in range(n_iter):
        state_keeper.add(current_cipher)
        proposed_cipher = generate_cipher(current_cipher)
        score_current_cipher = get_cipher_score(cipher_text,current_cipher,scoring_params)
        score_proposed_cipher = get_cipher_score(cipher_text,proposed_cipher,scoring_params)
        acceptance_probability = min(1,math.exp(score_proposed_cipher-score_current_cipher))
        if score_current_cipher>score:
            best_state = current_cipher
        if random_coin(acceptance_probability):
            current_cipher = proposed_cipher
        if i%500==0:
            print "iter",i,":",apply_cipher_on_text(cipher_text,current_cipher)[0:99]
    return state_keeper,best_state

## Run the Main Program:

scoring_params = create_scoring_params_dict(‘war_and_peace.txt‘)

plain_text = "As Oliver gave this first proof of the free and proper action of his lungs, the patchwork coverlet which was carelessly flung over the iron bedstead, rustled; the pale face of a young woman was raised feebly from the pillow; and a faint voice imperfectly articulated the words, Let me see the child, and die. The surgeon had been sitting with his face turned towards the fire: giving the palms of his hands a warm and a rub alternately. As the young woman spoke, he rose, and advancing to the bed‘s head, said, with more kindness than might have been expected of him: "

encryption_key = "XEBPROHYAUFTIDSJLKZMWVNGQC"
cipher_text = apply_cipher_on_text(plain_text,encryption_key)
decryption_key = "ICZNBKXGMPRQTWFDYEOLJVUAHS"

print"Text To Decode:", cipher_text
print "\n"
states,best_state = MCMC_decrypt(10000,cipher_text,scoring_params)
print "\n"
print "Decoded Text:",apply_cipher_on_text(cipher_text,best_state)
print "\n"
print "MCMC KEY FOUND:",best_state
print "ACTUAL DECRYPTION KEY:",decryption_key
时间: 2024-10-23 21:01:11

MCMC 破译密码 http://mlwhiz.com/blog/2015/08/21/MCMC_Algorithms_Cryptography/的相关文章

2015.08.21

在学习css过程中,自己总结了一些常识,以及别人在学习过程中遇到的问题. 1.不要使用过小的图片做背景平铺.这就是为何很多人都不用 1px 的原因,这才知晓.宽高 1px 的图片平铺出一个宽高 200px 的区域,需要 200*200=40, 000 次,占用资源.  2.无边框.推荐的写法是 border:none;,哈哈,我一直在用这个. border:0; 只是定义边框宽度为零,但边框样式.颜色还是会被浏览器解析,占用资源.  3.慎用 * 通配符.所谓通配符,就是将 CSS 中的所有标签

我关注的一周技术动态2015.08.17

服务化和资源管理技术 1. Kubernetes技术分析之存储 http://dockone.io/article/556 要点: 众所周知,使用Docker的时候,容器中的数据是临时,即当容器销毁时,其中的数据时丢失.如果需要持久化数据,需要使用Docker Volume挂载宿主机上的文件目录到容器中.本文介绍了 kubernetes 支持的几种存储系统. 2. Docker 1.8:可信镜像.Toolbox.Registry 以及编排工具大更新 http://dockone.io/artic

我关注的一周技术动态 2015.08.30

服务化和资源管理技术 1. Docker基础技术:AUFS http://coolshell.cn/articles/17061.html 要点: 支持层次化镜像是 docker 的一大创新之一, 本文详细介绍了实现层次化镜像的技术手段之一 aufs 的使用方法, 读完之后你就会理解docker层次化镜像的奥秘了. 2. Docker基础技术:DeviceMapper http://coolshell.cn/articles/17200.html 要点: devicemapper 是支持 doc

dockone上2015.08 Docker有价值文章

Docker入门与基础 [1] Docker入门实战, http://yuedu.baidu.com/ebook/d817967416fc700abb68fca1 [2] 什么是Docker?刘梦馨, 28 Jun 2014, http://oilbeater.com/docker/2014/06/28/what-is-docker.html [3] 访谈 | Docker公司首席布道师谈容器和下一代虚拟化, http://dockone.io/article/590 [4] 两年之后,再思考D

Storm(2015.08.12笔记)

2015.08.12Storm ? 一.Storm简介 Storm是Twitter开源的一个类似于Hadoop的实时数据处理框架. ? Storm能实现高频数据和大规模数据的实时处理. 官网资料显示storm的一个节点在1秒钟能够处理100万个100字节的消息([email protected]的CPU,24GB的内存) (storm +kafka+flume) ? ? 二.HADOOP与STORM比较 数据来源:HADOOP处理的是HDFS上TB级别的数据(历史数据),STORM是处理的是实时

【转换博客通知】(本博客2015.08.02停用)

2015.08.02 本博客停用,搬运至 http://tonyfang.is-programmer.com/ 感谢各位对我的支持!

2015.1.21学习笔记和心得!

2015.1.21 随笔: 指令:cp -v 显示复制过程 sort 按次序显示文件 whereis 查找命令 ln -s src dest 连接文件 dest -> src /etc/apt/sources.list //存放镜像的地址 /var/lib/lists/* // 存放索引文件的地址 /var/cache/apt/archives //下载的软件包缓存的地址 编写shell脚本:三步走 1.创建shell脚本,vim shell.sh 2.修改权限,增加执行权限 chmod 777

Clover KextsToPatch 使用方法 2015.10.21

Clover KextsToPatch 使用方法 2015.10.21 前些天,因为 Thinkpad X230 BIOS 白名单限制,给她换了一块 ar9285 无线网卡,只是因为这块网卡正好可以被 Mac OS X 驱动,也正好在 Thinkpad X230 BIOS 白名单之中.给 Clover 配置的时候,为了防止忘记,便记录下来. 因为灵活使用 Clover 成为黑苹果用户的必修课,否则你就只能漫天寻找 kext,寄希望与运气能正确驱动你的硬件了.Clover 中有一个强大的功能 Ke

【我的书】Unity Shader的书 — 文件夹(2015.12.21更新)

写在前面 感谢全部点进来看的朋友.没错.我眼下打算写一本关于Unity Shader的书. 出书的目的有以下几个: 总结我接触Unity Shader以来的历程,给其它人一个借鉴.我非常明确学Shader的艰难,在群里也见了非常多人提出的问题. 我认为学习Shader还是一件有规律可循的事情,但问题是中文资料难觅,而大家又不愿意去看英文...这对我有什么优点呢?强迫我对知识进行梳理,对细节问题把握更清楚. 第二个原因你懂的. 关于本书的定位问题: 面向Unity Shader刚開始学习的人,但要