R中的替代加密/解密 [英] Substitution Encryption/Decryption in R

查看:59
本文介绍了R中的替代加密/解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用变量alpha和密钥,将ptext加密为名为ctext的变量.使用替代密码

Using the variables alpha and key, encrypt ptext into a variable named ctext. Using substitution cipher

所以我有一个用矢量分隔的文本文件

So I have a text file separated in a vector

ptext <- strsplit(ptext,split = "", fixed = TRUE)
ptext <- unlist(ptext)

我还为此密码创建了一个密钥

I also created a key for this cipher

key <- "ZGYHXIWJVKULTMSARBQCPDOENF"
key <- unlist(strsplit(key,""))
and an Alphabet vector for the key

alpha <- "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
alpha <= toupper(alpha)
alpha <- unlist(strsplit(alpha,""))

现在,我的目标是尝试替换与p中的字母相对应的ptext向量中的所有字符(例如:相对于key中的Z相对于alpha中的A.因此,文本中的所有A都将被Z代替)

Now my goal is to try to replace all the character in the ptext vector corresponding to the letters in the key in relation to alpha (Example: A in alpha in relation to Z in the key. So all A's in the text would be replaced by a Z)

我知道我应该匹配键中的字母

I know I am supposed to match the alpha in key

cipher <- match(key,alpha)

现在我的问题是,ptext文件中的字符超过1000个.我将如何替换该向量中的所有字母?

Now my issue is, the ptext file is over 1000 characters in it. How would I be able to replace all the letters in that vector?

推荐答案

您可以使用 chartr 来避免拆分字符串和粘贴回去.

You could use chartr which will avoid splitting the string and pasting back.

ptext <- 'REQWDSFFFSLK'
alpha <- 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
key   <- 'ZGYHXIWJVKULTMSARBQCPDOENF'

chartr(alpha, key, ptext)
#[1] "BXROHQIIIQLU"

在这里,所有 R 都替换为 B E 替换为 X ,依此类推,每个字符值.

Here, all R is replaced with B, E with X and so on for every character value.

这篇关于R中的替代加密/解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