Encrypt_Core::instance()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 1 Features 0
Metric Value
cc 2
eloc 4
c 2
b 1
f 0
nc 2
nop 1
dl 0
loc 9
rs 9.6666
1
<?php defined('SYSPATH') or die('No direct access allowed.');
2
/**
3
 * The Encrypt library provides two-way encryption of text and binary strings
4
 * using the MCrypt extension.
5
 * @see http://php.net/mcrypt
6
 *
7
 * $Id: Encrypt.php 4072 2009-03-13 17:20:38Z jheathco $
8
 *
9
 * @package    Core
10
 * @author     Kohana Team
11
 * @copyright  (c) 2007-2008 Kohana Team
12
 * @license    http://kohanaphp.com/license.html
13
 */
14
class Encrypt_Core
15
{
16
17
    // OS-dependant RAND type to use
18
    protected static $rand;
19
20
    // Configuration
21
    protected $config;
22
23
    /**
24
     * Returns a singleton instance of Encrypt.
25
     *
26
     * @param   array  configuration options
27
     * @return  Encrypt_Core
0 ignored issues
show
Documentation introduced by
Should the return type not be Encrypt?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
28
     */
29
    public static function instance($config = null)
30
    {
31
        static $instance;
32
33
        // Create the singleton
34
        empty($instance) and $instance = new Encrypt((array) $config);
35
36
        return $instance;
37
    }
38
39
    /**
40
     * Loads encryption configuration and validates the data.
41
     *
42
     * @param   array|string      custom configuration or config group name
43
     * @throws  Kohana_Exception
44
     */
45
    public function __construct($config = false)
46
    {
47
        if (! defined('MCRYPT_ENCRYPT')) {
48
            throw new Kohana_Exception('encrypt.requires_mcrypt');
49
        }
50
51 View Code Duplication
        if (is_string($config)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
52
            $name = $config;
53
54
            // Test the config group name
55
            if (($config = Kohana::config('encryption.'.$config)) === null) {
56
                throw new Kohana_Exception('encrypt.undefined_group', $name);
57
            }
58
        }
59
60
        if (is_array($config)) {
61
            // Append the default configuration options
62
            $config += Kohana::config('encryption.default');
63
        } else {
64
            // Load the default group
65
            $config = Kohana::config('encryption.default');
66
        }
67
68
        if (empty($config['key'])) {
69
            throw new Kohana_Exception('encrypt.no_encryption_key');
70
        }
71
72
        // Find the max length of the key, based on cipher and mode
73
        $size = mcrypt_get_key_size($config['cipher'], $config['mode']);
74
75
        if (strlen($config['key']) > $size) {
76
            // Shorten the key to the maximum size
77
            $config['key'] = substr($config['key'], 0, $size);
78
        }
79
80
        // Find the initialization vector size
81
        $config['iv_size'] = mcrypt_get_iv_size($config['cipher'], $config['mode']);
82
83
        // Cache the config in the object
84
        $this->config = $config;
85
86
        Kohana::log('debug', 'Encrypt Library initialized');
87
    }
88
89
    /**
90
     * Encrypts a string and returns an encrypted string that can be decoded.
91
     *
92
     * @param   string  data to be encrypted
93
     * @return  string  encrypted data
94
     */
95
    public function encode($data)
96
    {
97
        // Set the rand type if it has not already been set
98
        if (Encrypt::$rand === null) {
99
            if (KOHANA_IS_WIN) {
100
                // Windows only supports the system random number generator
101
                Encrypt::$rand = MCRYPT_RAND;
102
            } else {
103
                if (defined('MCRYPT_DEV_URANDOM')) {
104
                    // Use /dev/urandom
105
                    Encrypt::$rand = MCRYPT_DEV_URANDOM;
106
                } elseif (defined('MCRYPT_DEV_RANDOM')) {
107
                    // Use /dev/random
108
                    Encrypt::$rand = MCRYPT_DEV_RANDOM;
109
                } else {
110
                    // Use the system random number generator
111
                    Encrypt::$rand = MCRYPT_RAND;
112
                }
113
            }
114
        }
115
116
        if (Encrypt::$rand === MCRYPT_RAND) {
117
            // The system random number generator must always be seeded each
118
            // time it is used, or it will not produce true random results
119
            mt_srand();
120
        }
121
122
        // Create a random initialization vector of the proper size for the current cipher
123
        $iv = mcrypt_create_iv($this->config['iv_size'], Encrypt::$rand);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $iv. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
124
125
        // Encrypt the data using the configured options and generated iv
126
        $data = mcrypt_encrypt($this->config['cipher'], $this->config['key'], $data, $this->config['mode'], $iv);
127
128
        // Use base64 encoding to convert to a string
129
        return base64_encode($iv.$data);
130
    }
131
132
    /**
133
     * Decrypts an encoded string back to its original value.
134
     *
135
     * @param   string  encoded string to be decrypted
136
     * @return  string  decrypted data
137
     */
138
    public function decode($data)
139
    {
140
        // Convert the data back to binary
141
        $data = base64_decode($data);
142
143
        // Extract the initialization vector from the data
144
        $iv = substr($data, 0, $this->config['iv_size']);
0 ignored issues
show
Comprehensibility introduced by
Avoid variables with short names like $iv. Configured minimum length is 3.

Short variable names may make your code harder to understand. Variable names should be self-descriptive. This check looks for variable names who are shorter than a configured minimum.

Loading history...
145
146
        // Remove the iv from the data
147
        $data = substr($data, $this->config['iv_size']);
148
149
        // Return the decrypted data, trimming the \0 padding bytes from the end of the data
150
        return rtrim(mcrypt_decrypt($this->config['cipher'], $this->config['key'], $data, $this->config['mode'], $iv), "\0");
151
    }
152
} // End Encrypt
153