generate a secure password in javascript

后端 未结 6 2113
暗喜
暗喜 2021-02-02 02:25

What\'s the quickest way to generate a secure password in javascript?

I want it to contain at least 1 special character, and 2 mixed case. Must be at least 6 characters

6条回答
  •  猫巷女王i
    2021-02-02 03:02

    use this code for strong password :D

    const generatePassword = (
      passwordLength = 8,
    ) => {
      const lowerCase = 'abcdefghijklmnopqrstuvwxyz'
      const upperCase = lowerCase.toUpperCase()
      const numberChars = '0123456789'
      const specialChars = '!"@$%+-_?^&*()'
    
      let generatedPassword = ''
      let restPassword = ''
    
      const restLength = passwordLength % 4 
      const usableLength = passwordLength - restLength
      const generateLength = usableLength / 4
    
      const randomString = (char) => {
        return char[Math.floor(Math.random() * (char.length))]
      }
      for (let i = 0; i <= generateLength - 1; i++) {
        generatedPassword += `${randomString(lowerCase)}${randomString(upperCase)}${randomString(numberChars)}${randomString(specialChars)}`
      }
    
      for (let i = 0; i <= restLength - 1; i++) {
        restPassword += randomString([...lowerCase, ...upperCase, ...numberChars, ...specialChars])
      }
    
      return generatedPassword + restPassword
    }
    

提交回复
热议问题