Skip to content

Instantly share code, notes, and snippets.

@pjlsergeant
Last active December 21, 2021 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjlsergeant/a6ed72105df8c98d827915fe203d08e7 to your computer and use it in GitHub Desktop.
Save pjlsergeant/a6ed72105df8c98d827915fe203d08e7 to your computer and use it in GitHub Desktop.
#!perl
# Dictionary encrypted so the keys aren't enumerable, but where possession of
# a key allows you to decrypt the value.
#
# eg: a translations file where you don't want people to be able to know all
# the translated strings, but you do want someone with a string to be able
# to translate it
use strict;
use warnings;
use Crypt::CBC;
use Data::Printer;
my $enc = encrypt({ foo => 'bar', bar => 2 });
p $enc;
my $dec = { map { $_ => decrypt( $enc, $_ ) } qw/foo bar/ };
p $dec;
sub encrypt {
my $hash = shift;
my $new_hash = {};
for my $old_key ( keys %$hash ) {
# Replace with sensible hashing system
my $new_key = crypt( $old_key, 'na' );
# Replace with a more sensibly-derived key
my $cipher = Crypt::CBC->new( -key => $old_key, -cipher => 'Cipher::AES' );
$new_hash->{ $new_key } = $cipher->encrypt( $hash->{ $old_key } );
}
return $new_hash;
}
sub decrypt {
my ( $hash, $key ) = @_;
my $hashed_key = crypt( $key, 'na' );
my $encrypted_value = $hash->{ $hashed_key } || return;
my $cipher = Crypt::CBC->new( -key => $key, -cipher => 'Cipher::AES' );
return $cipher->decrypt( $encrypted_value );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment