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