Merge pull request #14 from PrajwalGoudar/master

added code to generate font fun captcha(type_1)
This commit is contained in:
hrj 2019-03-13 10:12:39 +05:30 committed by GitHub
commit 8f701f255e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
9 changed files with 3451 additions and 3109 deletions

View File

@ -7,4 +7,3 @@ interface ChallengeProvider {
//TODO: def configure(): Unit
}

View File

@ -0,0 +1,48 @@
package lc;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.Random;
public class FontFunCaptcha implements ChallengeProvider{
public String getId() {
return "FontFunCaptcha";
}
private byte[] fontFun(String captchaText){
String[] fonts = {"Captcha Code","Mom'sTypewriter","Annifont","SF Intoxicated Blues",
"BeachType","Batmos","Barbecue","Bad Seed","Aswell","Alien Marksman"};
String[] colors = {"#f68787","#f8a978","#f1eb9a","#a4f6a5"};
BufferedImage img = new BufferedImage(350, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = img.createGraphics();
Random rand = new Random();
for(int i=0; i< captchaText.length(); i++) {
Font font = new Font(fonts[rand.nextInt(10)], Font.ROMAN_BASELINE, 48);
graphics2D.setFont(font);
FontMetrics fontMetrics = graphics2D.getFontMetrics();
HelperFunctions.setRenderingHints(graphics2D);
graphics2D.setColor(Color.decode(colors[rand.nextInt(4)]));
graphics2D.drawString(String.valueOf(captchaText.charAt(i)), (i * 48), fontMetrics.getAscent());
}
graphics2D.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(img,"png",baos);
}catch (Exception e){
e.printStackTrace();
}
return baos.toByteArray();
}
public Challenge returnChallenge() {
String secret = HelperFunctions.randomString(7);
return new Challenge(fontFun(secret),"png",secret.toLowerCase());
}
public boolean checkAnswer(String secret, String answer){
return answer.toLowerCase().equals(secret);
}
}

View File

@ -0,0 +1,55 @@
package lc;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.stream.ImageOutputStream;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.io.ByteArrayOutputStream;
public class GifCaptcha implements ChallengeProvider{
private BufferedImage charToImg(String text){
BufferedImage img = new BufferedImage(250, 100, BufferedImage.TYPE_INT_RGB);
Font font = new Font("Bradley Hand", Font.ROMAN_BASELINE, 48);
Graphics2D graphics2D = img.createGraphics();
graphics2D.setFont(font);
graphics2D.setColor(new Color((int)(Math.random() * 0x1000000)));
graphics2D.drawString( text , 45, 45);
graphics2D.dispose();
return img;
}
private byte[] gifCaptcha(String text){
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ImageOutputStream output = new MemoryCacheImageOutputStream(byteArrayOutputStream);
GifSequenceWriter writer = new GifSequenceWriter( output, 1,1000, true );
for(int i=0; i< text.length(); i++){
BufferedImage nextImage = charToImg(String.valueOf(text.charAt(i)));
writer.writeToSequence(nextImage);
}
writer.close();
output.close();
return byteArrayOutputStream.toByteArray();
} catch (IOException e){
e.printStackTrace();
}
return null;
}
public Challenge returnChallenge() {
String secret = HelperFunctions.randomString(6);
return new Challenge(gifCaptcha(secret),"gif",secret.toLowerCase());
}
public boolean checkAnswer(String secret, String answer) {
return answer.toLowerCase().equals(secret);
}
public String getId() {
return "GifCaptcha";
}
}

View File

