In this post I will show you a method I created to encrypt and decrypt a string using an asymmetric encryption method.
The method shown takes into account that you already possess your key pairs.
I created this method so I could implement encryption between an Android app and a web server.
Asymmetric encryption has a block size limit. I found the block size for my example implementation is 64 bits. There is an 11 bits that is used reserved for padding. This means that max characters in a string to encrypt is 53 bits.
This implementation takes care of creating cipher blocks of 53 bits into an array for encryption and also for decryption.
Code
This is the encryption function used
function encryptString($public_key, $encryptedText){
$encrypted_arr = str_split($encryptedText, 53);
$encryptedStr = "";
for($i = 0; $i < sizeof($encrypted_arr); $i++){
openssl_public_encrypt($encrypted_arr[$i], $encrypted, $public_key);
if($i != 0){
$encryptedStr .= ":";
}
$encryptedStr .= base64_encode($encrypted);
}
return $encryptedStr;
}
This is the decryption function used
function decryptString($private_key, $message){
$dataArr = explode(":", $message);
$str = "";
for($i = 0; $i < count($dataArr); $i++){
openssl_private_decrypt(base64_decode($dataArr[$i]), $test_decrypted, $private_key);
$str .= $test_decrypted;
}
$str = mb_convert_encoding($str, "UTF-8");
return $str;
}
Below is a sample of how to implement. I put these functions inside a class named MyUtils.
<?php
class MyUtils {
function encryptString($public_key, $encryptedText){
....
}
function decryptString($private_key, $message){
.....
}
}
?>
$myUtils = new MyUtils();
$new_test_str = "{'id':45,'message':'Peter Peter Pumpkin eater','host':'localhost'}";
echo "<br /><br /><br />";
echo "This is the text: $new_test_str";
echo "<br /><br /><br />";
$encrpyted_text = $myUtils->encryptPost($myVars, $new_test_str);
echo "<br /><br /><br />";
echo "This is the encrypted text: $encrpyted_text";
$decrypted = $myUtils->decryptString($myVars, $encrpyted_text);
echo "<br /><br /><br />";
echo "This is the decrypted text: $decrypted";
//if you want to access it as a json array
$str = json_decode($decrypted, true);
$message = $json['message'];
echo "This is the decrypted text: $message";
Leave a Reply