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
MCMC 破译密码 http://mlwhiz.com/blog/2015/08/21/MCMC_Algorithms_Cryptography/的更多相关文章
- 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 ...
- Storm(2015.08.12笔记)
2015.08.12Storm 一.Storm简介 Storm是Twitter开源的一个类似于Hadoop的实时数据处理框架. Storm能实现高频数据和大规模数据的实时处理. 官网资料显示s ...
- Zookepper(2015.08.16笔记)
2015.08.16zookepper Zookeeper 是 Google 的 Chubby一个开源的实现,是 Hadoop 的分布式协调服务(如同小区里面的供水.电的系统) 它包含一个简单的原 ...
- http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/
http://browniefed.com/blog/2015/09/10/the-shapes-of-react-native/
- 2015.12.21~2015.12.24真题回顾!-- HTML5学堂
2015.12.21~2015.12.24真题回顾!-- HTML5学堂 山不在高,有仙则名!水不在深,有龙则灵!千里冰封,非一日之寒!IT之路,须厚积薄发!一日一小练,功成不是梦!小小技巧,尽在HT ...
- 【我的书】Unity Shader的书 — 文件夹(2015.12.21更新)
写在前面 感谢全部点进来看的朋友.没错.我眼下打算写一本关于Unity Shader的书. 出书的目的有以下几个: 总结我接触Unity Shader以来的历程,给其它人一个借鉴.我非常明确学Shad ...
- Murano Weekly Meeting 2015.07.21
会议时间: 2015.07.21 主持人: Kirill Zaitsev, core from Mirantis 会议摘要: 1.murano client和murano dashboard升级到y ...
- Clover KextsToPatch 使用方法 2015.10.21
Clover KextsToPatch 使用方法 2015.10.21 前些天,因为 Thinkpad X230 BIOS 白名单限制,给她换了一块 ar9285 无线网卡,只是因为这块网卡正好可 ...
- Murano Weekly Meeting 2015.08.25
Meeting time: 2015.August.25th 1:00~2:00 Chairperson: Serg Melikyan, PTL from Mirantis Meeting summ ...
随机推荐
- 使用Volley框架中的ImageLoader来异步的加载图片
Volley框架在请求网络图片方面也做了很多工作,提供了好几种方法.本文介绍使用ImageLoader来进行网络图片的加载.ImageLoader的内部使用ImageRequest来实现,它的构造器可 ...
- ASP.NET的几个试题(《C#与.NET程序员面试宝典》)
更多参考:博客园笔记 :ASP.NET是什么 ASP.NET不是一种语言,而是创建动态Web页的一种强大的服务器端技术,它是Microsoft.NET Framework中一套用于生成Web应用程序和 ...
- WCF日志跟踪SvcTraceViewer.exe
参考: https://msdn.microsoft.com/zh-cn/library/ms732023.aspx https://msdn.microsoft.com/zh-cn/library/ ...
- MAC OS X常用命令总结2
1. dir:显示某个目录下的子目录与文件. 格式:dir [x:] [Path] [filename][ parameter] 参数解释: /a 显示所有文件夹与文件. /p 分页 ...
- 一线互联网公司必备——最为详细的Docker入门吐血总结
在计算机技术日新月异的今天, Docker 在国内发展的如火如荼. 特别是在一线互联网公司 Docker 的使用是十分普遍的,甚至成为了一些企业面试的加分项,不信的话看看下面这张图. ...
- .NET程序如何启动?
.net程序如何启动? .NET Framework在Windows平台顶部运行,这意味着.NET Framework必须使用 windows可以理解的技术来构建.首先,所有托管模块和程序集文件都必须 ...
- 微信 unionid 获取 解密数据
1.申请注册微信开放平台 open.weixin.qq.com 2.绑定公众号或者小程序到微信开放平台 3.微信公众号的话,使用微信网页授权获取 unionid https://mp.weixin. ...
- 通过html字符串连接组合并调用javascript函数
----通过字符串连接并调用javascript函数-- var t_html = $("#Photo").html(); var n_html = "<a id= ...
- 蓝桥杯 算法训练 ALGO-93 反置数
算法训练 反置数 时间限制:1.0s 内存限制:512.0MB 问题描述 一个整数的“反置数”指的是把该整数的每一位数字的顺序颠倒过来所得到的另一个整数.如果一个整数的末尾是以0结尾,那么在它 ...
- (转)winform下UPD通信的简单应用
本文转载自:http://blog.csdn.net/wanlong360599336/article/details/7557046 先看效果图: 使用UDP的好处就是不需要三次握手,但是缺点就是存 ...