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