1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
@Slf4j @Component public class VerifyCodeManager {
private final byte[] VERIFY_CODE_KEY = SecureUtil.generateKey(SymmetricAlgorithm.AES.getValue()).getEncoded();
private static final int VERIFY_CODE_HEIGHT = 50;
private static final int VERIFY_CODE_WIDTH = 150;
private static final int VERIFY_CODE_VALID_TIME = 5 * 60 * 1000;
public boolean checkVerifyCode(String usage, String verifyCode, String verification) { if (usage == null || verifyCode == null || verification == null) { return false; } boolean isValid = true; try { SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, VERIFY_CODE_KEY); String decryptStr = aes.decryptStr(verification); log.debug("解密后的验证码内容为:{}", decryptStr); String[] split = decryptStr.split("_"); if (split.length != 3 || !NumberUtil.isNumber(split[2])) { isValid = false; } if (!split[0].equalsIgnoreCase(usage)) { isValid = false; } if (!split[1].equalsIgnoreCase(verifyCode)) { isValid = false; } if (System.currentTimeMillis() > Long.parseLong(split[2])) { isValid = false; } } catch (Exception e) { log.debug("验证码校验出错", e); isValid = false; } return isValid; }
public VerifyCode createVerifyCode(String usage) { SpecCaptcha specCaptcha = new SpecCaptcha(VERIFY_CODE_WIDTH, VERIFY_CODE_HEIGHT); String base64Image = specCaptcha.toBase64(); String code = specCaptcha.text(); long expire = System.currentTimeMillis() + VERIFY_CODE_VALID_TIME; String verifyString = String.format("%s_%s_%d", usage, code, expire); SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, VERIFY_CODE_KEY); String verification = aes.encryptHex(verifyString); log.debug("生成的验证码为:{},用处为:{},有效期为:{}", code, usage, expire); return new VerifyCode(base64Image, verification); } }
|