3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2010, StatusNet, Inc.
6 * A sample module to show best practices for StatusNet plugins
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.
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.
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/>.
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/
30 if (!defined('STATUSNET')) {
34 require_once 'Crypt/RSA.php';
36 class Magicsig extends Memcached_DataObject
38 const PUBLICKEYREL = 'magic-public-key';
40 public $__table = 'magicsig';
43 * Key to user.id/profile.id for the local user whose key we're storing.
50 * Flattened string representation of the key pair; callers should
51 * usually use $this->publicKey and $this->privateKey directly,
52 * which hold live Crypt_RSA key objects.
59 * Crypto algorithm used for this key; currently only RSA-SHA256 is supported.
66 * Public RSA key; gets serialized in/out via $this->keypair string.
73 * PrivateRSA key; gets serialized in/out via $this->keypair string.
79 public function __construct($alg = 'RSA-SHA256')
85 * Fetch a Magicsig object from the cache or database on a field match.
91 public /*static*/ function staticGet($k, $v=null)
93 $obj = parent::staticGet(__CLASS__, $k, $v);
95 $obj = Magicsig::fromString($obj->keypair);
97 // Double check keys: Crypt_RSA did not
98 // consistently generate good keypairs.
99 // We've also moved to 1024 bit keys.
100 if (strlen($obj->publicKey->modulus->toBits()) != 1024) {
113 'user_id' => DB_DATAOBJECT_INT,
114 'keypair' => DB_DATAOBJECT_STR + DB_DATAOBJECT_NOTNULL,
115 'alg' => DB_DATAOBJECT_STR
119 static function schemaDef()
121 return array(new ColumnDef('user_id', 'integer',
123 new ColumnDef('keypair', 'text',
125 new ColumnDef('alg', 'varchar',
131 return array_keys($this->keyTypes());
136 return array('user_id' => 'K');
139 function sequenceKey() {
140 return array(false, false, false);
144 * Save this keypair into the database.
146 * Overloads default insert behavior to encode the live key objects
147 * as a flat string for storage.
153 $this->keypair = $this->toString();
155 return parent::insert();
159 * Generate a new keypair for a local user and store in the database.
161 * Warning: this can be very slow on systems without the GMP module.
162 * Runtimes of 20-30 seconds are not unheard-of.
164 * @param int $user_id id of local user we're creating a key for
166 public function generate($user_id)
168 $rsa = new Crypt_RSA();
170 $keypair = $rsa->createKey();
172 $rsa->loadKey($keypair['privatekey']);
174 $this->privateKey = new Crypt_RSA();
175 $this->privateKey->loadKey($keypair['privatekey']);
177 $this->publicKey = new Crypt_RSA();
178 $this->publicKey->loadKey($keypair['publickey']);
180 $this->user_id = $user_id;
185 * Encode the keypair or public key as a string.
187 * @param boolean $full_pair set to false to leave out the private key.
190 public function toString($full_pair = true)
192 $mod = Magicsig::base64_url_encode($this->publicKey->modulus->toBytes());
193 $exp = Magicsig::base64_url_encode($this->publicKey->exponent->toBytes());
195 if ($full_pair && $this->privateKey->exponent->toBytes()) {
196 $private_exp = '.' . Magicsig::base64_url_encode($this->privateKey->exponent->toBytes());
199 return 'RSA.' . $mod . '.' . $exp . $private_exp;
203 * Decode a string representation of an RSA public key or keypair
204 * as a Magicsig object which can be used to sign or verify.
206 * @param string $text
209 public static function fromString($text)
211 $magic_sig = new Magicsig();
214 $text = preg_replace('/\s+/', '', $text);
217 if (!preg_match('/RSA\.([^\.]+)\.([^\.]+)(.([^\.]+))?/', $text, $matches)) {
223 if (!empty($matches[4])) {
224 $private_exp = $matches[4];
226 $private_exp = false;
229 $magic_sig->loadKey($mod, $exp, 'public');
231 $magic_sig->loadKey($mod, $private_exp, 'private');
238 * Fill out $this->privateKey or $this->publicKey with a Crypt_RSA object
239 * representing the give key (as mod/exponent pair).
241 * @param string $mod base64-encoded
242 * @param string $exp base64-encoded exponent
243 * @param string $type one of 'public' or 'private'
245 public function loadKey($mod, $exp, $type = 'public')
247 common_log(LOG_DEBUG, "Adding ".$type." key: (".$mod .', '. $exp .")");
249 $rsa = new Crypt_RSA();
250 $rsa->signatureMode = CRYPT_RSA_SIGNATURE_PKCS1;
251 $rsa->setHash('sha256');
252 $rsa->modulus = new Math_BigInteger(Magicsig::base64_url_decode($mod), 256);
253 $rsa->k = strlen($rsa->modulus->toBytes());
254 $rsa->exponent = new Math_BigInteger(Magicsig::base64_url_decode($exp), 256);
256 if ($type == 'private') {
257 $this->privateKey = $rsa;
259 $this->publicKey = $rsa;
264 * Returns the name of the crypto algorithm used for this key.
268 public function getName()
274 * Returns the name of a hash function to use for signing with this key.
277 * @fixme is this used? doesn't seem to be called by name.
279 public function getHash()
281 switch ($this->alg) {
289 * Generate base64-encoded signature for the given byte string
290 * using our private key.
292 * @param string $bytes as raw byte string
293 * @return string base64-encoded signature
295 public function sign($bytes)
297 $sig = $this->privateKey->sign($bytes);
298 return Magicsig::base64_url_encode($sig);
303 * @param string $signed_bytes as raw byte string
304 * @param string $signature as base64
307 public function verify($signed_bytes, $signature)
309 $signature = Magicsig::base64_url_decode($signature);
310 return $this->publicKey->verify($signed_bytes, $signature);
314 * URL-encoding-friendly base64 variant encoding.
316 * @param string $input
319 public static function base64_url_encode($input)
321 return strtr(base64_encode($input), '+/', '-_');
325 * URL-encoding-friendly base64 variant decoding.
327 * @param string $input
330 public static function base64_url_decode($input)
332 return base64_decode(strtr($input, '-_', '+/'));