| 1 | package Dancer2::Session::Pg::Cipher::AESGCM; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Moo; | ||
| 7 | use Carp qw( croak ); | ||
| 8 | use Crypt::AuthEnc::GCM (); | ||
| 9 | |||
| 10 | our $VERSION = '0.002'; | ||
| 11 | |||
| 12 | # The key length is the only thing that distinguishes the three, and it decides | ||
| 13 | # the stored id -- so these three numbers are as permanent as the ids are. | ||
| 14 | my %ID_FOR_KEY_BYTES = ( | ||
| 15 | 16 => 1, | ||
| 16 | 24 => 2, | ||
| 17 | 32 => 3, | ||
| 18 | ); | ||
| 19 | |||
| 20 | has key_bytes => ( is => 'ro', default => sub { 32 } ); | ||
| 21 | |||
| 22 | # BELOW the attribute, not above it: the role requires key_bytes, and Role::Tiny | ||
| 23 | # checks the required list at the moment `with` runs -- before `has` has made the | ||
| 24 | # accessor. Moving this line up gives "missing key_bytes" at compile time. | ||
| 25 | with 'Dancer2::Session::Pg::Cipher'; | ||
| 26 | |||
| 27 | sub BUILD { | ||
| 28 | my ($self) = @_; | ||
| 29 | croak sprintf '%s: key_bytes must be 16, 24 or 32 (got %s)', ref $self, | ||
| 30 | ( defined $self->key_bytes ? $self->key_bytes : 'undef' ) | ||
| 31 | if !defined $self->key_bytes || !exists $ID_FOR_KEY_BYTES{ $self->key_bytes }; | ||
| 32 | return; | ||
| 33 | } | ||
| 34 | |||
| 35 | sub cipher_id { my ($self) = @_; return $ID_FOR_KEY_BYTES{ $self->key_bytes } } | ||
| 36 | sub cipher_name { my ($self) = @_; return sprintf 'AES-%d-GCM', 8 * $self->key_bytes } | ||
| 37 | sub iv_bytes { return 12 } | ||
| 38 | sub tag_bytes { return 16 } | ||
| 39 | |||
| 40 | sub seal { | ||
| 41 | my ( $self, $key, $iv, $plaintext, $aad ) = @_; | ||
| 42 | return Crypt::AuthEnc::GCM::gcm_encrypt_authenticate( 'AES', $key, $iv, $aad, $plaintext ); | ||
| 43 | } | ||
| 44 | |||
| 45 | sub unseal { ## no critic (Subroutines::ProhibitManyArgs) -- six is the AEAD contract in Dancer2::Session::Pg::Cipher | ||
| 46 | my ( $self, $key, $iv, $ciphertext, $tag, $aad ) = @_; | ||
| 47 | return Crypt::AuthEnc::GCM::gcm_decrypt_verify( 'AES', $key, $iv, $aad, $ciphertext, $tag ); | ||
| 48 | } | ||
| 49 | |||
| 50 | 1; | ||
| 51 | |||
| 52 | __END__ |