@ -0,0 +1,151 @@
package lc;
import javax.imageio.*;
import javax.imageio.metadata.*;
import javax.imageio.stream.*;
import java.awt.image.*;
import java.io.*;
import java.util.Iterator;
public class GifSequenceWriter {
protected ImageWriter gifWriter;
protected ImageWriteParam imageWriteParam;
protected IIOMetadata imageMetaData;
/**
* Creates a new GifSequenceWriter
*
* @param outputStream the ImageOutputStream to be written to
* @param imageType one of the imageTypes specified in BufferedImage
* @param timeBetweenFramesMS the time between frames in miliseconds
* @param loopContinuously wether the gif should loop repeatedly
* @throws IIOException if no gif ImageWriters are found
*
* @author Elliot Kroo (elliot[at]kroo[dot]net)
*/
public GifSequenceWriter(
ImageOutputStream outputStream,
int imageType,
int timeBetweenFramesMS,
boolean loopContinuously) throws IIOException, IOException {
// my method to create a writer
gifWriter = getWriter();
imageWriteParam = gifWriter.getDefaultWriteParam();
ImageTypeSpecifier imageTypeSpecifier =
ImageTypeSpecifier.createFromBufferedImageType(imageType);
imageMetaData =
gifWriter.getDefaultImageMetadata(imageTypeSpecifier,
imageWriteParam);
String metaFormatName = imageMetaData.getNativeMetadataFormatName();
IIOMetadataNode root = (IIOMetadataNode)
imageMetaData.getAsTree(metaFormatName);
IIOMetadataNode graphicsControlExtensionNode = getNode(
root,
"GraphicControlExtension");
graphicsControlExtensionNode.setAttribute("disposalMethod", "none");
graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE");
graphicsControlExtensionNode.setAttribute(
"transparentColorFlag",
"FALSE");
graphicsControlExtensionNode.setAttribute(
"delayTime",
Integer.toString(timeBetweenFramesMS / 10));
graphicsControlExtensionNode.setAttribute(
"transparentColorIndex",
"0");
IIOMetadataNode commentsNode = getNode(root, "CommentExtensions");
commentsNode.setAttribute("CommentExtension", "Created by MAH");
IIOMetadataNode appEntensionsNode = getNode(
root,
"ApplicationExtensions");
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
int loop = loopContinuously ? 0 : 1;
child.setUserObject(new byte[]{ 0x1, (byte) (loop & 0xFF), (byte)
((loop >> 8) & 0xFF)});
appEntensionsNode.appendChild(child);
imageMetaData.setFromTree(metaFormatName, root);
gifWriter.setOutput(outputStream);
gifWriter.prepareWriteSequence(null);
}
public void writeToSequence(RenderedImage img) throws IOException {
gifWriter.writeToSequence(
new IIOImage(
img,
null,
imageMetaData),
imageWriteParam);
}
/**
* Close this GifSequenceWriter object. This does not close the underlying
* stream, just finishes off the GIF.
*/
public void close() throws IOException {
gifWriter.endWriteSequence();
}
/**
* Returns the first available GIF ImageWriter using
* ImageIO.getImageWritersBySuffix("gif").
*
* @return a GIF ImageWriter object
* @throws IIOException if no GIF image writers are returned
*/
private static ImageWriter getWriter() throws IIOException {
Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif");
if(!iter.hasNext()) {
throw new IIOException("No GIF Image Writers Exist");
} else {
return iter.next();
}
}
/**
* Returns an existing child node, or creates and returns a new child node (if
* the requested node does not exist).
*
* @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node.
* @param nodeName the name of the child node.
*
* @return the child node, if found or a new node created with the given name.
*/
private static IIOMetadataNode getNode(
IIOMetadataNode rootNode,
String nodeName) {
int nNodes = rootNode.getLength();
for (int i = 0; i < nNodes; i++) {
if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName)
== 0) {
return((IIOMetadataNode) rootNode.item(i));
}
}
IIOMetadataNode node = new IIOMetadataNode(nodeName);
rootNode.appendChild(node);
return(node);
}
/**
public GifSequenceWriter(
BufferedOutputStream outputStream,
int imageType,
int timeBetweenFramesMS,
boolean loopContinuously) {
*/
}

View File

