#凯撒密码:将每一个字母替换为字母表中下一位字母,比如a变成b。

english.letters <- c('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',

'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',

'w', 'x', 'y', 'z')

caesar.cipher <- list()

inverse.caesar.cipher <- list()

#加密LIST和解密LIST

for (index in 1:length(english.letters))

{

caesar.cipher[[english.letters[index]]] <- english.letters[index %% 26 + 1]

inverse.caesar.cipher[[english.letters[index %% 26 + 1]]] <- english.letters[index]

}

print(caesar.cipher)

# 单字符串加密

apply.cipher.to.string <- function(string, cipher)

{

output <- ''

for (i in 1:nchar(string))

{

output <- paste(output, cipher[[substr(string, i, i)]], sep = '')

}

return(output)

}

#向量字符串加密

apply.cipher.to.text <- function(text, cipher)

{

output <- c()

for (string in text)

{

output <- c(output, apply.cipher.to.string(string, cipher))

}

return(output)

}

apply.cipher.to.text(c('sample', 'text'), caesar.cipher)

#贪心优化:只有当新解密规则得到的解密串的概率变高时,才接受新的解密规则

#思路:

#1.如果解密规则B解密出的解密串的概率大于解密规则A对应的解密串,那么我们用B代替A

#2.如果解密规则B解密出的解密串的概率小于解密规则A对应的解密串,我们仍然有可能用B代替A,不过并不是每次都替换。

#如果解密规则B对应的解密串的概率是p1,解密规则A对应的解密串的概率是p2,以p1/p2的概率从解密规则A替换到解密规则B(表示有一定的概率接受B,这使得不会陷入贪心优化陷阱中)

#随便产生一个加密规则

generate.random.cipher <- function()

{

cipher <- list()

inputs <- english.letters

outputs <- english.letters[sample(1:length(english.letters), length(english.letters))]

for (index in 1:length(english.letters))

{

cipher[[inputs[index]]] <- outputs[index]  }

return(cipher)

}

modify.cipher <- function(cipher, input, output)

{

new.cipher <- cipher

new.cipher[[input]] <- output

old.output <- cipher[[input]]

collateral.input <- names(which(sapply(names(cipher), function (key) {cipher[[key]]}) == output))

new.cipher[[collateral.input]] <- old.output

return(new.cipher)

}

#对加密算法作一些修改

propose.modified.cipher <- function(cipher)

{

input <- sample(names(cipher), 1)

output <- sample(english.letters, 1)

return(modify.cipher(cipher, input, output))

}

#加载词典

load(file.path('G:\\dataguru\\ML_for_Hackers\\ML_for_Hackers-master\\07-Optimization\\data\\lexical_database.Rdata'))

#看一下里面的数据

lexical.database[['a']]

lexical.database[['the']]

lexical.database[['he']]

lexical.database[['she']]

lexical.database[['data']]

#取概率的,词典里有就返回,词典里没有返回一个最小的浮点数

one.gram.probability <- function(one.gram, lexical.database = list())

{

lexical.probability <- lexical.database[[one.gram]]

if (is.null(lexical.probability) || is.na(lexical.probability))

{

return(.Machine$double.eps)

}

else

{

return(lexical.probability)

}

}

#给定一个字符串向量,计算概率,概率不用连乘,用求和

log.probability.of.text <- function(text, cipher, lexical.database = list())

{

log.probability <- 0.0

for (string in text)

{

decrypted.string <- apply.cipher.to.string(string, cipher)

log.probability <- log.probability +

log(one.gram.probability(decrypted.string, lexical.database))

}

return(log.probability)

}

#

metropolis.step <- function(text, cipher, lexical.database = list())

{

#对加密规则作一下修改

proposed.cipher <- propose.modified.cipher(cipher)

#计算原加密规则及修改过的加密规则的概率

lp1 <- log.probability.of.text(text, cipher, lexical.database)

lp2 <- log.probability.of.text(text, proposed.cipher, lexical.database)

#如果新的比较好,直接换掉

if (lp2 > lp1)

{

return(proposed.cipher)

}

else

{

#如果旧的比较好,

a <- exp(lp2 - lp1)

#x是均匀分布的0~1间随机数

x <- runif(1)

if (x < a)

{

return(proposed.cipher)

}

else

{

return(cipher)

}

}

}

# 5个字符串的向量

decrypted.text <- c('here', 'is', 'some', 'sample', 'text')

#用凯撒加密规则加一下密

encrypted.text <- apply.cipher.to.text(decrypted.text, caesar.cipher)

set.seed(1)

#生成随机加密规则

cipher <- generate.random.cipher()

results <- data.frame()

#50000次迭代

number.of.iterations <- 50000

for (iteration in 1:number.of.iterations)

{

#算一下加密结果的概率

log.probability <- log.probability.of.text(encrypted.text,cipher,lexical.database)

#得出解密结果

current.decrypted.text <- paste(apply.cipher.to.text(encrypted.text, cipher),collapse = ' ')

#得出判断结果,1为正确,0为不正确

correct.text <- as.numeric(current.decrypted.text == paste(decrypted.text,

collapse = ' '))

#形成数据框,包括迭代次数,概率及解密后的结果,以及正确率

results <- rbind(results,data.frame(Iteration = iteration, LogProbability = log.probability,CurrentDecryptedText = current.decrypted.text,CorrectText = correct.text))

cipher <- metropolis.step(encrypted.text, cipher, lexical.database)

}

