Last active
December 21, 2021 14:28
-
-
Save pjlsergeant/a6ed72105df8c98d827915fe203d08e7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!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