@ -0,0 +1,23 @@
package lc;
import java.awt.*;
public class HelperFunctions {
public static void setRenderingHints(Graphics2D g2d){
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_ON);
}
public static String randomString(int n){
String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz23456789$#%@&?";
StringBuilder stringBuilder = new StringBuilder();
for(int i=0; i<n; i++){
int index = (int)(characters.length() * Math.random());
stringBuilder.append(characters.charAt(index));
}
return stringBuilder.toString();
}
}

View File

@ -0,0 +1,60 @@
package lc;
import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.font.TextLayout;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
public class ShadowTextCaptcha implements ChallengeProvider{
public String getId() {
return "ShadowText";
}
public boolean checkAnswer(String secret, String answer) {
return answer.toLowerCase().equals(secret);
}
private byte[] shadowText(String text){
BufferedImage img = new BufferedImage(350, 100, BufferedImage.TYPE_INT_RGB);
Font font = new Font("Arial",Font.ROMAN_BASELINE ,48);
Graphics2D graphics2D = img.createGraphics();
TextLayout textLayout = new TextLayout(text, font, graphics2D.getFontRenderContext());
HelperFunctions.setRenderingHints(graphics2D);
graphics2D.setPaint(Color.WHITE);
graphics2D.fillRect(0, 0, 350, 100);
graphics2D.setPaint(Color.BLACK);
textLayout.draw(graphics2D, 15, 50);
graphics2D.dispose();
float[] kernel = {
1f / 9f, 1f / 9f, 1f / 9f,
1f / 9f, 1f / 9f, 1f / 9f,
1f / 9f, 1f / 9f, 1f / 9f
};
ConvolveOp op = new ConvolveOp(new Kernel(3, 3, kernel),
ConvolveOp.EDGE_NO_OP, null);
BufferedImage img2 = op.filter(img, null);
Graphics2D g2d = img2.createGraphics();
HelperFunctions.setRenderingHints(g2d);
g2d.setPaint(Color.WHITE);
textLayout.draw(g2d, 13, 50);
g2d.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(img2,"png",baos);
}catch(Exception e){
e.printStackTrace();
}
return baos.toByteArray();
}
public Challenge returnChallenge() {
String secret = HelperFunctions.randomString(6);
return new Challenge(shadowText(secret),"png",secret.toLowerCase());
}
}

View File

@ -3,7 +3,10 @@ package lc
import com.sksamuel.scrimage._
import java.sql._
import java.io._
import httpserver._
import lc.HTTPServer._
import lc.FontFunCaptcha._
import lc.GifCaptcha._
import lc.ShadowTextCaptcha._
import javax.imageio._
import java.awt.image._
import org.json4s._
@ -23,7 +26,11 @@ class Captcha {
val selectPstmt: PreparedStatement = con.prepareStatement("SELECT secret, provider FROM challenge WHERE token = ?")
val imagePstmt: PreparedStatement = con.prepareStatement("SELECT image FROM challenge WHERE token = ?")
val filters = Map("FilterChallenge" -> new FilterChallenge)
val filters = Map("FilterChallenge" -> new FilterChallenge,
"FontFunCaptcha" -> new FontFunCaptcha,
"GifCaptcha" -> new GifCaptcha,
"ShadowTextCaptcha" -> new ShadowTextCaptcha
)
def getCaptcha(id: Id): Array[Byte] = {
imagePstmt.setString(1, id.id)
@ -38,12 +45,13 @@ class Captcha {
def getChallenge(param: Parameters): Id = {
//TODO: eval params to choose a provider
val providerMap = "FilterChallenge"
val providerMap = "GifCaptcha"
val provider = filters(providerMap)
val challenge = provider.returnChallenge()
val blob = new ByteArrayInputStream(challenge.content)
val token = scala.util.Random.nextInt(10000).toString
val id = Id(token)
print("Successfull")
insertPstmt.setString(1, token)
insertPstmt.setString(2, provider.getId)
insertPstmt.setString(3, challenge.secret)