Encryption is the process of converting plaintext into ciphertext using algorithms to prevent unauthorized access.
Encryption is divided into two types:
1. Symmetric Key Encryption
2. Asymmetric Encryption (Public Key Encryption)
How Encryption Algorithms Work
An encryption algorithm is a mathematical function that converts plaintext into ciphertext, typically using a key to perform encryption and decryption operations.
1. Encryption Process
The encryption process consists of two steps:
Plaintext Input
: Input the plaintext into the encryption algorithm.
Ciphertext Output
: The encryption algorithm performs a series of complex mathematical operations on the plaintext using the key, and the output is the ciphertext.
The ciphertext is the result produced by the encryption algorithm; it is the plaintext encrypted with a key and is typically unreadable directly.
2. Decryption Process
The decryption process is the reverse of the encryption process and consists of two steps:
Ciphertext Input
: Input the ciphertext into the decryption algorithm.
Plaintext Output
: The decryption algorithm performs a series of complex mathematical operations on the ciphertext using the key, and the output is the plaintext.
3. Security
The security of an encryption algorithm depends on the strength of the key; if the key is strong enough, methods like brute force cannot be used to crack the ciphertext.
4. Applications
Encryption algorithms are widely used in various fields, including network security, data protection, identity verification, etc.
Symmetric Key Encryption
Symmetric key encryption is a method of data encryption that uses the same key for both encryption and decryption. It is usually used for encrypting large amounts of data because it is fast and efficient.
There are two main types of symmetric key encryption: Block Ciphers
and Stream Ciphers
.
1. Block Ciphers
Block ciphers encrypt data in fixed-size blocks (e.g., 64 or 128 bits) using a key. They are widely used in various applications, including network security, database encryption, and file encryption.
Common Block Ciphers include:
Advanced Encryption Standard
(AES): AES is the most widely used block cipher, supporting key lengths of 128, 192, or 256 bits.
Triple DES
(3DES): 3DES is a triple iteration of DES, providing higher security.
International Data Encryption Algorithm
(IDEA): IDEA is a fast and efficient cipher but has been replaced by AES.
2. Stream Ciphers
Stream ciphers typically encrypt data bit by bit or byte by byte in a continuous stream. They are often used in real-time applications such as network transmission and audio/video encryption.
Common Stream Ciphers include:
Rivest Cipher
(RC4): RC4 is the most commonly used stream cipher, known for its speed and efficiency.
Wired Equivalent Privacy
(WEP): WEP is a stream cipher used for wireless local area networks (WLAN), but it has been replaced by WPA and WPA2.
Secure Sockets Layer
(SSL): SSL is a protocol for encrypting network communications, using stream ciphers to protect data.
Example: AES (Advanced Encryption Standard)
function encrypt($data="", $key="") {
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length("aes-256-cbc")); // Dynamic iv (we can also set a static iv)
$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);
Note: If we need to regenerate the same encrypted data on the same plaintext, we must always use the same Salt Key
and IV
. Otherwise, the output will differ.
Asymmetric Encryption (Public Key Encryption):
This uses two different keys: a public key for encryption and a private key for decryption.
We do not use secure key exchange for encryption because it is slower than symmetric encryption, but it is useful for digital signatures and authentication.
Common public key encryption techniques include: RSA
, ECC
(Elliptic Curve Cryptography), Diffie-Hellman
.
Here is an example of the RSA algorithm.
If we do not have the public and private keys, we can generate them from the command line interface.
To generate a private key file in the directory:
openssl genrsa -out privateKey.pem 2048
For the public key:
openssl rsa -in privateKey.pem -pubout
Here, privateKey.pem
and privateKey.pem
are the generated filenames.
The generated public key is the RSA result.
The private key is not the RSA result; additional coding is needed to make it the RSA result.
First, install this package in the Laravel project.
Composer require "phpseclib/phpseclib": "~2.0"
use phpseclib\Crypt\RSA;
// Private key: pem to rsa code
$privateKey = 'set pem file data';
$rsa = new RSA();
$rsa->loadKey($privateKey);
$rsaPrivateKey = $rsa->getPrivateKey();
dd($rsaPrivateKey);
Additionally, if we need to convert the public key from pem to RSA, we can use this code for conversion.
// Public key: pem to rsa.
$publicKey = 'set pem file data';
$rsa = new RSA();
$rsa->loadKey($publicKey);
$rsa->setPublicKey($publicKey);
$rsaPublicKey = $rsa->getPublicKey();
dd($rsaPublicKey);
Let’s look at a real implementation of asymmetric encryption:
When merchants transact with banks, they need to use public key encryption and private key decryption to protect data security.
The bank provides the merchant with a public key, which the merchant shares with the bank. The merchant uses the private key to encrypt transaction request data and sends the encrypted data to the bank. The bank uses the public key provided by the merchant to decrypt the data.
After processing the data, the bank uses the private key to send an encrypted response to the merchant. The merchant uses the bank’s public key to decrypt the response to obtain the plain reply.
Additionally, the bank requires the merchant to send a signature with each transaction request. The merchant uses the private key and PKCS1Padding
algorithm to decrypt the decoded sensitive data. The signature is generated using the SHA256withRSA
signing algorithm.
Now an API call will be made to initiate a transaction on the bank side.
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);
$err = curl_error($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$curlErrorNo = curl_errno($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;
}
}
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);
Considerations When Choosing an Encryption Algorithm:
1. Required level of security.
2. Speed of encryption and decryption.
3. Complexity of key management.
4. Resource limitations.
Where to Use Encryption Algorithms
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