Machine Learning for hackers读书笔记(七)优化:密码破译的更多相关文章

  1. Machine Learning for hackers读书笔记(六)正则化:文本回归

    data<-'F:\\learning\\ML_for_Hackers\\ML_for_Hackers-master\\06-Regularization\\data\\' ranks < ...

  2. Machine Learning for hackers读书笔记(三)分类:垃圾邮件过滤

    #定义函数,打开每一个文件,找到空行,将空行后的文本返回为一个字符串向量,该向量只有一个元素,就是空行之后的所有文本拼接之后的字符串 #很多邮件都包含了非ASCII字符,因此设为latin1就可以读取 ...

  3. Machine Learning for hackers读书笔记_一句很重要的话

    为了培养一个机器学习领域专家那样的直觉,最好的办法就是,对你遇到的每一个机器学习问题,把所有的算法试个遍,直到有一天,你凭直觉就知道某些算法行不通.

  4. Machine Learning for hackers读书笔记(十二)模型比较

    library('ggplot2')df <- read.csv('G:\\dataguru\\ML_for_Hackers\\ML_for_Hackers-master\\12-Model_C ...

  5. Machine Learning for hackers读书笔记(十)KNN:推荐系统

    #一,自己写KNN df<-read.csv('G:\\dataguru\\ML_for_Hackers\\ML_for_Hackers-master\\10-Recommendations\\ ...

  6. Machine Learning for hackers读书笔记(九)MDS:可视化地研究参议员相似性

    library('foreign') library('ggplot2') data.dir <- file.path('G:\\dataguru\\ML_for_Hackers\\ML_for ...

  7. Machine Learning for hackers读书笔记(八)PCA:构建股票市场指数

    library('ggplot2') prices <- read.csv('G:\\dataguru\\ML_for_Hackers\\ML_for_Hackers-master\\08-PC ...

  8. Machine Learning for hackers读书笔记(五)回归模型:预测网页访问量

    线性回归函数 model<-lm(Weight~Height,data=?) coef(model):得到回归直线的截距 predict(model):预测 residuals(model):残 ...

  9. Machine Learning for hackers读书笔记(四)排序:智能收件箱

    #数据集来源http://spamassassin.apache.org/publiccorpus/ #加载数据 library(tm)library(ggplot2)data.path<-'F ...

随机推荐

  1. CkEditor 插件开发

    CKEditor的插件开发其实很简单只需要两步.1.通过CKEditor.plugins.add()方法编写插件的逻辑主体, 2.告诉CKEditor我们有一个自定义插件需要添加进来. //创建插件逻 ...

  2. jQuery1.9.1--attr,prop与val方法源码分析

    这里只介绍这几个方法的源码,这部分引用了一个技巧,钩子对象,用来做兼容fixed的对象,后面也有一些使用.钩子对象具体的兼容细节这里就不详解了. var nodeHook, boolHook, rcl ...

  3. Unity3D开发Windows Store应用程序 注意事项

    原地址:http://blog.csdn.net/jbjwpzyl3611421/article/details/12704491 针对最近在移植window store项目中遇到的问题,我整理了官方 ...

  4. 使用命令行编译、打包、运行WordCount--不用eclipse

    1)首先创建WordCount1023文件夹,然后在此目录下使用编辑器,例如vim编写WordCount源文件,并保存为WordCount.java文件 /** * Licensed under th ...

  5. POJ 2092

    #include <iostream> #include <algorithm> #define MAXN 10005 using namespace std; int _m[ ...

  6. POJ 1185 炮兵阵地 (状压DP)

    题目链接 题意 : 中文题不详述. 思路 :状压DP,1表示该位置放炮弹,0表示不放.dp[i][j][k],代表第 i 行的状态为k时第i-1行的状态为 j 时放置的最大炮弹数.只是注意判断的时候不 ...

  7. HDFS Protocol修改流程

        相对于1.x版本的Hadoop,2.x版本的Hadoop采用了Protocol Buffer作为序列化反序列化工具,以及RPC通讯工具.这样当我们对Hadoop源码进行修改之前,就需要了解Ha ...

  8. ios开发--集成银联3.3.0

    项目最近需要集成银联,在网上搜了一下发现都并不是最新版的银联集成教程,自己摸索了一下,总结写了下来. 附上3.3.0的下载网址 https://open.unionpay.com/upload/dow ...

  9. iOS开发--UITableView

    -.建立 UITableView  DataTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 420)];  [Data ...

  10. Hadoop完全分布式集群配置

    1.前话 寒假实在太闲了,所以闲着无聊地去了解"大数据"这个新概念,这几年到处都在说什么大数据时代的,不能不让我感到好奇啊. 大数据有啥用?随便谷歌百度一大堆我也不多说了. 我自己 ...