· 6 years ago · Jul 10, 2019, 06:14 PM
1<?php
2
3 /*
4
5 === SafeRequest ===
6 Developed by Justin Garofolo
7 Open source .NET/PHP library to allow encrypted json data to be transferred between client and server.
8 Github: https://github.com/ooojustin/SafeRequest.NET
9 LICENSE: https://github.com/ooojustin/SafeRequest.NET/blob/master/LICENSE.md
10
11 */
12
13 class SafeRequest {
14
15 var $auth;
16 var $enc;
17
18 function __construct($key, $iv = null) {
19 $this->enc = new Encryption($key);
20 if ($iv !== null)
21 if (count($iv) == 16)
22 $this->enc->SetIV($iv);
23 $_POST = $this->getPOST();
24 $this->auth = $this->enc->DecryptString($_POST['authentication_key']);
25 }
26
27 // Decrypts POST data from SafeRequest client.
28 // Example: $_POST = GetPost('secret_key');
29 function getPOST() {
30 $data = file_get_contents('php://input');
31 $data = $this->enc->DecryptString($data);
32 return json_decode($data, true);
33 }
34
35 // Returns encrypted JSON information to SafeRequest client.
36 // Example: output(true, 'my encrypted string here', 'secret_key');
37 function output($status, $message, $extras = null) {
38 $response = array('status' => $status, 'message' => $message);
39 if ($extras != null)
40 array_fuse($response, $extras);
41 $response['authentication_key'] = $this->auth;
42 $data = json_encode($response);
43 $data = $this->enc->EncryptString($data);
44 die($data);
45 }
46
47 }
48
49
50 /* Encryption class to safely communicate with SafeRequest client.
51 Example:
52 $enc = new Encryption('secret_key);
53 $encrypted = $enc->EncryptString('secret message');
54 $decrypted = $enc->DecryptString($encrypted);
55 echo $decrypted; // outputs 'secret message'
56 */
57 class Encryption {
58
59 var $_key;
60 var $_iv;
61
62 function __construct($key) {
63 $this->_key = substr(hash('sha256', $key, true), 0, 32);
64 $this->_iv = $this->bytes_to_string(array(0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0));
65 }
66
67 function EncryptString($plainText) {
68 return base64_encode(openssl_encrypt($plainText, 'aes-256-cbc', $this->_key, OPENSSL_RAW_DATA, $this->_iv));
69 }
70
71 function DecryptString($cipherText) {
72 return openssl_decrypt(base64_decode($cipherText), 'aes-256-cbc', $this->_key, OPENSSL_RAW_DATA, $this->_iv);
73 }
74
75 function SetIV($iv) {
76 $this->_iv = $this->bytes_to_string($iv);
77 }
78
79 function bytes_to_string($bytes) {
80 return implode(array_map("chr", $bytes));
81 }
82
83 }
84
85 // Combines 2 arrays. ($arr2 gets added to the end of $arr1)
86 function array_fuse(&$arr1, $arr2) {
87 foreach ($arr2 as $key => $value)
88 $arr1[$key] = $value;
89 }
90
91?>