Created
May 9, 2014 21:32
-
-
Save mrhanlon/f47eb1d2956a2432c6d4 to your computer and use it in GitHub Desktop.
Math Captcha for Java Portlets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static final String[] NUMBERS = {"zero","one","two","three","four","five","six","seven","eight","nine","ten"}; | |
private static final String[] OPERATIONS = {"+", "-", "×"}; | |
private static final Random RAND = new Random(); // not high entropy, but not a big deal here | |
private Map<String,String> generateCaptcha(PortletSession session) { | |
Map<String,String> captcha = new HashMap<String, String>(); | |
int first, second, third, op, pos, solution; | |
op = RAND.nextInt(OPERATIONS.length); | |
captcha.put("operation", OPERATIONS[op]); | |
switch (op) { | |
case 2: // multiplication; limit generated args to [1-5] | |
first = RAND.nextInt(5) + 1; | |
second = RAND.nextInt(5) + 1; | |
third = first * second; | |
break; | |
case 1: // subtraction | |
first = RAND.nextInt(NUMBERS.length); | |
second = RAND.nextInt(NUMBERS.length); | |
if (first < second) { | |
// reorder to ensure positive solution | |
int tmp = first; | |
first = second; | |
second = tmp; | |
} | |
third = first - second; | |
break; | |
default: // addition | |
first = RAND.nextInt(NUMBERS.length); | |
second = RAND.nextInt(NUMBERS.length); | |
third = first + second; | |
} | |
String rFirst = NUMBERS[first], rSecond = NUMBERS[second], rThird; | |
if (third < NUMBERS.length) { | |
rThird = NUMBERS[third]; | |
} else { | |
rThird = Integer.toString(third); | |
} | |
pos = RAND.nextInt(3); | |
switch (pos) { | |
case 0: | |
solution = first; | |
captcha.put("second", rSecond); | |
captcha.put("third", rThird); | |
break; | |
case 1: | |
captcha.put("first", rFirst); | |
solution = second; | |
captcha.put("third", rThird); | |
break; | |
default: | |
captcha.put("first", rFirst); | |
captcha.put("second", rSecond); | |
solution = third; | |
break; | |
} | |
session.setAttribute("captcha_solution", Integer.toString(solution)); | |
return captcha; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment