Continued:
[core.git] / framework / main / classes / streams / crypto / class_McryptStream.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Stream\Crypto;
4
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
7 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
8 use Org\Mxchange\CoreFramework\Stream\BaseStream;
9
10 /**
11  * A mcrypt-based encryption stream
12  *
13  * @author              Roland Haeder <webmaster@shipsimu.org>
14  * @version             0.0.0
15  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2019 Core Developer Team
16  * @license             GNU GPL 3.0 or any newer version
17  * @link                http://www.shipsimu.org
18  * @todo                mcrypt will become deprecated, rewrite to OpenSSL
19  *
20  * This program is free software: you can redistribute it and/or modify
21  * it under the terms of the GNU General Public License as published by
22  * the Free Software Foundation, either version 3 of the License, or
23  * (at your option) any later version.
24  *
25  * This program is distributed in the hope that it will be useful,
26  * but WITHOUT ANY WARRANTY; without even the implied warranty of
27  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28  * GNU General Public License for more details.
29  *
30  * You should have received a copy of the GNU General Public License
31  * along with this program. If not, see <http://www.gnu.org/licenses/>.
32  */
33 class McryptStream extends BaseStream implements EncryptableStream {
34         /**
35          * Protected constructor
36          *
37          * @return      void
38          */
39         protected function __construct () {
40                 // Call parent constructor
41                 parent::__construct(__CLASS__);
42         }
43
44         /**
45          * Creates an instance of this node class
46          *
47          * @param       $rngInstance            An RNG instance
48          * @return      $streamInstance         An instance of this node class
49          */
50         public static final function createMcryptStream (RandomNumberGenerator $rngInstance) {
51                 // Get a new instance
52                 $streamInstance = new McryptStream();
53
54                 // Set the RNG instance
55                 $streamInstance->setRngInstance($rngInstance);
56
57                 // Return the instance
58                 return $streamInstance;
59         }
60
61         /**
62          * Encrypt the string with fixed salt
63          *
64          * @param       $str            The unencrypted string
65          * @param       $key            Optional key, if none provided, a random key will be generated
66          * @return      $encrypted      Encrypted string
67          */
68         public function encryptStream ($str, $key = NULL) {
69                 // Debug message
70                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']: key[' . gettype($key) . ']=' . $key);
71
72                 // Init crypto module
73                 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
74                 $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
75
76                 // Generate key, if none provided
77                 if (is_null($key)) {
78                         // None provided
79                         $key = $this->getRngInstance()->generateKey();
80                 } // END - if
81
82                 // Add some "payload" to the string
83                 switch ($this->getRngInstance()->randomNumber(0, 8)) {
84                         case 0:
85                                 $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
86                                 break;
87
88                         case 1:
89                                 $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
90                                 break;
91
92                         case 2:
93                                 $payloadString = crc32($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
94                                 break;
95
96                         case 3:
97                                 $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
98                                 break;
99
100                         case 4:
101                                 $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
102                                 break;
103
104                         case 5:
105                                 $payloadString = md5($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
106                                 break;
107
108                         case 6:
109                                 $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . crc32($this->getRngInstance()->randomString(20));
110                                 break;
111
112                         case 7:
113                                 $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . md5($this->getRngInstance()->randomString(20));
114                                 break;
115
116                         case 8:
117                                 $payloadString = sha1($this->getRngInstance()->randomString(10)) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . base64_encode($str) . EncryptableStream::DATA_PAYLOAD_SEPARATOR . sha1($this->getRngInstance()->randomString(20));
118                                 break;
119                 }
120
121                 // Encrypt the string
122                 $encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $payloadString, MCRYPT_MODE_ECB, $iv);
123
124                 // Return the string
125                 return $encrypted;
126         }
127
128         /**
129          * Decrypt the string with fixed salt
130          *
131          * @param       $encrypted      Encrypted string
132          * @param       $key            Optional key, if none provided, a random key will be generated
133          * @return      $str            The unencrypted string
134          */
135         public function decryptStream ($encrypted, $key = NULL) {
136                 // Init crypto module
137                 $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
138                 $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
139
140                 // Shall we use a default key or custom?
141                 if (is_null($key)) {
142                         // Generate (default) key
143                         $key = $this->getRngInstance()->generateKey();
144                 } // END - if
145
146                 // Decrypt the string
147                 $payloadString = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $encrypted, MCRYPT_MODE_ECB, $iv);
148
149                 // Get the real string out
150                 $strArray = explode(EncryptableStream::DATA_PAYLOAD_SEPARATOR, $payloadString);
151
152                 // Does the element count match?
153                 assert(count($strArray) == 3);
154
155                 // Decode the string
156                 $str = base64_decode($strArray[1]);
157
158                 // Trim trailing nulls away
159                 $str = rtrim($str, "\0");
160
161                 // Return the string
162                 return $str;
163         }
164
165         /**
166          * Streams the data and maybe does something to it
167          *
168          * @param       $data   The data (string mostly) to "stream"
169          * @return      $data   The data (string mostly) to "stream"
170          * @throws      UnsupportedOperationException   If this method is called (which is a mistake)
171          */
172         public function streamData ($data) {
173                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('Unhandled ' . strlen($data) . ' bytes in this stream.');
174                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
175         }
176
177 }