Skip to content

Instantly share code, notes, and snippets.

@glebkema
Last active June 4, 2020 10:27
Show Gist options
  • Save glebkema/39f0bbb0d20722c1a7ff049f0449f8a4 to your computer and use it in GitHub Desktop.
Save glebkema/39f0bbb0d20722c1a7ff049f0449f8a4 to your computer and use it in GitHub Desktop.
Encrypt and decrypt all digits in the expiration time by the Affine cipher
<?php
// Answer for https://www.gutefrage.net/frage/wie-kann-man-einen-php-token-generator-machen#answer-352860809
// Encrypt and decrypt all digits in the expiration time by the Affine cipher
// https://en.wikipedia.org/wiki/Affine_cipher
// https://stackoverflow.com/a/23679870/6263942
// encypt and decrypt the digit by the Affine cipher
function encrypt_digit( $digit ) {
return ( 7 * $digit ) % 10;
// return ( 7 * $digit + 3 ) % 10;
}
function decrypt_digit( $digit ) {
return ( 3 * $digit ) % 10;
// return ( 3 * ( $digit - 3 ) + 10 ) % 10;
}
// encypt and decrypt all digits in the number
function encrypt_number( $number ) {
$array = array_map( 'intval', str_split( $number ) );
return implode( array_map( 'encrypt_digit', $array ) );
}
function decrypt_number( $number ) {
$array = array_map( 'intval', str_split( $number ) );
return implode( array_map( 'decrypt_digit', $array ) );
}
function get_expiration_time( $minutes = 60 ) {
return time() + $minutes * 60;
}
function is_expired( $time ) {
return intval( $time ) < time();
}
// test the encryption and decryption of the digits
for ($i = 0; $i < 10; $i++) {
$e = encrypt_digit( $i );
echo $i . "\t" . $e . "\t" . decrypt_digit( $e ) . PHP_EOL;
}
// test the encryption and decryption of the time
$expiration_time = get_expiration_time( 0 );
$encrypted = encrypt_number( $expiration_time );
$decrypted = decrypt_number( $encrypted );
echo $expiration_time . PHP_EOL;
echo $encrypted . PHP_EOL;
echo $decrypted . PHP_EOL;
echo ( is_expired( $decrypted ) ? 'expired' : 'not expired' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment