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