]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
dee193cd5ad1e1550fb3fbea844d751aee342cc8
[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         return Magicsig::fromString($obj->keypair);
54     }
55
56
57     function table()
58     {
59         return array(
60             'user_id' => DB_DATAOBJECT_INT,
61             'keypair' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
62             'alg'     => DB_DATAOBJECT_STR
63         );
64     }
65
66     static function schemaDef()
67     {
68         return array(new ColumnDef('user_id', 'integer',
69                                    null, true, 'PRI'),
70                      new ColumnDef('keypair', 'varchar',
71                                    255, false),
72                      new ColumnDef('alg', 'varchar',
73                                    64, false));
74     }
75
76
77     function keys()
78     {
79         return array_keys($this->keyTypes());
80     }
81
82     function keyTypes()
83     {
84         return array('user_id' => 'K');
85     }
86
87     function sequenceKeys() {
88         return array(false, false, false);
89     }
90
91     function insert()
92     {
93         $this->keypair = $this->toString();
94
95         return parent::insert();
96     }
97
98     public function generate($user_id, $key_length = 512)
99     {
100         PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
101
102         $keypair = new Crypt_RSA_KeyPair($key_length);
103         $params['public_key'] = $keypair->getPublicKey();
104         $params['private_key'] = $keypair->getPrivateKey();
105
106         $this->_rsa = new Crypt_RSA($params);
107         PEAR::popErrorHandling();
108
109         $this->user_id = $user_id;
110         $this->insert();
111     }
112
113
114     public function toString($full_pair = true)
115     {
116         $public_key = $this->_rsa->_public_key;
117         $private_key = $this->_rsa->_private_key;
118
119         $mod = base64_url_encode($public_key->getModulus());
120         $exp = base64_url_encode($public_key->getExponent());
121         $private_exp = '';
122         if ($full_pair && $private_key->getExponent()) {
123             $private_exp = '.' . base64_url_encode($private_key->getExponent());
124         }
125
126         return 'RSA.' . $mod . '.' . $exp . $private_exp; 
127     }
128     
129     public static function fromString($text)
130     {
131         PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
132
133         $magic_sig = new Magicsig();
134         
135         // remove whitespace
136         $text = preg_replace('/\s+/', '', $text);
137
138         // parse components
139         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
140             return false;
141         }
142         
143         $mod = base64_url_decode($matches[1]);
144         $exp = base64_url_decode($matches[2]);
145         if ($matches[4]) {
146             $private_exp = base64_url_decode($matches[4]);
147         }
148
149         $params['public_key'] = new Crypt_RSA_KEY($mod, $exp, 'public');
150         if ($params['public_key']->isError()) {
151             $error = $params['public_key']->getLastError();
152             common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
153             return false;
154         }
155         if ($private_exp) {
156             $params['private_key'] = new Crypt_RSA_KEY($mod, $private_exp, 'private');
157             if ($params['private_key']->isError()) {
158                 $error = $params['private_key']->getLastError();
159                 common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
160                 return false;
161             }
162         }
163
164         $magic_sig->_rsa = new Crypt_RSA($params);
165         PEAR::popErrorHandling();
166
167         return $magic_sig;
168     }
169
170     public function getName()
171     {
172         return $this->alg;
173     }
174
175     public function getHash()
176     {
177         switch ($this->alg) {
178
179         case 'RSA-SHA256':
180             return 'sha256';
181         }
182
183     }
184     
185     public function sign($bytes)
186     {
187         $sig = $this->_rsa->createSign($bytes, null, 'sha256');
188         if ($this->_rsa->isError()) {
189             $error = $this->_rsa->getLastError();
190             common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
191             return false;
192         }
193
194         return $sig;
195     }
196
197     public function verify($signed_bytes, $signature)
198     {
199         $result =  $this->_rsa->validateSign($signed_bytes, $signature, null, 'sha256');
200         if ($this->_rsa->isError()) {
201             $error = $this->keypair->getLastError();
202             common_log(LOG_DEBUG, 'RSA Error: '. $error->getMessage());
203             return false;
204         }
205         return $result;
206     }
207         
208 }
209
210 // Define a sha256 function for hashing
211 // (Crypt_RSA should really be updated to use hash() )
212 function sha256($bytes)
213 {
214     return hash('sha256', $bytes);
215 }
216
217 function base64_url_encode($input)
218 {
219     return strtr(base64_encode($input), '+/', '-_');
220 }
221
222 function base64_url_decode($input)
223 {
224     return base64_decode(strtr($input, '-_', '+/'));
225 }