我正在尝试在 R 中进行 AES-256 位加密。这是对数据帧的一列进行的。例如。,
df:-
**fname lname city country**
aas das Mum IN
asdw gup del IN
erf fre Sfo US ...
在这个数据帧中,我需要加密前 2 个字段并将加密的值存储在数据帧中。
目前我正在使用代码:
for(i in 1:nrow(df))
{
ip <- charToRaw(df$name[i])
enc <- PKI.encrypt(ip, key)
enc ->df$ip[i]
}
在这里,我本质上是尝试在循环中加密“名称”字段的所有条目,并尝试将其存储回 df。
但是,这样做时,我担心以下几点:
1. 加密值示例如下:
14 5e 9d 27 e8 6d cd d0 f3 1a 8d 50 6c 8c be a9 12 f4 43 92 0a 44 8a 50 cb be 15 44 23 2a 37 8b fa 8c 8e 5c c5 67 61 81 d5 22 dc fa c3 47 4a 22 76 34 dd 4c
aa e9 ae a0 d0 48 bf 28 f6 fc f4 94 0f 0b 10 d6 e7 84 94 6a a6 60 da 4e f6 56 9a b2 6a 54 11 0e f4 bf f1 2b c1 5a 18 14 e4 d1 58 a9 22 6f 08 c2 fe c8 13 0d
4c 58 a7 bd 96 e8 9e e3 76 80 95 c4 3f e1 16 48 aa aa ef 57 2a 69 4f 45 a0 0a 80 3c 95 f8 06 1b 46 ee f5 ed 8a 29 7d aa f7 73 90 f7 2c 93 4e c9 34 f5 20 6b
38 45 87 49 37 f0 29 9e 4e 53 a6 52 af 51 56 07 13 3c 68 bc cf de bc 88 ac 5e 36 4a 01 d0 19 50 53 49 c0 78 b2 c8 b3 df b8 fa 2b a1 8d 3c 25 a8 fa 9f fd ee
ab c6 ff ff 36 6c 65 db bd 0d 40 2d 96 c1 da 85 f2 07 4f 2a 4b 2d c6 a8 ad 29 e7 28 8b ac 56 91 a5 73 ec 24 da 56 ba 13 95 09 54 77 a0 6e 74 90
这是 AES 256 中预期的那种输出吗??
谢谢!!
最佳答案
您可以使用 map
代替 for 循环来自 purrr
包裹。 map
可以将结果作为列表存储在您的数据框中。
library(PKI)
library(purrr)
key <- PKI.genRSAkey(2048)
# create some helper functions
encrypt <- function(x){
# function assumes you already created a RSA key called key
x <- charToRaw(x)
e <- PKI.encrypt(x, key)
return(e)
}
decrypt <- function(x) {
# function assumes you already have a key called key
e <- PKI.decrypt(x, key)
x <- rawToChar(e)
return(x)
}
# encrypt the first name
df$ip <- map(df$fname, encrypt)
str(df)
'data.frame': 3 obs. of 5 variables:
$ fname : chr "aas" "asdw" "erf"
$ lname : chr "das" "gup" "fre"
$ city : chr "Mum" "del" "Sfo"
$ country: chr "IN" "IN" "US"
$ ip :List of 3
..$ : raw 10 06 f5 2d ...
..$ : raw 42 e5 d7 6f ...
..$ : raw 7d 48 66 be ...
检查一切是否正常
identical(df$fname, unlist(map(df$ip, decrypt)))
[1] TRUE
数据:
df <- structure(list(fname = c("aas", "asdw", "erf"),
lname = c("das","gup", "fre"),
city = c("Mum", "del", "Sfo"),
country = c("IN", "IN", "US")),
.Names = c("fname", "lname", "city", "country"),
class = "data.frame",
row.names = c(NA, -3L))
关于r - 数据帧中列的 AES 256 加密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49857426/