UnsignedMathGenerator.java 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package com.ruoyi.common.captcha;
  2. import cn.hutool.captcha.generator.CodeGenerator;
  3. import cn.hutool.core.math.Calculator;
  4. import cn.hutool.core.util.CharUtil;
  5. import cn.hutool.core.util.RandomUtil;
  6. import com.ruoyi.common.utils.StringUtils;
  7. /**
  8. * 无符号计算生成器
  9. *
  10. * @author Lion Li
  11. */
  12. public class UnsignedMathGenerator implements CodeGenerator {
  13. private static final long serialVersionUID = -5514819971774091076L;
  14. private static final String OPERATORS = "+-*";
  15. /**
  16. * 参与计算数字最大长度
  17. */
  18. private final int numberLength;
  19. /**
  20. * 构造
  21. */
  22. public UnsignedMathGenerator() {
  23. this(2);
  24. }
  25. /**
  26. * 构造
  27. *
  28. * @param numberLength 参与计算最大数字位数
  29. */
  30. public UnsignedMathGenerator(int numberLength) {
  31. this.numberLength = numberLength;
  32. }
  33. @Override
  34. public String generate() {
  35. final int limit = getLimit();
  36. int a = RandomUtil.randomInt(limit);
  37. int b = RandomUtil.randomInt(limit);
  38. String max = Integer.toString(Math.max(a,b));
  39. String min = Integer.toString(Math.min(a,b));
  40. max = StringUtils.rightPad(max, this.numberLength, CharUtil.SPACE);
  41. min = StringUtils.rightPad(min, this.numberLength, CharUtil.SPACE);
  42. return max + RandomUtil.randomChar(OPERATORS) + min + '=';
  43. }
  44. @Override
  45. public boolean verify(String code, String userInputCode) {
  46. int result;
  47. try {
  48. result = Integer.parseInt(userInputCode);
  49. } catch (NumberFormatException e) {
  50. // 用户输入非数字
  51. return false;
  52. }
  53. final int calculateResult = (int) Calculator.conversion(code);
  54. return result == calculateResult;
  55. }
  56. /**
  57. * 获取验证码长度
  58. *
  59. * @return 验证码长度
  60. */
  61. public int getLength() {
  62. return this.numberLength * 2 + 2;
  63. }
  64. /**
  65. * 根据长度获取参与计算数字最大值
  66. *
  67. * @return 最大值
  68. */
  69. private int getLimit() {
  70. return Integer.parseInt("1" + StringUtils.repeat('0', this.numberLength));
  71. }
  72. }