]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/classes/Magicsig.php
Add IdentiCurse to notice sources
[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 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 require_once 'Crypt/RSA.php';
35
36 class Magicsig extends Memcached_DataObject
37 {
38     const PUBLICKEYREL = 'magic-public-key';
39
40     public $__table = 'magicsig';
41
42     public $user_id;
43     public $keypair;
44     public $alg;
45
46     public $publicKey;
47     public $privateKey;
48
49     public function __construct($alg = 'RSA-SHA256')
50     {
51         $this->alg = $alg;
52     }
53
54     public /*static*/ function staticGet($k, $v=null)
55     {
56         $obj =  parent::staticGet(__CLASS__, $k, $v);
57         if (!empty($obj)) {
58             $obj = Magicsig::fromString($obj->keypair);
59
60             // Double check keys: Crypt_RSA did not
61             // consistently generate good keypairs.
62             // We've also moved to 1024 bit keys.
63             if (strlen($obj->publicKey->modulus->toBits()) != 1024) {
64                 $obj->delete();
65                 return false;
66             }
67         }
68
69         return $obj;
70     }
71
72
73     function table()
74     {
75         return array(
76             'user_id' => DB_DATAOBJECT_INT,
77             'keypair' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
78             'alg'     => DB_DATAOBJECT_STR
79         );
80     }
81
82     static function schemaDef()
83     {
84         return array(new ColumnDef('user_id', 'integer',
85                                    null, false, 'PRI'),
86                      new ColumnDef('keypair', 'text',
87                                    false, false),
88                      new ColumnDef('alg', 'varchar',
89                                    64, false));
90     }
91
92     function keys()
93     {
94         return array_keys($this->keyTypes());
95     }
96
97     function keyTypes()
98     {
99         return array('user_id' => 'K');
100     }
101
102     function sequenceKey() {
103         return array(false, false, false);
104     }
105
106     function insert()
107     {
108         $this->keypair = $this->toString();
109
110         return parent::insert();
111     }
112
113     public function generate($user_id)
114     {
115         $rsa = new Crypt_RSA();
116
117         $keypair = $rsa->createKey();
118
119         $rsa->loadKey($keypair['privatekey']);
120
121         $this->privateKey = new Crypt_RSA();
122         $this->privateKey->loadKey($keypair['privatekey']);
123
124         $this->publicKey = new Crypt_RSA();
125         $this->publicKey->loadKey($keypair['publickey']);
126
127         $this->user_id = $user_id;
128         $this->insert();
129     }
130
131     public function toString($full_pair = true)
132     {
133         $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
134         $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
135         $private_exp = '';
136         if ($full_pair && $this->privateKey->exponent->toBytes()) {
137             $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
138         }
139
140         return 'RSA.' . $mod . '.' . $exp . $private_exp;
141     }
142
143     public static function fromString($text)
144     {
145         $magic_sig = new Magicsig();
146
147         // remove whitespace
148         $text = preg_replace('/\s+/', '', $text);
149
150         // parse components
151         if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
152             return false;
153         }
154
155         $mod = $matches[1];
156         $exp = $matches[2];
157         if (!empty($matches[4])) {
158             $private_exp = $matches[4];
159         } else {
160             $private_exp = false;
161         }
162
163         $magic_sig->loadKey($mod, $exp, 'public');
164         if ($private_exp) {
165             $magic_sig->loadKey($mod, $private_exp, 'private');
166         }
167
168         return $magic_sig;
169     }
170
171     public function loadKey($mod, $exp, $type = 'public')
172     {
173         common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
174
175         $rsa = new Crypt_RSA();
176         $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
177         $rsa->setHash('sha256');
178         $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
179         $rsa->k = strlen($rsa->modulus->toBytes());
180         $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
181
182         if ($type == 'private') {
183             $this->privateKey = $rsa;
184         } else {
185             $this->publicKey = $rsa;
186         }
187     }
188
189     public function getName()
190     {
191         return $this->alg;
192     }
193
194     public function getHash()
195     {
196         switch ($this->alg) {
197
198         case 'RSA-SHA256':
199             return 'sha256';
200         }
201     }
202
203     public function sign($bytes)
204     {
205         $sig = $this->privateKey->sign($bytes);
206         return Magicsig::base64_url_encode($sig);
207     }
208
209     public function verify($signed_bytes, $signature)
210     {
211         $signature = Magicsig::base64_url_decode($signature);
212         return $this->publicKey->verify($signed_bytes, $signature);
213     }
214
215
216     public static function base64_url_encode($input)
217     {
218         return strtr(base64_encode($input), '+/', '-_');
219     }
220
221     public static function base64_url_decode($input)
222     {
223         return base64_decode(strtr($input, '-_', '+/'));
224     }
225 }