首页 > 解决方案 > 在 Groovy 中使用特殊字符创建强密码

问题描述

我想用小字母和大写字母以及数字和特殊字符在 groovy 中创建一个强密码。

以下是所需的特殊字符:

~`!@#$%^&*()-_=+[{]}\|;:'",<.>/?

我正在使用下面的代码,但我还想在我的密码中至少包含一个特殊字符。

 def pass_length = 15;

    def pool = ['a'..'z','A'..'Z',0..9,'_'].flatten();
    Random rand = new Random(System.currentTimeMillis());

    def passChars = (0..pass_length - 1).collect { pool[rand.nextInt(pool.size())] };
    def PASSWORD = passChars.join();

目前它只创建一个字母数字密码。我可以对代码进行任何快速更改吗?帮助我,因为我是使用 groovy 的新手。

标签: groovy

解决方案


您可以选择一个随机的特殊字符,并将其放在生成的密码中的随机位置。这将确保密码中至少有一个特殊字符。

另外,为什么不将特殊字符也添加到您的字典中呢?这样,特殊字符更有可能出现在最终字符串中。

def pass_length = 15;

def special = ['~' ,'`', ...] // you get the idea...
def pool = ['a'..'z','A'..'Z',0..9,'_'].flatten().plus(special);
Random rand = new Random(System.currentTimeMillis());

def passChars = (0..pass_length - 1).collect { pool[rand.nextInt(pool.size)] };
def specialChar = special[rand.nextInt(special.size)]
passChars[rand.nextInt(passChars.size)] = specialChar
def PASSWORD = passChars.join();

推荐阅读