# 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

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

  1. http://highscalability.com/blog/2015/5/18/how-mysql-is-able-to-scale-to-200-million-qps-mysql-cluster.html

    http://highscalability.com/blog/2015/5/18/how-mysql-is-able-to-scale-to-200-million-qps-mysql-cluste ...

  2. Storm(2015.08.12笔记)

    2015.08.12Storm   一.Storm简介 Storm是Twitter开源的一个类似于Hadoop的实时数据处理框架.   Storm能实现高频数据和大规模数据的实时处理. 官网资料显示s ...

  3. Zookepper(2015.08.16笔记)

    2015.08.16zookepper   Zookeeper 是 Google 的 Chubby一个开源的实现,是 Hadoop 的分布式协调服务(如同小区里面的供水.电的系统) 它包含一个简单的原 ...

  4. http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/

    http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/

  5. 2015.12.21~2015.12.24真题回顾!-- HTML5学堂

    2015.12.21~2015.12.24真题回顾!-- HTML5学堂 山不在高,有仙则名!水不在深,有龙则灵!千里冰封,非一日之寒!IT之路,须厚积薄发!一日一小练,功成不是梦!小小技巧,尽在HT ...

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

    写在前面 感谢全部点进来看的朋友.没错.我眼下打算写一本关于Unity Shader的书. 出书的目的有以下几个: 总结我接触Unity Shader以来的历程,给其它人一个借鉴.我非常明确学Shad ...

  7. Murano Weekly Meeting 2015.07.21

    会议时间: 2015.07.21 主持人: Kirill Zaitsev, core from Mirantis 会议摘要:  1.murano client和murano dashboard升级到y ...

  8. Clover KextsToPatch 使用方法 2015.10.21

    Clover KextsToPatch 使用方法 2015.10.21   前些天,因为 Thinkpad X230 BIOS 白名单限制,给她换了一块 ar9285 无线网卡,只是因为这块网卡正好可 ...

  9. Murano Weekly Meeting 2015.08.25

    Meeting time: 2015.August.25th 1:00~2:00 Chairperson:  Serg Melikyan, PTL from Mirantis Meeting summ ...

随机推荐

  1. CSS书写格式

    转自: https://segmentfault.com/a/1190000005046830 CSS书写格式 1.格式化代码 1.1文件 [建议]:CSS文件使用无BOM的UTF-8编码 1.2缩进 ...

  2. 在Git远程管理项目

    新建repository 本地目录下,在命令行里新建一个代码仓库(repository) 里面只有一个README.md 命令如下: touch README.md        git init 初 ...

  3. 【spring源码学习】spring的事件发布监听机制源码解析

    [一]相关源代码类 (1)spring的事件发布监听机制的核心管理类:org.springframework.context.event.SimpleApplicationEventMulticast ...

  4. jslinq 使用总结

    最近一直在用 jslinq 感觉还是不错的.用于增强 Array.find() 上重点: 1: 引用 cnpm install jslinq --save (本人用淘宝镜像--npmFQ感觉也不快-- ...

  5. IDEA生成serialVersionUID的警告

    默认情况下Intellij IDEA是关闭了继承了java.io.Serializable的类生成serialVersionUID的警告.如果需要ide提示生成serialVersionUID,那么需 ...

  6. CENTOS7配置静态IP后无法ping通外部网络的问题

    我今天想谈论的并不是如何配置静态IP,这样的话题已经有好多高手再谈. 我想谈的是为什么,我按照他们的教程无论如何也要发生各种问题,没办法连接外网的问题. 先给大家看我的最终版配置方案:我只修改了一个文 ...

  7. Ambari-HDP

    文档说明以及下载路径 https://docs.hortonworks.com/index.html Ambari的安装路径 https://docs.hortonworks.com/HDPDocum ...

  8. INSTALL_FAILED_SHARED_USER_INCOMPATIBLE的问题

    eclipse编译出来的apk,安装时报出INSTALL_FAILED_SHARED_USER_INCOMPATIBLE的错误. 原因:apk的AndroidManifest.xml中声明了andro ...

  9. 整数a整数b

    namespace ConsoleApplication6{ class Program { static void Main(string[] args) { while (true) { Cons ...

  10. zabbix增加手机短信、邮件监控的注意要点,SSL邮件发送python脚本

    1.短信接口文档: URL http://xxx.com/interfaces/sendMsg.htm Method POST Description 文字短信调用接口 Request Param L ...