Completed
Push — master ( 6ef06d...ce5074 )
by Florent
02:18
created

AESMCrypt::decrypt()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
rs 9.4285
cc 1
eloc 7
nc 1
nop 3
1
<?php
2
3
/*
4
 * The MIT License (MIT)
5
 *
6
 * Copyright (c) 2014-2016 Spomky-Labs
7
 *
8
 * This software may be modified and distributed under the terms
9
 * of the MIT license.  See the LICENSE file for details.
10
 */
11
12
namespace SpomkyLabs\Jose\Algorithm\ContentEncryption;
13
14
use Jose\Util\StringUtil;
15
16
/**
17
 */
18
final class AESMCrypt implements AESInterface
19
{
20
    public static function encrypt($data, $k, $iv)
21
    {
22
        $resource = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
23
        $padded_text = self::pad($data, 16);
24
        mcrypt_generic_init($resource, $k, $iv);
25
        $cipherText = mcrypt_generic($resource, $padded_text);
26
        mcrypt_generic_deinit($resource);
27
28
        return $cipherText;
29
    }
30
31
    public static function decrypt($data, $k, $iv)
32
    {
33
        $resource = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
34
        mcrypt_generic_init($resource, $k, $iv);
35
        $decrypted = mdecrypt_generic($resource, $data);
36
        mcrypt_generic_deinit($resource);
37
        $decrypted_text = self::unpad($decrypted);
38
39
        return $decrypted_text;
40
    }
41
42
    private static function pad($data, $block_size)
43
    {
44
        $padding = $block_size - (StringUtil::getStringLength($data) % $block_size);
45
        $pattern = chr($padding);
46
47
        return $data.str_repeat($pattern, $padding);
48
    }
49
50
    private static function unpad($data)
51
    {
52
        $padChar = StringUtil::getSubString($data, -1);
53
        $padLength = ord($padChar);
54
55
        return StringUtil::getSubString($data, 0, -$padLength);
56
    }
57
}
58