pwdRules.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * @Author: Badguy
  3. * @Date: 2022-02-15 17:16:32
  4. * @LastEditTime: 2022-02-18 17:57:54
  5. * @LastEditors: your name
  6. * @Description: 账号管理方法
  7. * have a nice day!
  8. */
  9. export function generatePassword(rules, minNum, maxNum) {
  10. var rulesArr = rules.split('')
  11. var rulesArrLnArr = []
  12. var pwd = ''
  13. var numbers = '0123456789'
  14. var lower = 'abcdefghijklmnopqrstuvwxyz'
  15. var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  16. var others = '~!@#$%^&*()_'
  17. function rand(min, max) {
  18. return Math.random() * (max - min) + min
  19. }
  20. var pwdLen = parseInt(rand(minNum, maxNum)) // 随机生成密码长度10-12位。
  21. // alert("密码长度:" + pwdLen);
  22. var item = new Array(pwdLen) // 存放密码的类型 数字(1),小写(2),大写(3),特殊字符(4)
  23. for (let i = 0; i < rulesArr.length; i++) {
  24. if (rulesArr[i] === '1') {
  25. rulesArrLnArr.push(i + 1 + '')
  26. }
  27. }
  28. for (let i = 0; i < rulesArrLnArr.length; i++) {
  29. item[rulesArrLnArr[i]] = rulesArrLnArr[i] + ''
  30. // console.log(`rulesArrLnArr[i]`, rulesArrLnArr[i])
  31. }
  32. for (let i = 0; i < pwdLen; i++) {
  33. if (rulesArrLnArr.indexOf(i + '') === -1) {
  34. item[i] = ''
  35. item[i] += rulesArrLnArr[parseInt(Math.random() * (rulesArrLnArr.length - 0) + 0)] // 其余部分随机生成1-4的数字。
  36. }
  37. }
  38. // 打乱次序,重新排序,否则密码第四位永远是特殊符号。
  39. item.sort(function () {
  40. return 0.5 - Math.random()
  41. }) // 返回0 两个数位置不变;小于0 就交换位置;大于0就不交换位置
  42. for (let j = 0; j < pwdLen; j++) {
  43. if (item[j] === '4') {
  44. pwd += numbers.charAt(Math.random() * (numbers.length - 1) + 1)
  45. } else if (item[j] === '1') {
  46. pwd += lower.charAt(Math.random() * (lower.length - 1) + 1)
  47. } else if (item[j] === '2') {
  48. pwd += upper.charAt(Math.random() * (upper.length - 1) + 1)
  49. } else if (item[j] === '3') {
  50. pwd += others.charAt(Math.random() * (others.length - 1) + 1)
  51. }
  52. }
  53. return pwd
  54. }