1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
<?php
class CheckUserEncryptedData {
// The data symmetrically encrypted with a random key
public $encString;
// Symmetric key, encrypted with the public key
public $envKeys;
// algorithm name, passed into openssl 'method' param. Kept as a variable here in case
// the class definition needs to change, and we have serialized objects stored.
private $algName;
// Hash of the public key, in case you've used multiple keys, and need to identify the
// correct private key
private $keyHash;
/**
* Create an EncryptedData object from
*
* @param mixed $data Data/object to be encryted
* @param string $publicKey Public key for encryption
* @param string $algorithmName
*/
public function __construct( $data, $publicKey, $algorithmName = 'rc4' ) {
$this->keyHash = crc32( $publicKey );
$this->algName = $algorithmName;
$this->encryptData( serialize( $data ), $publicKey );
}
/**
* Decrypt the text in this object
*
* @param string $privateKey String with ascii-armored block,
* or the return of openssl_get_privatekey
* @return string plaintext
*/
public function getPlaintext( $privateKey ) {
$result = openssl_open(
$this->encString,
$plaintextData,
$this->envKeys,
$privateKey,
$this->algName
);
if ( $result == false ) {
return false;
}
return unserialize( $plaintextData );
}
/**
* Encrypt data with a public key
*
* @param string $data
* @param string $publicKey String with ascii-armored block,
* or the return of openssl_get_publickey
*/
private function encryptData( $data, $publicKey ) {
openssl_seal( $data, $encryptedString, $envelopeKeys, [ $publicKey ], $this->algName );
$this->encString = $encryptedString;
$this->envKeys = $envelopeKeys[0];
}
}
|