10

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

generate.password (length, capitals, numbers)
  • length:密码的长度
  • capitals:定义大写在哪里出现的向量,vector反映了密码字符串对应的位置,默认不应该是大写
  • numbers:定义大写字母出现位置的向量,vector 反映了对应的密码字符串位置,默认不应该是数字

例子:

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"
4

3 回答 3

13

stringi(版本> = 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"
于 2014-04-18T12:31:39.610 回答
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函数。

于 2013-09-14T09:35:52.603 回答
5

我喜欢@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)
}

generate.password(8)

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

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

"+J5Gi3"           # 6 alpha-numeric-specialchar

"77{h6RsGQJ66if5"  # 15 alpha-numeric-specialchar
于 2016-04-07T21:49:30.283 回答