Use PHP mycrypt library to encrypt and decrypt data

Here’s how you can encrypt a json string using the PHP’s mcrypt library. Pre-requisite

sudo apt-get install php5-mcrypt
$private_key = '-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQD0wSUI+wSKOqvpm79kNslxOw3DOLi76AEqsB5w/mQETdpOU0hT
GHKNBBIO3ZVzTks3FUs+NCfHuG3bUYW3ss8OjV8fJUzeq9Xt9HgMHH51nBvBQnNJ
14q7KB1onH5oBnLpIA3Yo0Xc9F0CHTiRYZzObhijPdTycTAn5RYg3gzWQwIDAQAB
AoGBANuTZ5Fd+V21c0NaGeNjD2fJDfjFK15QrrNIW5cNclc2LRK1vp3lwebm7vht
LEXMyMe7D8zXZ5TSzaPDyE3cWco4P+8Cm5nXy7D4I1YKQq+U5jwaTleWrUka9VnK
3znT9FXtihY5jxKqbA9ilmPBnrI/Yy2JDuqKpB+gO9bmjAdRAkEA+9XDsJl9hqXP
32ZBwrOTkNxWKMHbRdTwPNP/W4zPK/t6Srdtexucy63O99+vW9VS7wezDU4il/8Y
Q8mrIh0b+wJBAPjNZvUCZVu6xnTgRBft1qaqCHtSypj8hHbSLMUOXbKYYG0XY7Vj
rQ/S1srX9wFHirEcR/IWMLCseikbEhRzlFkCQQDG2FPKxndB8PzAtXopJSfYUtHJ
HsBnVCpYrT/M5tLSNJ+sDUdp1DSq8lMgj0NkLH1udVLgp5hTEb30EHGK3xcvAkEA
7ecqTZlO5hmAbn2LXv4zRAZOOe3+f67l0uBBouOLwJxnh6jX1LhM4VaPwEIlk/me
qqAKQ3focudZoDicXyXtcQJAdk8uZJUtf04/mbms9nX90wXTj3KgbDtE91/vFzih
0LQLOrheAcDbGDaENf3AqkFZ+6nXytmu3CnbWK7wUA62LA==
-----END RSA PRIVATE KEY-----';

$public_key  = '-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0wSUI+wSKOqvpm79kNslxOw3D
OLi76AEqsB5w/mQETdpOU0hTGHKNBBIO3ZVzTks3FUs+NCfHuG3bUYW3ss8OjV8f
JUzeq9Xt9HgMHH51nBvBQnNJ14q7KB1onH5oBnLpIA3Yo0Xc9F0CHTiRYZzObhij
PdTycTAn5RYg3gzWQwIDAQAB
-----END PUBLIC KEY-----';

if ($_SERVER['REQUEST_METHOD'] != "POST") {
  exit('{"ReturnType":"Error", "ReturnCode":"-1", "ReturnMessage":"Invalid API Call."}');
}
else {
  if(array_key_exists('', $_POST)) {
    if(empty($_POST['json_content'])) {
      exit('{"ReturnType":"Error", "ReturnCode":"101", "ReturnMessage":"json_content is required to encrypt license."}');
    }
    $arr_license = json_decode($_POST['json_content'], true);
    if(empty($arr_license))
      exit('{"ReturnType":"Error", "ReturnCode":"101", "ReturnMessage":"json_content must be a valid JSON string."}');
    $encr_text = ng_encrypt($arr_license);
    $arr_response = array();
    $arr_response['ReturnType'] = 'Success';
    $arr_response['ReturnCode'] = '100';
    $arr_response['ReturnMessage'] = 'Successfully completed the encryption.';
    $arr_response['EncrText'] = $encr_text;
    exit(json_encode($arr_response));
  }
  else {
    exit('{"ReturnType":"Error", "ReturnCode":"101", "ReturnMessage":"json_content is required to encrypt license."}');
  }
}

function ng_sign($data) {
  global $private_key;
  
  // sort it alpha for each key in each array under the data
  $data["signature"] = "";
  $data = presort($data);
  // generate signature
  $encoded = trim(json_encode($data));
    //$data["signature"] = hash("sha512", $encoded); //--Signature for FileFormatVersion = 1
  openssl_sign($encoded, $signature, openssl_get_privatekey($private_key));
  openssl_free_key($private_key);
  $data["signature"] = base64_encode($signature);
  // json encode the structure
  return trim(json_encode($data));
}

function ng_encrypt($data) {
  global $public_key;
  try {
    // encrypt the data
    $text = @mcrypt_encrypt(MCRYPT_RIJNDAEL_128, hash("sha512", $public_key), ng_sign($data), MCRYPT_MODE_CBC);
    // base 64 encode so that it's copy/paste able if the file is opened.
    $text = base64_encode($text);
  }
  catch(Exception $e){
    throw $e;
    error_log("ng_encrypt() : $e");
  }
  return $text;
}

function ng_verify($data) {
  // preserve data for signature verification
  $data = trim($data);
  $original_data = $data;
  // decode the stream
  $data = json_decode($data, 1);
  // expecting dictionary/array data
  if (!is_array($data)) {
      error_log('ng_verify() -> expected array');
  }
  // validate the license file against the signature for modification.
  if (array_key_exists("signature", $data)) {
  $signature = $data["signature"];
  $original_data = str_replace($signature, "", $original_data);
  if (hash("sha512", $original_data) != $signature) {
    error_log('ng_verify() -> sha512 mismatch');
  }
  }
  else {
    // license not signed
    error_log('ng_verify() -> license not signed');
  }
  return $data;
}

function ng_decrypt($text) {
  global $public_key;
  if (!is_string($text)) {
    error_log('ng_decrypt() -> license not a string');
  }
  try {
    // decode the contents
    $text = base64_decode($text);
    // decrypt the contents
    $data = @mcrypt_decrypt(MCRYPT_RIJNDAEL_128, hash("sha512", $public_key), $text, MCRYPT_MODE_CBC);
    // verify the contents and signature
    $data = ng_verify($data);
  }
  catch(Exception $e){
      error_log('ng_decrypt() -> operation failed');
  }
  return $data;
}

function presort(&$data) {
  if (is_array($data)) {
    foreach(array_keys($data) as $key) {
      $object[$key] = presort($data[$key]);
    }
    ksort($data);
  }
  return $data;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s