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

AESMCrypt   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 4
c 1
b 0
f 0
lcom 0
cbo 1
dl 0
loc 40
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A encrypt() 0 10 1
A decrypt() 0 10 1
A pad() 0 7 1
A unpad() 0 7 1
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