]> git.mxchange.org Git - friendica.git/blob - src/Util/Crypto.php
adee8cd60e4adb6a3814318b06810aab91fabf60
[friendica.git] / src / Util / Crypto.php
1 <?php
2 /**
3  * @file src/Util/Crypto.php
4  */
5 namespace Friendica\Util;
6
7 use Friendica\Core\Config;
8 use ASN_BASE;
9 use ASNValue;
10
11 require_once 'library/ASNValue.class.php';
12 require_once 'library/asn1.php';
13
14 /**
15  * @brief Crypto class
16  */
17 class Crypto
18 {
19         // supported algorithms are 'sha256', 'sha1'
20         /**
21          * @param string $data data
22          * @param string $key  key
23          * @param string $alg  algorithm
24          * @return string
25          */
26         public static function rsaSign($data, $key, $alg = 'sha256')
27         {
28                 openssl_sign($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
29                 return $sig;
30         }
31
32         /**
33          * @param string $data data
34          * @param string $sig  signature
35          * @param string $key  key
36          * @param string $alg  algorithm
37          * @return boolean
38          */
39         public static function rsaVerify($data, $sig, $key, $alg = 'sha256')
40         {
41                 return openssl_verify($data, $sig, $key, (($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
42         }
43
44         /**
45          * @param string $Der     der formatted string
46          * @param string $Private key type optional, default false
47          * @return string
48          */
49         private static function DerToPem($Der, $Private = false)
50         {
51                 //Encode:
52                 $Der = base64_encode($Der);
53                 //Split lines:
54                 $lines = str_split($Der, 65);
55                 $body = implode("\n", $lines);
56                 //Get title:
57                 $title = $Private ? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
58                 //Add wrapping:
59                 $result = "-----BEGIN {$title}-----\n";
60                 $result .= $body . "\n";
61                 $result .= "-----END {$title}-----\n";
62
63                 return $result;
64         }
65
66         /**
67          * @param string $Der der formatted string
68          * @return string
69          */
70         private static function DerToRsa($Der)
71         {
72                 //Encode:
73                 $Der = base64_encode($Der);
74                 //Split lines:
75                 $lines = str_split($Der, 64);
76                 $body = implode("\n", $lines);
77                 //Get title:
78                 $title = 'RSA PUBLIC KEY';
79                 //Add wrapping:
80                 $result = "-----BEGIN {$title}-----\n";
81                 $result .= $body . "\n";
82                 $result .= "-----END {$title}-----\n";
83
84                 return $result;
85         }
86
87         /**
88          * @param string $Modulus        modulo
89          * @param string $PublicExponent exponent
90          * @return string
91          */
92         private static function pkcs8Encode($Modulus, $PublicExponent)
93         {
94                 //Encode key sequence
95                 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
96                 $modulus->SetIntBuffer($Modulus);
97                 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
98                 $publicExponent->SetIntBuffer($PublicExponent);
99                 $keySequenceItems = array($modulus, $publicExponent);
100                 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
101                 $keySequence->SetSequence($keySequenceItems);
102                 //Encode bit string
103                 $bitStringValue = $keySequence->Encode();
104                 $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
105                 $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
106                 $bitString->Value = $bitStringValue;
107                 //Encode body
108                 $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
109                 $body = new ASNValue(ASNValue::TAG_SEQUENCE);
110                 $body->Value = $bodyValue;
111                 //Get DER encoded public key:
112                 $PublicDER = $body->Encode();
113                 return $PublicDER;
114         }
115
116         /**
117          * @param string $Modulus        modulo
118          * @param string $PublicExponent exponent
119          * @return string
120          */
121         private static function pkcs1Encode($Modulus, $PublicExponent)
122         {
123                 //Encode key sequence
124                 $modulus = new ASNValue(ASNValue::TAG_INTEGER);
125                 $modulus->SetIntBuffer($Modulus);
126                 $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
127                 $publicExponent->SetIntBuffer($PublicExponent);
128                 $keySequenceItems = array($modulus, $publicExponent);
129                 $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
130                 $keySequence->SetSequence($keySequenceItems);
131                 //Encode bit string
132                 $bitStringValue = $keySequence->Encode();
133                 return $bitStringValue;
134         }
135
136         /**
137          * @param string $m modulo
138          * @param string $e exponent
139          * @return string
140          */
141         public static function meToPem($m, $e)
142         {
143                 $der = self::pkcs8Encode($m, $e);
144                 $key = self::DerToPem($der, false);
145                 return $key;
146         }
147
148         /**
149          * @param string $key key
150          * @param string $m   modulo reference
151          * @param object $e   exponent reference
152          * @return void
153          */
154         private static function pubRsaToMe($key, &$m, &$e)
155         {
156                 $lines = explode("\n", $key);
157                 unset($lines[0]);
158                 unset($lines[count($lines)]);
159                 $x = base64_decode(implode('', $lines));
160
161                 $r = ASN_BASE::parseASNString($x);
162
163                 $m = base64url_decode($r[0]->asnData[0]->asnData);
164                 $e = base64url_decode($r[0]->asnData[1]->asnData);
165         }
166
167         /**
168          * @param string $key key
169          * @return string
170          */
171         public static function rsaToPem($key)
172         {
173                 self::pubRsaToMe($key, $m, $e);
174                 return self::meToPem($m, $e);
175         }
176
177         /**
178          * @param string $key key
179          * @return string
180          */
181         private static function pemToRsa($key)
182         {
183                 self::pemToMe($key, $m, $e);
184                 return self::meToRsa($m, $e);
185         }
186
187         /**
188          * @param string $key key
189          * @param string $m   modulo reference
190          * @param string $e   exponent reference
191          * @return void
192          */
193         public static function pemToMe($key, &$m, &$e)
194         {
195                 $lines = explode("\n", $key);
196                 unset($lines[0]);
197                 unset($lines[count($lines)]);
198                 $x = base64_decode(implode('', $lines));
199
200                 $r = ASN_BASE::parseASNString($x);
201
202                 $m = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
203                 $e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
204         }
205
206         /**
207          * @param string $m modulo
208          * @param string $e exponent
209          * @return string
210          */
211         private static function meToRsa($m, $e)
212         {
213                 $der = self::pkcs1Encode($m, $e);
214                 $key = self::DerToRsa($der);
215                 return $key;
216         }
217
218         /**
219          * @param integer $bits number of bits
220          * @return mixed
221          */
222         public static function newKeypair($bits)
223         {
224                 $openssl_options = array(
225                         'digest_alg'       => 'sha1',
226                         'private_key_bits' => $bits,
227                         'encrypt_key'      => false
228                 );
229
230                 $conf = Config::get('system', 'openssl_conf_file');
231                 if ($conf) {
232                         $openssl_options['config'] = $conf;
233                 }
234                 $result = openssl_pkey_new($openssl_options);
235
236                 if (empty($result)) {
237                         logger('new_keypair: failed');
238                         return false;
239                 }
240
241                 // Get private key
242                 $response = array('prvkey' => '', 'pubkey' => '');
243
244                 openssl_pkey_export($result, $response['prvkey']);
245
246                 // Get public key
247                 $pkey = openssl_pkey_get_details($result);
248                 $response['pubkey'] = $pkey["key"];
249
250                 return $response;
251         }
252 }