Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

dchest/captcha

Repository files navigation

⚠️ 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 audioCAPTCHAs.

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 onit 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 thespoken solution (currently in English, Russian, Chinese, and Japanese). To makeit hard for computers to solve audio captcha, the voice that pronounces numbershas random speed and pitch, and there is a randomly generated background noisemixed into the sound.

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

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

Captchas are created by calling New, which returns the captcha id. Theirrepresentations, though, are created on-the-fly by calling WriteImage orWriteAudio functions. Created representations are not stored anywhere, butsubsequent calls to these functions with the same id will write the samecaptcha solution. Reload function will create a new different solution for theprovided captcha, allowing users to "reload" captcha if they can't solve thedisplayed one without reloading the whole page. Verify and VerifyString areused to verify that the given solution is the right one for the given captchaid.

Server provides an http.Handler which can serve image and audiorepresentations of captchas automatically from the URL. It can also be usedto reload captchas. Refer to Server function documentation for details, ortake 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=240StdHeight=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 internalstorage 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 theargument.

func RandomDigits

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

RandomDigits returns a byte slice of the given length containingpseudorandom numbers in range 0-9. The slice can be used as a captchasolution.

func Reload

func Reload(id string) bool

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

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

func Server

func Server(imgWidth, imgHeight int) http.Handler

Server returns a handler that serves HTTP requests with image oraudio representations of captchas. Image dimensions are accepted asarguments. The server decides which captcha to serve based on the last URLpath 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 captchawith id "LBm5vMjHDtdUfaWYXiQX", and for "LBm5vMjHDtdUfaWYXiQX.wav" it serves thesame captcha in audio format.

To serve a captcha as a downloadable file, the URL must be constructed insuch 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 arandom number to make browsers refetch an image instead of loading it fromcache).

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

func SetCustomStore

func SetCustomStore(s Store)

SetCustomStore sets custom storage for captchas, replacing the defaultmemory 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 tocreate the given captcha id.

The function deletes the captcha with the given id from the internalstorage, 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 removesspaces and commas from the string, but any other characters, apart fromdigits 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 thegiven id and the given language. If there are no sounds for the givenlanguage, 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 thegiven id. The image will have the given width and height.

Types

typeAudiostruct {// 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 digitmust be in range 0-9. Digits are pronounced in the given language. If thereare no sounds for the given language, English is used.

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

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, andreturns the number of bytes written and an error if any.

typeImagestruct {*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 thegiven 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.

typeStoreinterface {// Set sets the digits for the captcha id.Set(idstring,digits []byte)// Get returns stored digits for the captcha id. Clear indicates// whether the captcha must be deleted from the store.Get(idstring,clearbool) (digits []byte)}

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

It is the responsibility of an object to delete expired and used captchaswhen necessary (for example, the default memory store collects them in Setmethod 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 thegiven collection threshold and expiration time in seconds. The returnedstore must be registered with SetCustomStore to replace the default one.

About

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

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp