Bug 28998: Introduce Koha::Encryption
authorJonathan Druart <jonathan.druart@bugs.koha-community.org>
Fri, 10 Sep 2021 09:27:33 +0000 (11:27 +0200)
committerFridolin Somers <fridolin.somers@biblibre.com>
Wed, 4 May 2022 15:18:31 +0000 (05:18 -1000)
Test plan:
Run t/db_dependent/Koha/Encryption.t

Signed-off-by: Marcel de Rooy <m.de.rooy@rijksmuseum.nl>
[AMENDED] Added copyright line to module.
Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Signed-off-by: Fridolin Somers <fridolin.somers@biblibre.com>
Koha/Encryption.pm [new file with mode: 0644]
t/db_dependent/Koha/Encryption.t [new file with mode: 0755]

diff --git a/Koha/Encryption.pm b/Koha/Encryption.pm
new file mode 100644 (file)
index 0000000..aaa9125
--- /dev/null
@@ -0,0 +1,61 @@
+package Koha::Encryption;
+
+# Copyright 2022 Koha Development Team
+#
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
+
+use Modern::Perl;
+
+use base qw( Crypt::CBC );
+
+=head1 NAME
+
+Koha::Encryption - Koha class to encrypt or decrypt strings
+
+=head1 SYNOPSIS
+
+  use Koha::Encryption;
+  my $secret    = Koha::AuthUtils::generate_salt( 'weak', 16 );
+  my $crypt     = Koha::Encryption->new;
+  my $encrypted = $crypt->encrypt_hex($secret);
+  my $decrypted = $crypt->decrypt_hex($encrypted);
+
+  return 1 if $decrypted eq $secret;
+
+It's based on Crypt::CBC
+
+=cut
+
+=head2 METHODS
+
+=head3 new
+
+    my $cipher = Koha::Encryption->new;
+
+    Constructor. Uses encryption_key from koha-conf.xml.
+
+=cut
+
+sub new {
+    my ( $class ) = @_;
+    my $key = C4::Context->config('encryption_key');
+    return $class->SUPER::new(
+        -key    => $key,
+        -cipher => 'Cipher::AES'
+    );
+}
+
+1;
diff --git a/t/db_dependent/Koha/Encryption.t b/t/db_dependent/Koha/Encryption.t
new file mode 100755 (executable)
index 0000000..52373ff
--- /dev/null
@@ -0,0 +1,13 @@
+use Modern::Perl;
+
+use Test::More tests => 1;
+use Koha::Encryption;
+use t::lib::Mocks;
+
+t::lib::Mocks::mock_config('encryption_key', 'my secret passphrase');
+
+my $string = 'a string to encrypt';
+
+my $crypt = Koha::Encryption->new;
+my $encrypted_string = $crypt->encrypt_hex($string);
+is( $crypt->decrypt_hex($encrypted_string), $string, 'Decrypted to original text' );