Subversion Repositories cheapmusic

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
7 - 1
<?php
2
/**
3
 * Openssl encrypt/decrypt functions
4
 *
5
 * Available under the MIT License
6
 *
7
 * The MIT License (MIT)
8
 * Copyright (c) 2016 ionCube Ltd.
9
 *
10
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
11
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
12
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
13
 * permit persons to whom the Software is furnished to do so, subject to the following conditions:
14
 *
15
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of
16
 * the Software.
17
 *
18
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
19
 * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
20
 * OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21
 * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
22
 */
23
class Cryptor
24
{
25
    private static $instance = null;
26
    private static $cipher_algo;
27
    private static $hash_algo;
28
    private static $keystring;
29
    private static $iv_num_bytes;
30
    private static $format;
31
    const FORMAT_RAW = 0;
32
    const FORMAT_B64 = 1;
33
    const FORMAT_HEX = 2;
34
 
35
    /**
36
     * Create a Cryptor singleton instance
37
     * @param array $cryptConfig The cipher algorithm, the hash algorithm and the key.
38
     * @param [type] $fmt         Optional override for the output encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX. Default: FORMAT_B64.
39
     */
40
    public function getInstance($cryptorConfig = null, $fmt = Cryptor::FORMAT_B64)
41
    {
42
        if (is_null(self::$instance)){
43
            self::$instance = new self();
44
        } else {
45
            return self::$instance;
46
        }
47
        // store cryptor configuration
48
        if (!is_null($cryptorConfig)) {
49
            if (isset($cryptorConfig['cipherAlgorithm']) && !empty($cryptorConfig['cipherAlgorithm'])) {
50
                self::$cipher_algo = $cryptorConfig['cipherAlgorithm'];
51
            } else {
52
                self::$cipher_algo = 'aes-256-cbc';
53
            }
54
            if (isset($cryptorConfig['hashAlgorithm']) && !empty($cryptorConfig['hashAlgorithm'])) {
55
                self::$hash_algo = $cryptorConfig['hashAlgorithm'];
56
            } else {
57
                self::$hash_algo = 'sha256';
58
            }
59
            if (isset($cryptorConfig['key']) && !empty($cryptorConfig['key'])) {
60
                self::$keystring = $cryptorConfig['key'];
61
            } else {
62
                throw new \Exception("Cryptor:: - key not set in configuration");
63
            }
64
            if ($fmt === Cryptor::FORMAT_RAW || $fmt === Cryptor::FORMAT_B64 || $fmt == Cryptor::FORMAT_HEX) {
65
                self::$format = $fmt;
66
            } else {
67
                self::$format = Cryptor::FORMAT_B64;
68
            }
69
        }
70
 
71
        if (!in_array(self::$cipher_algo, openssl_get_cipher_methods(true)))
72
        {
73
            throw new \Exception("Cryptor:: - unknown cipher algo {" . self::$cipher_algo . "}");
74
        }
75
 
76
        if (!in_array(self::$hash_algo, openssl_get_md_methods(true)))
77
        {
78
            throw new \Exception("Cryptor:: - unknown hash algo {" . self::$hash_algo . "}");
79
        }
80
 
81
        self::$iv_num_bytes = openssl_cipher_iv_length(self::$cipher_algo);
82
 
83
        return self::$instance;
84
    }
85
    /**
86
     * Encrypt a string.
87
     * @param  string $in  String to encrypt.
88
     * @param  string $key Optional encryption key.
89
     * @param  int $fmt Optional override for the output encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
90
     * @return string      The encrypted string.
91
     */
92
    public function encryptString($in, $key = null, $fmt = null)
93
    {
94
        if ($fmt === null)
95
        {
96
            $fmt = self::$format;
97
        }
98
        if ($key === null)
99
        {
100
            $key = self::$keystring;
101
        }
102
        // Build an initialization vector
103
        $iv = openssl_random_pseudo_bytes(self::$iv_num_bytes, $isStrongCrypto);
104
        if (!$isStrongCrypto) {
105
            throw new \Exception("Cryptor::encryptString() - Not a strong key");
106
        }
107
        // Hash the key
108
        $keyhash = openssl_digest($key, self::$hash_algo, true);
109
        // and encrypt
110
        $opts =  OPENSSL_RAW_DATA;
111
        $encrypted = openssl_encrypt($in, self::$cipher_algo, $keyhash, $opts, $iv);
112
        if ($encrypted === false)
113
        {
114
            throw new \Exception('Cryptor::encryptString() - Encryption failed: ' . openssl_error_string());
115
        }
116
        // The result comprises the IV and encrypted data
117
        $res = $iv . $encrypted;
118
        // and format the result if required.
119
        if ($fmt == Cryptor::FORMAT_B64)
120
        {
121
            $res = base64_encode($res);
122
        }
123
        else if ($fmt == Cryptor::FORMAT_HEX)
124
        {
125
            $res = unpack('H*', $res)[1];
126
        }
127
        return $res;
128
    }
129
    /**
130
     * Decrypt a string.
131
     * @param  string $in  String to decrypt.
132
     * @param  string $key Optional decryption key.
133
     * @param  int $fmt Optional override for the input encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
134
     * @return string      The decrypted string.
135
     */
136
    public function decryptString($in, $key = null, $fmt = null)
137
    {
138
        if ($fmt === null)
139
        {
140
            $fmt = self::$format;
141
        }
142
        if ($key === null)
143
        {
144
            $key = self::$keystring;
145
        }
146
        $raw = $in;
147
        // Restore the encrypted data if encoded
148
        if ($fmt == Cryptor::FORMAT_B64)
149
        {
150
            $raw = base64_decode($in);
151
        }
152
        else if ($fmt == Cryptor::FORMAT_HEX)
153
        {
154
            $raw = pack('H*', $in);
155
        }
156
        // and do an integrity check on the size.
157
        if (strlen($raw) < self::$iv_num_bytes)
158
        {
159
            throw new \Exception('Cryptor::decryptString() - ' .
160
                'data length ' . strlen($raw) . " is less than iv length {self::$iv_num_bytes}");
161
        }
162
        // Extract the initialization vector and encrypted data
163
        $iv = substr($raw, 0, self::$iv_num_bytes);
164
        $raw = substr($raw, self::$iv_num_bytes);
165
        // Hash the key
166
        $keyhash = openssl_digest($key, self::$hash_algo, true);
167
        // and decrypt.
168
        $opts = OPENSSL_RAW_DATA;
169
        $res = openssl_decrypt($raw, self::$cipher_algo, $keyhash, $opts, $iv);
170
        if ($res === false)
171
        {
172
            throw new \Exception('Cryptor::decryptString - decryption failed: ' . openssl_error_string());
173
        }
174
        return $res;
175
    }
176
    /**
177
     * Static convenience method for encrypting.
178
     * @param  string $in  String to encrypt.
179
     * @param  string $key Optional encryption key.
180
     * @param  int $fmt Optional override for the output encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
181
     * @return string      The encrypted string.
182
     */
183
    public static function Encrypt($in, $key = null, $fmt = null)
184
    {
185
        //$c = new Cryptor();
186
        return self::encryptString($in, $key, $fmt);
187
    }
188
    /**
189
     * Static convenience method for decrypting.
190
     * @param  string $in  String to decrypt.
191
     * @param  string $key Optinal eecryption key.
192
     * @param  int $fmt Optional override for the input encoding. One of FORMAT_RAW, FORMAT_B64 or FORMAT_HEX.
193
     * @return string      The decrypted string.
194
     */
195
    public static function Decrypt($in, $key = null, $fmt = null)
196
    {
197
        //$c = new Cryptor();
198
        return self::decryptString($in, $key, $fmt);
199
    }
200
}