#凯撒密码:将每一个字母替换为字母表中下一位字母,比如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. Unity3D 将 Unity 嵌入WPF中的一些研究笔记

     一. 在 WPF 中使用 WebBrowser,直接打开 WebPlayer.html 以这种方式有一个问题是. 无法在 WebBrowser 的上面 放置其它的控件, 在运行时,都不会显示 . 以 ...

  2. 将HTMLCollection/NodeList/伪数组转换成数组

    这里把符合以下条件的对象称为伪数组(ArrayLike) 1,具有length属性 2,按索引方式存储数据 3,不具有数组的push,pop等方法 如 1,function内的arguments . ...

  3. LVM quick start

    这里记录一些任务用到的快速命令,详细LVM管理可参考: http://wenku.baidu.com/view/c29b8bc4bb4cf7ec4afed0ad.html 1.把home分区的磁盘空间 ...

  4. POJ 1236

    Network of Schools Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 10500   Accepted: 41 ...

  5. 无法激活服务,因为它不支持 ASP.NET 兼容性

    wcf错误直接上图: 原因: 一般是因为程序添加了启用了AJAX的WCF服务而缺少相关设置出现的错误. 解决方案: 1.webconfig <system.serviceModel> &l ...

  6. linux下文件编码的查看与修改

    在Linux中查看文件编码可以通过vim编辑器来查看,在vim命令模式下输入如下命令即可: :set fileencoding //在vim中查看文件编码 如果你只是想查看其它编码格式的文件或者想解决 ...

  7. div滚动条

    给DIV限定宽度或高度,并指定overflow样式为auto,这样当内空超出后就会自动出现滚动条了.如<div style="width:100px; height:100px; ov ...

  8. CyclicBarrier、CountDownLatch与Semaphore的小记

    CyclicBarrier: 适合的业务场景,比如 1).,现有一大任务,需要得到全年的统计数据的,这个工作量是巨大的,那么可以将其分割为12个月的子任务,各个子任务相互独立,当所有子任务完成了,则就 ...

  9. Spring框架学习之第6节

    bean的生命周期 为什么总是一个生命当做一个重点? Servlet –> servlet生命周期 Java对象生命周期 往往笔试,面试总喜欢问生命周期的问题? ①   实例化(当我们的程序加载 ...

  10. SPRING IN ACTION 第4版笔记-第十一章Persisting data with object-relational mapping-002设置JPA的EntityManagerFactory(<persistence-unit>、<jee:jndi-lookup>)

    一.EntityManagerFactory的种类 1.The JPA specification defines two kinds of entity managers:  Applicatio ...