]> git.mxchange.org Git - friendica.git/blob - include/crypto.php
Bugfix for pull request #2147 (Fix for issue #2122)
[friendica.git] / include / crypto.php
1 <?php
2
3 require_once('library/ASNValue.class.php');
4 require_once('library/asn1.php');
5
6 // supported algorithms are 'sha256', 'sha1'
7
8 function rsa_sign($data,$key,$alg = 'sha256') {
9
10         $sig = '';
11         if (version_compare(PHP_VERSION, '5.3.0', '>=') || $alg === 'sha1') {
12                 openssl_sign($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
13     }
14     else {
15                 if(strlen($key) < 1024 || extension_loaded('gmp')) {
16                         require_once('library/phpsec/Crypt/RSA.php');
17                         $rsa = new CRYPT_RSA();
18                         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
19                         $rsa->setHash($alg);
20                         $rsa->loadKey($key);
21                         $sig = $rsa->sign($data);
22                 }
23                 else {
24                         logger('rsa_sign: insecure algorithm used. Please upgrade PHP to 5.3');
25                         openssl_private_encrypt(hex2bin('3031300d060960864801650304020105000420') . hash('sha256',$data,true), $sig, $key);
26                 }
27         }
28         return $sig;
29 }
30
31 function rsa_verify($data,$sig,$key,$alg = 'sha256') {
32
33         if (version_compare(PHP_VERSION, '5.3.0', '>=') || $alg === 'sha1') {
34                 $verify = openssl_verify($data,$sig,$key,(($alg == 'sha1') ? OPENSSL_ALGO_SHA1 : $alg));
35     }
36     else {
37                 if(strlen($key) <= 300 || extension_loaded('gmp')) {
38                         require_once('library/phpsec/Crypt/RSA.php');
39                         $rsa = new CRYPT_RSA();
40                         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
41                         $rsa->setHash($alg);
42                         $rsa->loadKey($key);
43                         $verify = $rsa->verify($data,$sig);
44                 }
45                 else {
46                         // fallback sha256 verify for PHP < 5.3 and large key lengths
47                         $rawsig = '';
48                 openssl_public_decrypt($sig,$rawsig,$key);
49                 $verify = (($rawsig && substr($rawsig,-32) === hash('sha256',$data,true)) ? true : false);
50         }
51         }
52         return $verify;
53 }
54
55
56 function DerToPem($Der, $Private=false)
57 {
58     //Encode:
59     $Der = base64_encode($Der);
60     //Split lines:
61     $lines = str_split($Der, 65);
62     $body = implode("\n", $lines);
63     //Get title:
64     $title = $Private? 'RSA PRIVATE KEY' : 'PUBLIC KEY';
65     //Add wrapping:
66     $result = "-----BEGIN {$title}-----\n";
67     $result .= $body . "\n";
68     $result .= "-----END {$title}-----\n";
69  
70     return $result;
71 }
72
73 function DerToRsa($Der)
74 {
75     //Encode:
76     $Der = base64_encode($Der);
77     //Split lines:
78     $lines = str_split($Der, 64);
79     $body = implode("\n", $lines);
80     //Get title:
81     $title = 'RSA PUBLIC KEY';
82     //Add wrapping:
83     $result = "-----BEGIN {$title}-----\n";
84     $result .= $body . "\n";
85     $result .= "-----END {$title}-----\n";
86  
87     return $result;
88 }
89
90
91 function pkcs8_encode($Modulus,$PublicExponent) {
92         //Encode key sequence
93         $modulus = new ASNValue(ASNValue::TAG_INTEGER);
94         $modulus->SetIntBuffer($Modulus);
95         $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
96         $publicExponent->SetIntBuffer($PublicExponent);
97         $keySequenceItems = array($modulus, $publicExponent);
98         $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
99         $keySequence->SetSequence($keySequenceItems);
100         //Encode bit string
101         $bitStringValue = $keySequence->Encode();
102         $bitStringValue = chr(0x00) . $bitStringValue; //Add unused bits byte
103         $bitString = new ASNValue(ASNValue::TAG_BITSTRING);
104         $bitString->Value = $bitStringValue;
105         //Encode body
106         $bodyValue = "\x30\x0d\x06\x09\x2a\x86\x48\x86\xf7\x0d\x01\x01\x01\x05\x00" . $bitString->Encode();
107         $body = new ASNValue(ASNValue::TAG_SEQUENCE);
108         $body->Value = $bodyValue;
109         //Get DER encoded public key:
110         $PublicDER = $body->Encode();
111         return $PublicDER;
112 }
113
114
115 function pkcs1_encode($Modulus,$PublicExponent) {
116         //Encode key sequence
117         $modulus = new ASNValue(ASNValue::TAG_INTEGER);
118         $modulus->SetIntBuffer($Modulus);
119         $publicExponent = new ASNValue(ASNValue::TAG_INTEGER);
120         $publicExponent->SetIntBuffer($PublicExponent);
121         $keySequenceItems = array($modulus, $publicExponent);
122         $keySequence = new ASNValue(ASNValue::TAG_SEQUENCE);
123         $keySequence->SetSequence($keySequenceItems);
124         //Encode bit string
125         $bitStringValue = $keySequence->Encode();
126         return $bitStringValue;
127 }
128
129
130 function metopem($m,$e) {
131         $der = pkcs8_encode($m,$e);
132         $key = DerToPem($der,false);
133         return $key;
134 }       
135
136
137 function pubrsatome($key,&$m,&$e) {
138         require_once('library/asn1.php');
139         require_once('include/salmon.php');
140
141         $lines = explode("\n",$key);
142         unset($lines[0]);
143         unset($lines[count($lines)]);
144         $x = base64_decode(implode('',$lines));
145
146         $r = ASN_BASE::parseASNString($x);
147
148         $m = base64url_decode($r[0]->asnData[0]->asnData);
149         $e = base64url_decode($r[0]->asnData[1]->asnData);
150 }
151
152
153 function rsatopem($key) {
154         pubrsatome($key,$m,$e);
155         return(metopem($m,$e));
156 }
157
158 function pemtorsa($key) {
159         pemtome($key,$m,$e);
160         return(metorsa($m,$e));
161 }
162
163 function pemtome($key,&$m,&$e) {
164         require_once('include/salmon.php');
165         $lines = explode("\n",$key);
166         unset($lines[0]);
167         unset($lines[count($lines)]);
168         $x = base64_decode(implode('',$lines));
169
170         $r = ASN_BASE::parseASNString($x);
171
172         $m = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[0]->asnData);
173         $e = base64url_decode($r[0]->asnData[1]->asnData[0]->asnData[1]->asnData);
174 }
175
176 function metorsa($m,$e) {
177         $der = pkcs1_encode($m,$e);
178         $key = DerToRsa($der);
179         return $key;
180 }       
181
182 function salmon_key($pubkey) {
183         pemtome($pubkey,$m,$e);
184         return 'RSA' . '.' . base64url_encode($m,true) . '.' . base64url_encode($e,true) ;
185 }
186
187
188
189 if(! function_exists('aes_decrypt')) {
190 // DEPRECATED IN 3.4.1
191 function aes_decrypt($val,$ky)
192 {
193     $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
194     for($a=0;$a<strlen($ky);$a++)
195       $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
196     $mode = MCRYPT_MODE_ECB;
197     $enc = MCRYPT_RIJNDAEL_128;
198     $dec = @mcrypt_decrypt($enc, $key, $val, $mode, @mcrypt_create_iv( @mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM ) );
199     return rtrim($dec,(( ord(substr($dec,strlen($dec)-1,1))>=0 and ord(substr($dec, strlen($dec)-1,1))<=16)? chr(ord( substr($dec,strlen($dec)-1,1))):null));
200 }}
201
202
203 if(! function_exists('aes_encrypt')) {
204 // DEPRECATED IN 3.4.1
205 function aes_encrypt($val,$ky)
206 {
207     $key="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
208     for($a=0;$a<strlen($ky);$a++)
209       $key[$a%16]=chr(ord($key[$a%16]) ^ ord($ky[$a]));
210     $mode=MCRYPT_MODE_ECB;
211     $enc=MCRYPT_RIJNDAEL_128;
212     $val=str_pad($val, (16*(floor(strlen($val) / 16)+(strlen($val) % 16==0?2:1))), chr(16-(strlen($val) % 16)));
213     return mcrypt_encrypt($enc, $key, $val, $mode, mcrypt_create_iv( mcrypt_get_iv_size($enc, $mode), MCRYPT_DEV_URANDOM));
214 }} 
215
216 function pkcs5_pad ($text, $blocksize)
217 {
218     $pad = $blocksize - (strlen($text) % $blocksize);
219     return $text . str_repeat(chr($pad), $pad);
220 }
221
222 function pkcs5_unpad($text)
223 {
224     $pad = ord($text{strlen($text)-1});
225     if ($pad > strlen($text)) return false;
226     if (strspn($text, chr($pad), strlen($text) - $pad) != $pad) return false;
227     return substr($text, 0, -1 * $pad);
228
229
230
231 function new_keypair($bits) {
232
233         $openssl_options = array(
234                 'digest_alg'       => 'sha1',
235                 'private_key_bits' => $bits,
236                 'encrypt_key'      => false 
237         );
238
239         $conf = get_config('system','openssl_conf_file');
240         if($conf)
241                 $openssl_options['config'] = $conf;
242         
243         $result = openssl_pkey_new($openssl_options);
244
245         if(empty($result)) {
246                 logger('new_keypair: failed');
247                 return false;
248         }
249
250         // Get private key
251
252         $response = array('prvkey' => '', 'pubkey' => '');
253
254         openssl_pkey_export($result, $response['prvkey']);
255
256         // Get public key
257         $pkey = openssl_pkey_get_details($result);
258         $response['pubkey'] = $pkey["key"];
259
260         return $response;
261
262 }
263