Skip to content

Instantly share code, notes, and snippets.

@ugexe

ugexe/base64.pl6 Secret

Last active July 17, 2016 17:34
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 ugexe/7ce08d3ad4cfd36f275c437ba9713471 to your computer and use it in GitHub Desktop.
Save ugexe/7ce08d3ad4cfd36f275c437ba9713471 to your computer and use it in GitHub Desktop.
sub decode-base64(Str:D $str, Bool:D :$bin = False) {
my @alpha = flat 'A'..'Z','a'..'z','0'..'9', '+', '/';
my %encodings = @alpha.kv.hash.antipairs;
my $ords := $str.comb(/@alpha/).rotor(4, :partial).map: -> $chunk {
my $n = [+] $chunk.map: { (%encodings{$_} || 0) +< ((state $m = 24) -= 6) }
my $res = (16, 8, 0).map: { $n +> $_ +& 255 }
slip( $res.head( 3 - ( 4 - $chunk.elems ) ) );
}
?$bin ?? Buf.new($ords || 0) !! $ords
}
my $str = decode-base64("dXNlcm5hbWU6dGhpc2lzbm90bXlwYXNzd29yZA==", :bin).decode;
exit $str eq "username:thisisnotmypassword" ?? 0 !! 1;
# say decode-base64("dXNlcm5hbWU6dGhpc2lzbm90bXlwYXNzd29yZA==")
# -> 2016.06: (117 115 101 114 110 97 109 101 58 116 104 105 115 105 115 110 111 116 109 121 112 97 115 115 119 111 114 100)
# -> 2016.07: (117 115 101 114 110 97 109 101 58 116 104 105 115 105 115 110 111 116 109 121 112 97 115 115 119 111 114 100)
# say decode-base64("dXNlcm5hbWU6dGhpc2lzbm90bXlwYXNzd29yZA==", :bin)
# -> 2016.06: Buf:0x<75 73 65 72 6e 61 6d 65 3a 74 68 69 73 69 73 6e 6f 74 6d 79 70 61 73 73 77 6f 72 64>
# -> 2016.07: Buf:0x<75 72 6e 61 6d 65 3a 74 68 69 73 69 73 6e 6f 74 6d 79 70 61 73 73 77 6f 72 64>
# Notes:
# - It always seems to lose the same two items (index 1 and 2)
# - s/Buf.new($ords || 0)/Buf.new($ords)/ gives the correct results
@ugexe
Copy link
Author

ugexe commented Jul 17, 2016

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment