Airlock
view release on metacpan or search on metacpan
lib/Airlock/Code.pm view on Meta::CPAN
package Airlock::Code;
# ABSTRACT: Generate, normalize, hash and compare Airlock codes
use Moo;
use Crypt::URandom qw( urandom );
use Digest::SHA qw( sha256_hex );
use Types::Standard qw( Int Str );
use namespace::autoclean;
our $VERSION = '0.001';
has alphabet => (
is => 'ro',
isa => Str,
default => 'BCDFGHJKLMNPQRSTVWXZ'
);
has user_code_length => (
is => 'ro',
isa => Int,
default => 8
);
has secret_bytes => (
is => 'ro',
isa => Int,
default => 32
);
sub user_code {
my ( $self ) = @_;
my @chars = split //, $self->alphabet;
my $limit = 256 - ( 256 % @chars );
my $code = '';
while ( length $code < $self->user_code_length ) {
for my $byte ( unpack 'C*', urandom(16) ) {
next if $byte >= $limit;
$code .= $chars[ $byte % @chars ];
last if length $code == $self->user_code_length;
}
}
return $code;
}
sub secret { unpack 'H*', urandom( $_[0]->secret_bytes ) }
sub hash {
my ( $self, $value ) = @_;
utf8::encode($value) if utf8::is_utf8($value);
return sha256_hex($value);
}
sub normalize {
my ( $self, $input ) = @_;
return unless defined $input;
my $code = uc $input;
$code =~ s/[\s\-_.]//g;
my $alphabet = $self->alphabet;
return unless length $code == $self->user_code_length;
return unless $code =~ /\A[\Q$alphabet\E]+\z/;
return $code;
}
sub display {
my ( $self, $code ) = @_;
return join '-', $code =~ /(.{1,4})/g;
}
sub equals {
my ( $self, $left, $right ) = @_;
return 0 unless defined $left && defined $right;
return 0 unless length $left == length $right;
my $diff = 0;
$diff |= ord( substr $left, $_, 1 ) ^ ord( substr $right, $_, 1 ) for 0 .. length($left) - 1;
return $diff == 0 ? 1 : 0;
}
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Airlock::Code - Generate, normalize, hash and compare Airlock codes
=head1 VERSION
version 0.001
=head1 SYNOPSIS
my $code = Airlock::Code->new;
my $user_code = $code->user_code; # 'BCDFGHJK'
print $code->display($user_code); # 'BCDF-GHJK'
my $clean = $code->normalize('bcdf ghjk'); # 'BCDFGHJK', or nothing
my $device_code = $code->secret; # 64 hex characters
my $stored = $code->hash($device_code); # SHA-256, hex
=head1 DESCRIPTION
( run in 0.851 second using v1.01-cache-2.11-cpan-234fa220139 )