Skip to content

Instantly share code, notes, and snippets.

@pjlsergeant
Last active December 21, 2021 14:28
Show Gist options
  • Select an option

  • Save pjlsergeant/a6ed72105df8c98d827915fe203d08e7 to your computer and use it in GitHub Desktop.

Select an option

Save pjlsergeant/a6ed72105df8c98d827915fe203d08e7 to your computer and use it in GitHub Desktop.

Revisions

  1. Peter Sergeant revised this gist Dec 21, 2021. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion crypt-dict.pl
    Original file line number Diff line number Diff line change
    @@ -26,7 +26,7 @@ sub encrypt {
    for my $old_key ( keys %$hash ) {
    # Replace with sensible hashing system
    my $new_key = crypt( $old_key, 'na' );
    # Replace with a more sensible password
    # 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 } );
    }
  2. Peter Sergeant created this gist Dec 21, 2021.
    44 changes: 44 additions & 0 deletions crypt-dict.pl
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,44 @@
    #!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 sensible password
    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 );
    }