• Stars
    star
    1,818
  • Rank 25,535 (Top 0.6 %)
  • Language
    Go
  • License
    MIT License
  • Created over 13 years ago
  • Updated over 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Go package captcha implements generation and verification of image and audio CAPTCHAs.

Package captcha

⚠️ Warning: this captcha can be broken by advanced OCR captcha breaking algorithms.

import "github.com/dchest/captcha"

Package captcha implements generation and verification of image and audio CAPTCHAs.

A captcha solution is the sequence of digits 0-9 with the defined length. There are two captcha representations: image and audio.

An image representation is a PNG-encoded image with the solution printed on it in such a way that makes it hard for computers to solve it using OCR.

An audio representation is a WAVE-encoded (8 kHz unsigned 8-bit) sound with the spoken solution (currently in English, Russian, Chinese, and Japanese). To make it hard for computers to solve audio captcha, the voice that pronounces numbers has random speed and pitch, and there is a randomly generated background noise mixed into the sound.

This package doesn't require external files or libraries to generate captcha representations; it is self-contained.

To make captchas one-time, the package includes a memory storage that stores captcha ids, their solutions, and expiration time. Used captchas are removed from the store immediately after calling Verify or VerifyString, while unused captchas (user loaded a page with captcha, but didn't submit the form) are collected automatically after the predefined expiration time. Developers can also provide custom store (for example, which saves captcha ids and solutions in database) by implementing Store interface and registering the object with SetCustomStore.

Captchas are created by calling New, which returns the captcha id. Their representations, though, are created on-the-fly by calling WriteImage or WriteAudio functions. Created representations are not stored anywhere, but subsequent calls to these functions with the same id will write the same captcha solution. Reload function will create a new different solution for the provided captcha, allowing users to "reload" captcha if they can't solve the displayed one without reloading the whole page. Verify and VerifyString are used to verify that the given solution is the right one for the given captcha id.

Server provides an http.Handler which can serve image and audio representations of captchas automatically from the URL. It can also be used to reload captchas. Refer to Server function documentation for details, or take a look at the example in "capexample" subdirectory.

Examples

Image

Audio

Constants

const (
    // Default number of digits in captcha solution.
    DefaultLen = 6
    // The number of captchas created that triggers garbage collection used
    // by default store.
    CollectNum = 100
    // Expiration time of captchas used by default store.
    Expiration = 10 * time.Minute
)
const (
    // Standard width and height of a captcha image.
    StdWidth  = 240
    StdHeight = 80
)

Variables

var (
    ErrNotFound = errors.New("captcha: id not found")
)

Functions

func New

func New() string

New creates a new captcha with the standard length, saves it in the internal storage and returns its id.

func NewLen

func NewLen(length int) (id string)

NewLen is just like New, but accepts length of a captcha solution as the argument.

func RandomDigits

func RandomDigits(length int) (b []byte)

RandomDigits returns a byte slice of the given length containing pseudorandom numbers in range 0-9. The slice can be used as a captcha solution.

func Reload

func Reload(id string) bool

Reload generates and remembers new digits for the given captcha id. This function returns false if there is no captcha with the given id.

After calling this function, the image or audio presented to a user must be refreshed to show the new captcha representation (WriteImage and WriteAudio will write the new one).

func Server

func Server(imgWidth, imgHeight int) http.Handler

Server returns a handler that serves HTTP requests with image or audio representations of captchas. Image dimensions are accepted as arguments. The server decides which captcha to serve based on the last URL path component: file name part must contain a captcha id, file extension — its format (PNG or WAV).

For example, for file name "LBm5vMjHDtdUfaWYXiQX.png" it serves an image captcha with id "LBm5vMjHDtdUfaWYXiQX", and for "LBm5vMjHDtdUfaWYXiQX.wav" it serves the same captcha in audio format.

To serve a captcha as a downloadable file, the URL must be constructed in such a way as if the file to serve is in the "download" subdirectory: "/download/LBm5vMjHDtdUfaWYXiQX.wav".

To reload captcha (get a different solution for the same captcha id), append "?reload=x" to URL, where x may be anything (for example, current time or a random number to make browsers refetch an image instead of loading it from cache).

By default, the Server serves audio in English language. To serve audio captcha in one of the other supported languages, append "lang" value, for example, "?lang=ru".

func SetCustomStore

func SetCustomStore(s Store)

SetCustomStore sets custom storage for captchas, replacing the default memory store. This function must be called before generating any captchas.

func Verify

func Verify(id string, digits []byte) bool

Verify returns true if the given digits are the ones that were used to create the given captcha id.

The function deletes the captcha with the given id from the internal storage, so that the same captcha can't be verified anymore.

func VerifyString

func VerifyString(id string, digits string) bool

VerifyString is like Verify, but accepts a string of digits. It removes spaces and commas from the string, but any other characters, apart from digits and listed above, will cause the function to return false.

func WriteAudio

func WriteAudio(w io.Writer, id string, lang string) error

WriteAudio writes WAV-encoded audio representation of the captcha with the given id and the given language. If there are no sounds for the given language, English is used.

func WriteImage

func WriteImage(w io.Writer, id string, width, height int) error

WriteImage writes PNG-encoded image representation of the captcha with the given id. The image will have the given width and height.

Types

type Audio struct {
    // contains unexported fields
}

func NewAudio

func NewAudio(id string, digits []byte, lang string) *Audio

NewAudio returns a new audio captcha with the given digits, where each digit must be in range 0-9. Digits are pronounced in the given language. If there are no sounds for the given language, English is used.

Possible values for lang are "en", "ja", "ru", "zh".

func (*Audio) EncodedLen

func (a *Audio) EncodedLen() int

EncodedLen returns the length of WAV-encoded audio captcha.

func (*Audio) WriteTo

func (a *Audio) WriteTo(w io.Writer) (n int64, err error)

WriteTo writes captcha audio in WAVE format into the given io.Writer, and returns the number of bytes written and an error if any.

type Image struct {
    *image.Paletted
    // contains unexported fields
}

func NewImage

func NewImage(id string, digits []byte, width, height int) *Image

NewImage returns a new captcha image of the given width and height with the given digits, where each digit must be in range 0-9.

func (*Image) WriteTo

func (m *Image) WriteTo(w io.Writer) (int64, error)

WriteTo writes captcha image in PNG format into the given writer.

type Store interface {
    // Set sets the digits for the captcha id.
    Set(id string, digits []byte)

    // Get returns stored digits for the captcha id. Clear indicates
    // whether the captcha must be deleted from the store.
    Get(id string, clear bool) (digits []byte)
}

An object implementing Store interface can be registered with SetCustomStore function to handle storage and retrieval of captcha ids and solutions for them, replacing the default memory store.

It is the responsibility of an object to delete expired and used captchas when necessary (for example, the default memory store collects them in Set method after the certain amount of captchas has been stored.)

func NewMemoryStore

func NewMemoryStore(collectNum int, expiration time.Duration) Store

NewMemoryStore returns a new standard memory store for captchas with the given collection threshold and expiration time in seconds. The returned store must be registered with SetCustomStore to replace the default one.

More Repositories

1

tweetnacl-js

Port of TweetNaCl cryptographic library to JavaScript
JavaScript
1,663
star
2

uniuri

Go package uniuri generates random strings good for use in URIs to identify unique objects.
Go
429
star
3

webp-quicklook

[DEPRECATED] QuickLook plugin to generate thumbnails and previews for WebP images
C
281
star
4

siphash

Go implementation of SipHash-2-4, a fast short-input PRF created by Jean-Philippe Aumasson and Daniel J. Bernstein.
Go
258
star
5

semicolon-js

Semicolon.js — the most useful JavaScript library for cargo cult programmers
Shell
156
star
6

scrypt-async-js

Fast "async" scrypt implementation in JavaScript
JavaScript
139
star
7

fast-sha256-js

SHA-256, HMAC, HKDF and PBKDF2 implementation for JavaScript/TypeScript with typed arrays for modern browsers and Node.js
JavaScript
123
star
8

authcookie

[DEPRECATED] Go package authcookie implements creation and verification of signed authentication cookies.
Go
110
star
9

blake2b

Go implementation of BLAKE2 (b) cryptographic hash function (optimized for 64-bit platforms).
Go
90
star
10

blake2s-js

BLAKE2s cryptographic hash function in JavaScript
JavaScript
85
star
11

safefile

Go package safefile implements safe "atomic" saving of files.
Go
79
star
12

passwordreset

[DEPRECATED] Go package passwordreset implements creation and verification of secure tokens useful for implementation of "reset forgotten password" feature in web applications.
Go
78
star
13

ellipticlicense

Short product key generation and validation framework based on elliptic curve digital signatures (ECDSA) for Mac OS X/Cocoa. **DEPRECATED**
Objective-C
69
star
14

fossil-delta-js

Fossil SCM delta compression in JavaScript
JavaScript
67
star
15

tweetnacl-util-js

Some string encoding utilities
JavaScript
59
star
16

ed2curve-js

Convert Ed25519 signing keys into Curve25519 Diffie-Hellman keys
JavaScript
56
star
17

stemmer

Stemmer packages for Go programming language. Includes English, German and Dutch stemmers.
Go
50
star
18

pyblake2

Python extension module implementing BLAKE2 hash function
Python
38
star
19

nacl-stream-js

Streaming encryption based on TweetNaCl.js
JavaScript
36
star
20

scrypt

Go package scrypt implements the scrypt key derivation function as defined in Colin Percival's paper "Stronger Key Derivation via Sequential Memory-Hard Functions".
Go
31
star
21

pybayesantispam

Simple Bayesian spam rating in Python that is easy to use, small, contained in a single file, and doesn't require any external modules.
Python
27
star
22

static-search

Simple client-side static search engine (Go indexer, JavaScript searcher).
JavaScript
23
star
23

blake256

Go package blake256 implements BLAKE-256 and BLAKE-224 hash functions (SHA-3 finalist).
Go
20
star
24

tweetnacl-auth-js

HMAC-SHA-512-256 for TweetNacl.js
JavaScript
20
star
25

spipe

Go package spipe implements spiped protocol for creating symmetrically encrypted and authenticated connections.
Go
20
star
26

cryptopass

Chrome extension: password generator from master key using PBKDF2 with SHA-256.
JavaScript
18
star
27

jsmin

Go package to minify JavaScript, which is a direct port of Douglas Crockford's JSMin
Go
17
star
28

historic-password-hashes

Historic password hashing algorithms
C
16
star
29

b2sum

Go implementation of b2sum utility to calculate BLAKE2 checksums (GitHub Mirror)
Go
16
star
30

validator

Go package validator validates and normalizes email addresses and domain names.
Go
16
star
31

drakon-tea

TEA cipher in CBC mode written in DRAKON Editor + C as a fun exercise.
C
14
star
32

tinyscheme

Tiny fork of TinySCHEME to support no-hassle building on Mac OS X (plus a bridge to Objective-C, but use CocoaScheme instead of this) WARNING: NOT UPDATED, OLD
C
14
star
33

minimal-newtab

Chrome Extension: Minimalistic New Tab page that displays bookmarks from Bookmarks Bar and number of new messages in Gmail (including Google Apps).
JavaScript
12
star
34

htmlmin

Go package to minify HTML (alpha-quality)
Go
12
star
35

kkr

Kukuruz - static site generator similar to Jekyll in Go.
Go
11
star
36

blake2s

Go implementation of BLAKE2 (s) cryptographic hash function (optimized for 32-bit platforms).
Go
11
star
37

cache

Go package cache implements LRU (Least Recently Used) cache algorithm. [[ Deprecated, use https://github.com/dchest/lru ]]
Go
11
star
38

nacl

Pure Go implementation of NaCl: Networking and Cryptography Library. USE IMPLEMENTATION FROM go.crypto INSTEAD OF THIS ONE.
Go
11
star
39

bcrypt_pbkdf

Go implementation of bcrypt_pbkdf(3) from OpenBSD
Go
11
star
40

scryptutil

Go reimplementation of Colin Percival's scrypt file encryption utility.
Go
10
star
41

throttled-webrate

Another RateLimit for throttled
Go
10
star
42

uscrypt

Go package uscrypt implements Unix crypt-like password hashing scheme based on scrypt sequential memory-hard key derivation function.
Go
10
star
43

blake512

Go package blake512 implements BLAKE-512 and BLAKE-384 hash functions (SHA-3 finalist).
Go
10
star
44

qlfossil

OS X QuickLook plugin to display Fossil repositories
Objective-C
9
star
45

gotweet

This was the first command-line Twitter client in Go programming language, written two days after the release of Go. IT NO LONGER WORKS BECAUSE TWITTER REMOVED HTTP AUTHENTICATION SUPPORT IN API. Use the one in the link below!
Go
9
star
46

skein

Go implementation of Skein-512 hash function, MAC, and stream cipher.
Go
8
star
47

passwordhash

Go package for safe password hashing and comparison. (THIS PACKAGE IS DEPRECATED! USE bcrypt OR scrypt FROM go.crypto)
Go
8
star
48

hesfic

Content-addressable encrypted storage or something like that
Go
8
star
49

passwordcheck

Go package passwordcheck is a password and passphrase strength checker based on passwdqc.
C
7
star
50

imgpreview

Tiny image previews for HTML while the original image is loading
Go
7
star
51

varuint

Go package varuint implements SQLite4-like variable unsigned integer encoding.
Go
7
star
52

imageutil

Go package imageutil implements functions for the manipulation of images.
Go
7
star
53

ick

Stupid (but fast) static site generator
C
7
star
54

wots

Go package wots implements Winternitz-Lamport-Diffie one-time signature scheme.
Go
7
star
55

cssmin

Go package to minify CSS, which is a direct port of Ryan Grove's cssmin from Ruby
Go
6
star
56

zibr

Repack ZIP or PNG files into Brotli
Go
6
star
57

pbkdf2

Go implementation of PBKDF2 key derivation function. (Modified original from https://bitbucket.org/taruti/pbkdf2.go) DEPRECATED. Please use the one from the official go.crypto repo: http://code.google.com/p/go/source/browse?repo=crypto#hg%2Fpbkdf2
Go
6
star
58

commit-ads

Put your ad into my commit!
5
star
59

blakesum

Utility to calculate BLAKE-224, -256, -385, or -512 checksums.
Go
5
star
60

siv

[WORK-IN-PROGRESS] Go package siv implements Synthetic Initialization Vector (SIV) authenticated encryption using AES (AES-SIV) as specified in RFC 5297
Go
5
star
61

chacha20

Go package chacha20 implements ChaCha stream cipher.
Go
5
star
62

dhgroup14

Go package dhgroup14 implements blinded Diffie-Hellman key agreement with 2048-bit group #14 modulus from RFC 3526.
Go
4
star
63

CocoaScheme

Unfinished Scheme<->Objective-C bridge using s7 Scheme interpreter.
C
4
star
64

osxzip

Functions to compress and decompress ZIP files that preserve Mac OS X resource forks / extended attributes like Apple's Archive Utility.
4
star
65

gimli-js

Gimli permutation and hash implementation in JavaScript
JavaScript
4
star
66

threefish

Go implementation of Threefish-512 block cipher.
Go
4
star
67

comboserver

Comboserver serves multiple files combined in a single request.
Go
4
star
68

blake2xb

Go implementation of BLAKE2Xb XOF
Go
4
star
69

gospiped

spiped and spipe utilities reimplemented in Go
Go
4
star
70

tweets

My Twitter archive
JavaScript
3
star
71

translit.go

Go package translit implements non-standard one-way string transliteration from Cyrillic to Latin.
Go
3
star
72

Dockity

Mac OS X utility that automatically hides or shows dock based on windows positions, just like Ubuntu's Unity. (Click on releases to get binaries)
Objective-C
3
star
73

geli-threefish

geli-threefish is a set of patches for FreeBSD geom-eli and crypto kernel modules to support disk encryption with Threefish-512 algorithm.
C
3
star
74

vim-settings

My OLD .vim and .vimrc. SEE dchest/dotvim FOR A CLEAN START
Vim Script
3
star
75

generatepassword-js

Random password generator in JavaScript for browsers
JavaScript
3
star
76

Utilities

Various utility categories and classes (Objective-C)
Objective-C
3
star
77

godbm

UNMAINTAINED, not written by me. Forked from tux21b to send pull request, but the original seem to be no longer available. /// A simple DBM package for Go
Go
3
star
78

conflag

Drop-in replacement for Go's flag package that reads config files before command-line arguments
Go
3
star
79

dchest.com

My website
HTML
2
star
80

blake2xs

Go implementation of BLAKE2Xs XOF
Go
2
star
81

cmac

CMAC implementation from old Go crypto package converted to modern Go
Go
2
star
82

lua-corweb

Tiny unfinished Lua coroutine-based stateful web framework.
Lua
2
star
83

xaes

JavaScript XAES-256-GCM implementation using Web Cryptography API
JavaScript
2
star
84

dart-blake

BLAKE-256 hash function implementation for Dart language.
Dart
2
star
85

kukuruz

Static site generator similar to jekyll in Go (incomplete, but works). This version is deprecated, please see github.com/dchest/kkr for a new one!
Go
2
star
86

hide-google-plus-bell

Chrome extension to hide Google+ notifications bell (NO LONGER WORKS)
CSS
2
star
87

emacs-settings

My .emacs.d directory and .emacs (symlink it to ~/.emacs.d/emacs)
Emacs Lisp
2
star
88

cgirunner

Simple CGI runner in Go (aka "make nginx run CGIs")
Go
1
star
89

cbrotli

cbrotli without libbrotli
C
1
star
90

Lunokhod

Lua-Cocoa bindings and more (not ready, no longer developed)
C
1
star
91

db-api

PostgreSQL database with API
PLpgSQL
1
star
92

ficly-writes-like

Analyzes ficly.com stories using iwl.me
JavaScript
1
star
93

randomword

Print random word
Go
1
star
94

font-nsa

NSA Smiley Font
CSS
1
star
95

spipe-examples

Examples of using spipe package
Go
1
star
96

onmap

Go package onmap puts pins on a world map image.
Go
1
star
97

password-gen

GUI in Racket for password generator as in http://sellme.ru/p/
Racket
1
star
98

racket-cdb

Racket interface to TinyCDB library
Racket
1
star
99

kdfutil

Some useful key derivation utilities for Go
Go
1
star
100

blake2-dart

BLAKE2s implementation in Dart language.
Dart
1
star