HomeToolboxGallery

Software & Services
Hotels "R" MeIdleGuardKeyGuardNetflowNsUpkeeppsRadarVPN BypassWiFi Jitter Analyzer
Thronic.com content is FREE. Monetary support is optional.
Find anything of value?
PayPal, Bitcoin


Scripts
2D Rotation (JS)3D Rotation (JS)KiKiTrix (JS)AutoWrite (JS)Digitize Text (JS)Image Animation (JS)ASCII Loading Indicator (JS)Div Layer Movement (JS)Div Layer Resizing (JS)Text Scrolling (JS)Statistics Graph (PHP)RW Protect (BAT)SRT Renamer (PHP)String Encryption (PHP)Windows WiFi Hotspot (BAT)

General Computing

Thoughts on Coding StyleDomain 301 Perma RedirectWin/Linux PuTTY File TransferOpenVPN Site-to-Site SetupParity Data CheckingRclone Quick ReferenceSnapRAID NotesSSH TunnelingTransfer E-Mails with IMAPUDK Third Person CameraVPN Protocol Ports

GNU/Linux

Apache Process Mem UsageApache and CA OpenSSLApache2 htpasswd NotesCentOS 7 GlusterFS NotesCracking WEP and WPADebian 7 on Hyper-VDebian 7 to 8 UpgradeDebian 8 to 9 UpgradeDebian 9 DRBD SetupDebian and VirtualboxDebian and LSBInitScriptsDebian and systemdDebian Apache LetsEncryptDebian Apt AutoremoveDebian Cron & AnacronDebian KVM HypervisorLinux Bash ColorsLinux Cron BackupLinux Dnsmasq Setup NotesIptables Chain ExampleIptables Firewall and GatewayLinux MD RAID BasicsLinux iproute2 RoutingLinux SFTP Network ShareAvoid Linux Shell LoggingChecking Storage UsageLinux I/O Disk PerformanceLinux ZFS NotesVi/Vim Basic Reference

Microsoft
Bypass Windows PasswordDaz and ToolkitInt/Ext Drive ConfusionMRTG Network Traffic ViewMS Outlook NotesDOS File Content SearchDOS Merging VCF filesROBOCOPY Batch ScriptingPowerShell Reference NotesTeamViewer on HeadlessWorkgroup Failover ClusterDisable OneDrive in W10Windows WiFi and netshWindows Boot Custom UIHyper-V NetworkingHyper-V ReplicationIIS10 and PHP7 SetupPlex Media Server MigrationSecuring RDP ConnectionsServer 2012 R2 SetupWBAdmin Bare-Metal Backup

BSD/UNIX
FreeBSD 10.0 Setup (NOR)

C#/.NET
C# Associative ArraysC# Asynchronized WebcallC# Base64 GZipped JSONC# Code Execution TimerC# Dealing with WhitespacesC# djDBI for SQL CEC# Form ReferencingC# Get Folder SizeC# Handling DisconnectsC# HTTP POST and GETC# Importing DLL FunctionsC# Installing ServicesC# Kill and Start ProcessesC# Lambda ExpressionsC# Local AppData HandlingC# Memory StreamReadingC# Minimize to System TrayC# PDFsharp and MigraDocC# Public Fields vs PropsC# Registry HandlingC# Regular ExpressionsC# Require AdministratorC# RichTextBox File StreamC# Application SettingsC# SqlCeConnection CodeC# Start with hidden formC# String EncryptionC# Cross Thread HandlingC# Updating A RuntimeC# Gmail as SMTPVSI Dependency ErrorC# Handle XML

C/C++
C Autodelete Old FilesC/C++ Multiline StringsC Socket ListeningC StringsWin32 Button ControlWin32 Edit ControlWin32 GetLastError()Win32 KeyloggingWin32 KeypostingWin32 Simple WindowWin32 Socket ProgrammingWin32 VERSIONINFO

PHP
Bitwise IP HandlingPHP ClassesContent Length HandlingDetecting Mobile BrowsersdjDBI Database InterfaceHostname and Port RegexJSON Output HeadersMS Access Conn with COMProportional Image SizingRandom StringsRecursive FunctionsSending MailPHP SessionsSimple HTML-2-PDFPHP SimpleXMLTernary Operator and If/Else

