R中的密码生成器功能

时间:2013-09-14 09:04:08

标签: string r passwords cryptography

我正在寻找一种在R中编码密码生成器功能的智能方法:

generate.password (length, capitals, numbers)
  • length:密码的长度
  • 大写字母:定义大写字母位置的向量,向量反映相应的密码字符串位置,默认值应为无大写字母
  • 数字:定义大写字母出现位置的向量,向量反映相应的密码字符串位置,默认值应为无数字

示例:

generate.password(8)
[1] "hqbfpozr"


generate.password(length=8, capitals=c(2,4))
[1] "hYbFpozr"


generate.password(length=8, capitals=c(2,4), numbers=c(7:8))
[1] "hYbFpo49"

3 个答案:

答案 0 :(得分:11)

这是一种方法

generate.password <- function(length,
                              capitals = integer(0),
                              numbers  = integer(0)) {

   stopifnot(is.numeric(length),   length   > 0L,
             is.numeric(capitals), capitals > 0L, capitals <= length,
             is.numeric(numbers),  numbers  > 0L, numbers  <= length,
             length(intersect(capitals, numbers)) == 0L)

   lc  <- sample(letters, length,           replace = TRUE)
   uc  <- sample(LETTERS, length(capitals), replace = TRUE)
   num <- sample(0:9,     length(numbers),  replace = TRUE)

   pass <- lc
   pass[capitals] <- uc
   pass[numbers]  <- num

   paste0(pass, collapse = "")
}


## Examples
set.seed(1)
generate.password(8)
# [1] "gjoxfxyr"

set.seed(1)
generate.password(length=8, capitals=c(2,4))
# [1] "gQoBfxyr"

set.seed(1)
generate.password(length=8, capitals=c(2,4), numbers=c(7:8))
# [1] "gQoBfx21"

您还可以以相同的方式添加其他特殊字符。如果您想要重复字母和数字的值,请在replace =TRUE函数中添加sample

答案 1 :(得分:11)

有一个函数可以在stringi(版本&gt; = 0.2-3)包中生成随机字符串:

require(stringi)
stri_rand_strings(n=2, length=8, pattern="[A-Za-z0-9]")
## [1] "90i6RdzU" "UAkSVCEa"

因此,使用不同的模式,您可以为所需的密码生成部分,然后将其粘贴如下:

x <- stri_rand_strings(n=4, length=c(2,1,2,3), pattern=c("[a-z]","[A-Z]","[0-9]","[a-z]"))
x
## [1] "ex"  "N"   "81"  "tsy"
stri_flatten(x)
## [1] "exN81tsy"

答案 2 :(得分:0)

我喜欢@Hadd E. Nuff给出的解决方案......我所做的是包含0到9之间的数字,随机...这里是修改后的解决方案......

generate.password <- function(LENGTH){
punct <- c("!",  "#", "$", "%", "&", "(", ")", "*",  "+", "-", "/", ":", 
         ";", "<", "=", ">", "?", "@", "[", "^", "_", "{", "|", "}", "~")
nums <- c(0:9)
chars <- c(letters, LETTERS, punct, nums)
p <- c(rep(0.0105, 52), rep(0.0102, 25), rep(0.02, 10))
pword <- paste0(sample(chars, LENGTH, TRUE, prob = p), collapse = "")
return(pword)
}

这将生成非常强大的密码,如:

"C2~mD20U"         # 8 alpha-numeric-specialchar

"+J5Gi3"           # 6 alpha-numeric-specialchar

"77{h6RsGQJ66if5"  # 15 alpha-numeric-specialchar