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