SQL
MS Access Connection StringsMSSQL Case SensitivityMySQL Root Password ResetMySQL Check Slow QueriesColumn CountingQuick Note on CROSS JOINQuick Note on INNER JOINRandom Rows

HTML
HTML Raw Skeleton

JavaScript
AJAX Basicsevent.keyCode ReferenceIE7 Onclick EventsIE GIF Animation Problem

Java
Java Notater (NOR)

CSS
Border StylesFlyout MenusFont-Family Reference

Electrical

Betegnelser og SpenningsfallLovdata Elektrisk ArbeidResistors Series and ParallelSilicone and Circuit Boards

RC Hobby
Engine Break-In Procedure

Gaming

CSS Dedicated Server






Dag J Nedrelid
System and web developer. Tech hobbyist. Dad. Gamer.

PHP String Encryption (symmetric)

By Dag, on December 22nd, 2016

2 functions I wrote for encrypting strings between web pages using simple character level randomization with a reversed idea of private key usage where the data is never shared, and the encrypted string itself is just a map.

Without the randomized key, the map (encrypted string) is totally useless. There is no way of brute force cracking the encrypted data itself without the private key, like with math / semiprime based (e.g. RSA) encryptions. So you can protect the system by limiting failed attempts to avoid hackers from mapping the key, and changing it on a regular basis before enough attempts to map it is possible.

By having your source and target script read the private key from the same protected space in a closed system, you can effectively change it on every usage, making it practically impossible to crack since the encrypted value on its own is useless data without having a key to run it against. If used this way, it's a very strong and simple protective measure for encrypting simple alphanumeric(++) data.

The lock/encrypt function:
function djEncryptString($string, $key) 
{
	// $string is a random string to be encrypted.
	// $key is a randomized string that must contain all 
	// the characters found in $string as an absolute minimum.
	
	$key_chars = str_split($key);
	$string_chars = str_split($string);
	$key_coords = '';
	$key_coord_lengths = '';

	foreach($string_chars as $s_char) {
		for ($loop_a = 0; $loop_a < count($key_chars); $loop_a++) {
			if ($s_char == $key_chars[$loop_a]) {
				$key_coords .= (string)$loop_a;
				$key_coord_lengths .= (string)strlen($loop_a);
			}
		}
	}
	
	// Returns a string of coordinates of where the string 
	// characters are to be found within $key as well as the 
	// length of every coordinate since the string is a line 
	// of random numbers.
	
	return $key_coords .'-'. $key_coord_lengths;
}

The unlock/decrypt function:
function djDecryptString($enc_str, $key) 
{	
	// $enc_str is the output from djEncryptString().
	// $key is the same key as used to encrypt with.
	
	$key_chars = str_split($key);
	$enc_data = explode('-', $enc_str);
	$key_coords = $enc_data[0];
	$key_coord_lengths = str_split($enc_data[1]);
	
	$s = '';
	foreach ($key_coord_lengths as $c) {
		$s .= $key_chars[(int)substr($key_coords, 0, (int)$c)];
		$key_coords = substr($key_coords, (int)$c);
	}

	return $s;
}

PHP example usage:
// Create a random key to be used by both functions.
$key = str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890. ');

$original_string = 'This is a random string.';
$encrypted_string = djEncryptString($original_string, $key);

echo 'Key used: '. $key .'<br><br>';
echo 'Original string: '. $original_string .'<br><br>';
echo 'Encrypted string: '. $encrypted_string .'<br><br>';
echo 'Decrypted string: '. djDecryptString($encrypted_string, $key);

The above testing code produces output similar to this:
Key used: L2RZ6oMfcCjpWIuPxKsT5rSzteq.Dmln0O17d8YUX FgV4yNBiEvbJH3Q9AakhwG

Original string: This is a random string.

Encrypted string: 19614918414918415941215931365294118242149314327-222222222222221222222222

Decrypted string: This is a random string.

Demo

If you keep the contents of $key to a minimum of all alphanumeric characters (a-z, A-Z, 0-9) plus any special characters your $string may have, then just encrypting "Hi!" will have 633 = 250047 combinations.


©2007-2018 https://thronic.com
Π