Understanding Encryption: Symmetric and Asymmetric Algorithms with Code Examples
This article explains the fundamentals of encryption, covering symmetric and asymmetric key methods, algorithm mechanics, security considerations, real‑world applications, and provides PHP code samples for AES, RSA key generation, and secure API communication.
Encryption Overview
Encryption is the process of converting plaintext into ciphertext using algorithms to prevent unauthorized access.
Types of Encryption
1. Symmetric key encryption
2. Asymmetric encryption (public‑key encryption)
How Encryption Algorithms Work
Encryption algorithms are mathematical functions that transform plaintext into ciphertext, typically using a key for both encryption and decryption.
1. Encryption Process
The encryption process consists of two steps:
Plaintext input : The plaintext is fed into the encryption algorithm.
Ciphertext output : The algorithm applies complex mathematical operations with the key and produces ciphertext.
Ciphertext is the encrypted result, unreadable without the key.
2. Decryption Process
The decryption process is the reverse of encryption and also has two steps:
Ciphertext input : Ciphertext is fed into the decryption algorithm.
Plaintext output : The algorithm uses the key to recover the original plaintext.
3. Security
The security of an encryption algorithm depends on the strength of the key; a sufficiently strong key resists brute‑force attacks.
4. Applications
Encryption algorithms are widely used in network security, data protection, identity authentication, and more.
Symmetric Key Encryption
Symmetric encryption uses the same key for both encryption and decryption and is suitable for large volumes of data due to its speed and efficiency.
There are two main types of symmetric ciphers: Block cipher and Stream cipher .
1. Block Ciphers
Block ciphers encrypt fixed‑size blocks (e.g., 64 or 128 bits) and are used in network security, database encryption, and file encryption.
Common block ciphers include:
Advanced Encryption Standard (AES): supports 128, 192, or 256‑bit keys.
Triple DES (3DES): a three‑iteration version of DES offering higher security.
International Data Encryption Algorithm (IDEA): fast and effective but largely superseded by AES.
2. Stream Ciphers
Stream ciphers encrypt data bit‑by‑bit or byte‑by‑byte in a continuous stream, often used for real‑time applications such as network transmission and audio/video encryption.
Common stream ciphers include:
RC4 : the most widely used stream cipher, known for speed.
WEP : a stream cipher for wireless LANs, now replaced by WPA/WPA2.
SSL : a protocol that uses stream ciphers to protect network communication.
Example: AES (Advanced Encryption Standard)
<code>function encrypt($data="", $key="") {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc"));
$encrypted = openssl_encrypt($data, "aes-256-cbc", $key, 0, $iv);
return base64_encode($iv . '!!' . $encrypted);
}
function decrypt($data="", $key="") {
list($iv, $encryptedData) = explode('!!', base64_decode($data), 2);
return openssl_decrypt($encryptedData, "aes-256-cbc", $key, 0, $iv);
}
$plainData = [
'email' => '[email protected]',
'password' => 'codeOn@Vscode2024';
];
$saltKey = "asdckd44dbc228e16c2888436d17a";
$encryptedData = encrypt(json_encode($plainData), $saltKey);
echo $encryptedData;
$decryptedData = decrypt($encryptedData, $saltKey);
print_r($decryptedData);
</code>Note: To reproduce the same ciphertext for identical plaintext, the same Salt Key and IV must be used.
Asymmetric Encryption (Public‑Key Encryption)
Uses a pair of keys: a public key for encryption and a private key for decryption. Although slower than symmetric encryption, it is useful for digital signatures and authentication.
Common public‑key algorithms: RSA , ECC (Elliptic Curve Cryptography), and Diffie‑Hellman .
Generating RSA Keys
Generate a private key:
<code>openssl genrsa -out privateKey.pem 2048
</code>Extract the public key:
<code>openssl rsa -in privateKey.pem -pubout
</code>PHP Implementation with phpseclib
Install the library:
<code>Composer require "phpseclib/phpseclib": "~2.0"
</code>Load a PEM private key and obtain an RSA private key:
<code>use phpseclib\Crypt\RSA;
$privateKey = '...pem file data...';
$rsa = new RSA();
$rsa->loadKey($privateKey);
$rsaPrivateKey = $rsa->getPrivateKey();
dd($rsaPrivateKey);
</code>Convert a PEM public key to RSA:
<code>$publicKey = '...pem file data...';
$rsa = new RSA();
$rsa->loadKey($publicKey);
$rsa->setPublicKey($publicKey);
$rsaPublicKey = $rsa->getPublicKey();
dd($rsaPublicKey);
</code>Real‑World Asymmetric Encryption Example
In merchant‑bank transactions, the merchant encrypts request data with the bank’s public key and signs it with its private key; the bank decrypts with its private key and verifies the signature.
Sample PHP functions for signing, encrypting, decrypting, and making HTTP POST requests are provided below.
<code>public function signatureGenerate($data){
$private_key = "-----Your RSA Private Key-----";
openssl_sign(json_encode($data), $signature, $private_key, OPENSSL_ALGO_SHA256);
return base64_encode($signature);
}
public function encryptDataWithPublicKey($data){
$public_key = "-----Your Public Key-----";
openssl_public_encrypt(json_encode($data), $encryptedData, $public_key, OPENSSL_PKCS1_PADDING);
return base64_encode($encryptedData);
}
public function decryptDataWithPrivateKey($cryptText){
$private_key = "-----Your RSA Private Key-----";
openssl_private_decrypt(base64_decode($cryptText), $plainText, $private_key, OPENSSL_PKCS1_PADDING);
return json_decode($plainText, true);
}
public function HttpPostMethod($postURL, $postData, $authToken = null){
try{
$curl = curl_init($postURL);
$postData = json_encode($postData);
$header = array('Content-Type:application/json');
if($authToken){
$header[] = 'token:' . $authToken;
}
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$resultdata = curl_exec($curl);
$ResultArray = json_decode($resultdata, true);
curl_close($curl);
return $ResultArray;
} catch (\Exception $exception) {
echo 'Unable to connect to the bank, please try again later';
exit;
}
}
function initTransaction($merchantId, $merchantAccountNumber, $orderId){
$postUrl = 'api.your-bank.com/api/payment/initialize';
$plainData = array('merchant_id' => $merchantId, 'order_id' => $orderId);
$postData = array(
'account_number' => $merchantAccountNumber,
'sensitiveData' => $this->encryptDataWithPublicKey($sensitiveData),
'signature' => $this->signatureGenerate($sensitiveData)
);
return $this->HttpPostMethod($postUrl, $postData);
}
$encryptedResponse = $this->initTransaction('MER1234','ACC12345','ORD123456');
$plainResponse = $this->decryptDataWithPrivateKey($encryptedResponse['sensitiveData']);
dd($plainResponse);
</code>Considerations When Choosing an Encryption Algorithm
1. Required security level.
2. Encryption and decryption speed.
3. Complexity of key management.
4. Resource constraints.
Typical Use Cases for Encryption
1. Secure communications (e.g., email, VPN).
2. Data storage (e.g., databases, file systems).
3. Financial transactions (e.g., online banking).
4. Password protection.
5. Digital signatures.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.