]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
30da63c364ad6d2b725d3c73d7b28c325c4d8280
[quix0rs-gnu-social.git] / plugins / OStatus / classes / Magicsig.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * A sample module to show best practices for StatusNet plugins
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @package   StatusNet
24  * @author    James Walker <james@status.net>
25  * @copyright 2010 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
27  * @link      http://status.net/
28  */
29
30 require_once 'Crypt/RSA.php';
31
32 class Magicsig extends Memcached_DataObject
33 {
34
35     const PUBLICKEYREL = 'magic-public-key';
36     
37     public $__table = 'magicsig';
38
39     public $user_id;
40     public $keypair;
41     public $alg;
42     
43     private $_rsa;
44
45     public function __construct($alg = 'RSA-SHA256')
46     {
47         $this->alg = $alg;
48     }
49     
50     public /*static*/ function staticGet($k, $v=null)
51     {
52         $obj =  parent::staticGet(__CLASS__, $k, $v);
53         if (!empty($obj)) {
54             return Magicsig::fromString($obj->keypair);
55         }
56
57         return $obj;
58     }
59
60
61     function table()
62     {
63         return array(
64             'user_id' => DB_DATAOBJECT_INT,
65             'keypair' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
66             'alg'     => DB_DATAOBJECT_STR
67         );
68     }
69
70     static function schemaDef()
71     {
72         return array(new ColumnDef('user_id', 'integer',
73                                    null, true, 'PRI'),
74                      new ColumnDef('keypair', 'varchar',
75                                    255, false),
76                      new ColumnDef('alg', 'varchar',
77                                    64, false));
78     }
79
80
81     function keys()
82     {
83         return array_keys($this->keyTypes());
84     }
85
86     function keyTypes()
87     {
88         return array('user_id' => 'K');
89     }
90
91     function sequenceKey() {
92         return array(false, false, false);
93     }
94
95     function insert()
96     {
97         $this->keypair = $this->toString();
98
99         return parent::insert();
100     }
101
102     public function generate($user_id, $key_length = 512)
103     {
104         PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
105
106         $keypair = new Crypt_RSA_KeyPair($key_length);
107         $params['public_key'] = $keypair->getPublicKey();
108         $params['private_key'] = $keypair->getPrivateKey();
109
110         $this->_rsa = new Crypt_RSA($params);
111         PEAR::popErrorHandling();
112
113         $this->user_id = $user_id;
114         $this->insert();
115     }
116
117
118     public function toString($full_pair = true)
119     {
120         $public_key = $this->_rsa->_public_key;
121         $private_key = $this->_rsa->_private_key;
122
123         $mod = base64_url_encode($public_key->getModulus());
124         $exp = base64_url_encode($public_key->getExponent());
125         $private_exp = '';
126         if ($full_pair && $private_key->getExponent()) {
127             $private_exp = '.' . base64_url_encode($private_key->getExponent());
128         }
129
130         return 'RSA.' . $mod . '.' . $exp . $private_exp; 
131     }
132     
133     public static function fromString($text)
134     {
135         PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
136
137         $magic_sig = new Magicsig();
138         
139         // remove whitespace
140         $text = preg_replace('/\s+/', '', $text);
141
142         // parse components
143         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
144             return false;
145         }
146         
147         $mod = base64_url_decode($matches[1]);
148         $exp = base64_url_decode($matches[2]);
149         if ($matches[4]) {
150             $private_exp = base64_url_decode($matches[4]);
151         }
152
153         $params['public_key'] = new Crypt_RSA_KEY($mod, $exp, 'public');
154         if ($params['public_key']->isError()) {
155             $error = $params['public_key']->getLastError();
156             common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
157             return false;
158         }
159         if ($private_exp) {
160             $params['private_key'] = new Crypt_RSA_KEY($mod, $private_exp, 'private');
161             if ($params['private_key']->isError()) {
162                 $error = $params['private_key']->getLastError();
163                 common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
164                 return false;
165             }
166         }
167
168         $magic_sig->_rsa = new Crypt_RSA($params);
169         PEAR::popErrorHandling();
170
171         return $magic_sig;
172     }
173
174     public function getName()
175     {
176         return $this->alg;
177     }
178
179     public function getHash()
180     {
181         switch ($this->alg) {
182
183         case 'RSA-SHA256':
184             return 'sha256';
185         }
186
187     }
188     
189     public function sign($bytes)
190     {
191         $sig = $this->_rsa->createSign($bytes, null, 'sha256');
192         if ($this->_rsa->isError()) {
193             $error = $this->_rsa->getLastError();
194             common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
195             return false;
196         }
197
198         return $sig;
199     }
200
201     public function verify($signed_bytes, $signature)
202     {
203         $result =  $this->_rsa->validateSign($signed_bytes, $signature, null, 'sha256');
204         if ($this->_rsa->isError()) {
205             $error = $this->keypair->getLastError();
206             common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
207             return false;
208         }
209         return $result;
210     }
211         
212 }
213
214 // Define a sha256 function for hashing
215 // (Crypt_RSA should really be updated to use hash() )
216 function sha256($bytes)
217 {
218     return hash('sha256', $bytes);
219 }
220
221 function base64_url_encode($input)
222 {
223     return strtr(base64_encode($input), '+/', '-_');
224 }
225
226 function base64_url_decode($input)
227 {
228     return base64_decode(strtr($input, '-_', '+/'));
229 }