PHPackages                             www.gobuy.cheap/data\_encryption - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Security](/categories/security)
4. /
5. www.gobuy.cheap/data\_encryption

ActiveLibrary[Security](/categories/security)

www.gobuy.cheap/data\_encryption
================================

v1.1(1y ago)014MITPHP

Since Jul 24Pushed 1y ago1 watchersCompare

[ Source](https://github.com/codingdrips1on1/www.gobuy.cheap)[ Packagist](https://packagist.org/packages/www.gobuy.cheap/data_encryption)[ RSS](/packages/wwwgobuycheap-data-encryption/feed)WikiDiscussions main Synced yesterday

READMEChangelogDependencies (4)Versions (3)Used By (0)

Table of Contents
-----------------

[](#table-of-contents)

- [About Library](#about-library)
    - [Features](#features)
    - [Requirements](#requirements)
    - [CMS Functionality](#cms-functionality)
    - [Built-in Logging](#built-in-logging)
    - [Installation](#installation)
    - [Usage](#usage)
    - [Cascading Encryption Stages](#cascading-encryption-stages)
- [Advanced Encryption (CMS and PKCS) Including Chain of Trust and Diffie-Hellman.](#advanced-encryption-cms-and-pkcs-including-chain-of-trust-and-diffie-hellman)
    - [To sign a file](#to-sign-a-file)
    - [Choosing Between .pem, .crt, and .key extensions for data storage](#choosing-between-pem-crt-and-key-extensions-for-data-storage)
    - [Example of File Content:](#example-of-file-content)
    - [Best Practices](#best-practices)
    - [Explanation of the `openssl.cnf` file Contents](#explanation-of-the-opensslcnf-file-contents)
        - [\[req\] Section](#req-section)
        - [Distinguished Name Section](#distinguished-name-section)
        - [Attributes Section](#attributes-section)
        - [X.509 Extensions Section](#x509-extensions-section)
        - [\[req\_distinguished\_name\] Section](#req_distinguished_name-section)
        - [\[req\_attributes\] Section](#req_attributes-section)
        - [\[v3\_req\] Section](#v3_req-section)
        - [\[alt\_names\] Section](#alt_names-section)
    - [Cascading intermediate certificate](#cascading-intermediate-certificate)
        - [output](#output)
        - [Types of Certificate Bundles](#types-of-certificate-bundles)
    - [Usage Contexts](#usage-contexts)
        - [Only Cascaded Intermediate Certificates](#only-cascaded-intermediate-certificates)
            - [Certificate Chain (Including Root CA)](#certificate-chain-including-root-ca)
        - [in Summary](#in-summary)
        - [Optionals](#optionals)
    - [To encrypt a file](#to-encrypt-a-file)
        - [1. MIME-Version: 1.0](#1-mime-version-10)
        - [2. Content-Disposition: attachment; filename="smime.p7m"](#2-content-disposition-attachment-filenamesmimep7m)
        - [3. Content-Type: application/pkcs7-mime; smime-type=enveloped-data; name="smime.p7m"](#3-content-type-applicationpkcs7-mime-smime-typeenveloped-data-namesmimep7m)
        - [4. Content-Transfer-Encoding: base64](#4-content-transfer-encoding-base64)
        - [Putting It All Together](#putting-it-all-together)
        - [Usage in S/MIME](#usage-in-smime)
    - [Padding](#padding)
    - [Receiver](#receiver)
    - [Using PKCS7 System](#using-pkcs7-system)
    - [Alternative Certificate Generation](#alternative-certificate-generation)
    - [Use these for you convenience:](#use-these-for-you-convenience)
        - [Explanation](#explanation)
- [Diffie-Hellman](#diffie-hellman)
    - [Blade Template Code](#blade-template-code)
        - [Explanation](#explanation-1)
        - [HTML Div Element for Diffie-Hellman Key Exchange Data](#html-div-element-for-diffie-hellman-key-exchange-data)
            - [HTML Code](#html-code)
            - [Explanation](#explanation-2)
        - [Detailed Explanation](#detailed-explanation)
    - [Controller method](#controller-method)
        - [Detailed Explanation](#detailed-explanation-1)
    - [Alternatively on Diffie-Hellman's](#alternatively-on-diffie-hellmans)
    - [Symmetric Key Generation](#symmetric-key-generation)
    - [Message Authentication Codes (MACs)](#message-authentication-codes-macs)
    - [Key Derivation](#key-derivation)
    - [Forward Secrecy](#forward-secrecy)
    - [Secure Authentication](#secure-authentication)
- [Elliptic-Curve Diffie-Hellman (ECDH)](#elliptic-curve-diffie-hellman-ecdh)
    - [Additional Details:](#additional-details)
- [Certificate Info](#certificate-info)
- [Fetching a Certificate Revocation List (CRL)](#fetching-a-certificate-revocation-list-crl)
- [Exception Handling](#exception-handling)
- [Initial Work](#initial-work)
- [Contributing](#contributing)
- [License](#license)
- [Support](#support)
- [Author](#author)
- [Books for your information.](#books-for-your-information)

Encrypt with confidence, stay secure with our APIs. Your data's shield in transit - powered by our encryption. Protecting every bit, byte, and heartbeat of your data. Trust us to keep your secrets safe on the move. We offer the encryption you can rely on, security you can trust.

About Library
=============

[](#about-library)

Ensuring the safety of user data during transit is crucial in today's digital age, and our encryption APIs are designed to provide robust protection. By leveraging advanced encryption standards, we ensure that your data is transformed into a secure format that can only be decrypted by authorized parties. This not only protects the data from unauthorized access but also maintains its integrity throughout the transmission process. Users can count on our APIs to provide a seamless and secure encryption experience, making their applications more resilient against data breaches and cyber threats.

Our encryption stages involve multiple layers of security to disguise data effectively. First, data is encrypted using strong algorithms, converting it into ciphertext that is unreadable without the correct decryption key. This process ensures that even if data is intercepted, it remains inaccessible to malicious actors. Additionally, our APIs support key management protocols that safeguard the encryption keys themselves, adding an extra layer of protection. By utilizing our comprehensive encryption stages, users can rest assured that their sensitive information is shielded from prying eyes at every step of its journey.

We understand that the security of your applications is paramount, and our encryption APIs are designed with this in mind. From initial encryption to key management and final decryption, every stage is meticulously crafted to provide maximum security. Our solutions are continuously updated to adhere to the latest security standards and practices, ensuring that your data remains secure in an ever-evolving threat landscape. Trust in our encryption stages to keep your data safe, allowing you to focus on delivering exceptional experiences to your users without compromising on security.

Features
--------

[](#features)

- **Easy-to-use CMS**: Manage your content efficiently with our user-friendly CMS.
- **PKCS7 Encryption**: Secure your data with advanced PKCS7 signing, encrypting, decrypting, and signature-verifying capabilities.
- **Diffie-Hellman's**: Secured using DH's key-exchange mechanism.
- **Elliptic-Curve Diffie-Hellman (ECDH)**: ECDH provides higher security with shorter key lengths compared to ordinary DH. For instance, a 256-bit key in ECDH offers comparable security to a 3072-bit key in DH. This makes ECDH more efficient in terms of computational resources and communication bandwidth.
- **Built-in Logging**: Comprehensive logging provided by Monolog.
- **Exception Handling**: Robust error management to ensure smooth operation.

Requirements
------------

[](#requirements)

- **PHP 7.4 or higher**: Ensure your server is running PHP version 7.4 or later.
- **OpenSSL extension enabled**: Make sure the OpenSSL extension is enabled in your PHP configuration.
- **Composer**: Dependency management is handled through Composer.

1. Ensure your PHP environment meets the [Requirements](#requirements).

CMS Functionality
-----------------

[](#cms-functionality)

1. Access the CMS interface to manage your content easily.

Built-in Logging
----------------

[](#built-in-logging)

Logging is managed by Monolog. You can configure logging settings in the `config/logging.php` file:

Installation
------------

[](#installation)

Use Composer to install the library:

```
composer require www.gobuy.cheap/data_encryption
```

Usage
-----

[](#usage)

To use the CMS Signer, you need to include the Composer autoload file and start invoking class members with the instance `$gobuy`. Class name is `GoBuyEncryption` incase you prefer a different class object name. The class constructor takes no argument.

Check if OpenSSL module is loaded.

```
// Load the OpenSSL module
if (!extension_loaded('openssl')) {
    die('OpenSSL extension is not loaded.');
}
```

For Laravel users. You have to inject our object as parameter in your method to be able to work with the class members as shown below. Or you could simply instantiate our class:

```
protected $gobuy;
public function index( Request $req, GoBuyEncryption $gobuy ) {

 $this->gobuy = $gobuy;

}
```

For output dispalys and display of OpenSSL errors use the helpers below for your convinience:

```
$gobuy->output( "Some output message", "Title of the output" ); // Display errors if string or var_dumps if an array.
$gobuy->showAnyError( ); // Displays all openssl_error_string()
$gobuy->log->warning('Foo');

// Error file is in public/log/
```

You may also decide to log your output in a different location. Then try the below solution:

```
$gobuy->initLogger( "ERR_NAME" )
            ->thenSetPath( $root."app/log.log" );
$gobuy->log->info('The file has been successfully created.');
```

For Laravel users, the root path `$this->getRoot()` stops in the directory where the laravel `app` folder and `vendor` are. The App folder and the vendor are to be in the same directory for this class method to serve properly. If you dont use it, then files are expected to be in the `public` folder. To use, you can say:

```
$root = $gobuy->getRoot( ); // You could proceed to generate your own path, if you choose not to use ours.
$gobuy->create( $folderName ); // This helper helps you create new folders only in the 'app' folder.
$gobuy->checkAndCreateFile($root."app/CMS/data.txt"); // This helper helps you create a new folder, if it does not exist, and its file. Supply full path with the file name.

$gobuy->folderExistsOrCreate( $root."/FOO" ); // Create folder if it does not exist.
```

Cascading Encryption Stages
---------------------------

[](#cascading-encryption-stages)

We cascade encryption stages to strengthen your digital footprints, and secure your digital presence. This also makes it very hard for the man-in-the-middle or any other cryptoanalyst to figure out the key with one of the methods out there. If you desire more layers of encryption on the already existing encryption (which we recommend) then simply call the method `harden(...)`.

```
$hardened = $gobuy->harden( $data, $strongKey );
```

On the receiving side call the method `ease()` to return back to working with `$encryptedData`. You can also use this to disguise passwords when signin up your users (very handy).

```
@inject('gobuy', 'App\Services\GoBuy')
//Blade
@php
    $encryptedData = $gobuy->ease( $hardened, $strongKey );
@endphp
```

After hashing a password, simply call this method to help disfigure the password more, making it harder for any cryptoanalyst who may be on your output. This is symetrical - meaning that both you and the client need the same key.

```
$damagedPassword = $gobuy->damageThis( $password, $strongKey );
```

Call the below method to reverse this. This is symetrical - meaning that both you and the client need the same key.

```
$gobuy->restore( $damagedPassword, $strongKey );
```

Call the veil on your passwords, messages, or data, in general, for a much stronger disguise.

```
$veiled = $gobuy->veil( "abcdefghijklmnopqrstuvwxyz0123456789", $key );
```

Call the below method to undo the above. This is symetrical - meaning that both you and the client need the same key.

```
$originalData = $gobuy->unveil( $veiled, $strongKey );
```

Call `cipher` to have your data encrypted. Our output is quite robust since we have employed more advanced padding, and we give you the chance to select how many stages of encryption you want by adjusting the argument `$itrCount`. The higher this value, the stronger the encryption and harder for analysts to detect. Be careful of overhead as you increase the number count. `12` is the recommended value; unless you are certain your CPU or server can handle a higher value. The threats out there were brought to careful consideration as these encryption blocks were built. Your input is efficiently disguised for transit, in order to ensure safe delivery to the receiving side. If you do not supply `$itrCount` and `$padding` arguments, then we will internally. Ours are firm and recommended, unless you have a particular standard you plan to use.

```
$cipher = $gobuy->cipher( "Hello, world!!!!", $strongKey, $itrCount, $padding ); // The last two arguments are optional
```

On the receiving side just easily call the method `decipher()` to return back to working with `$encrypted`data.

```
  //Blade
@php
    $deciphered = $gobuy->decipher( $cipher, $strongKey, $padding ); // The last argument is optional.
@endphp
```

Use the below to return an array list of all the available encryption methods in OpenSSL.

```
  //Blade
@php
    $gobuy->getEncMethods(  );
@endphp
```

Before we go into the advanced stuff, remember this method, which helps you quickly generate a pair of private and public keys in PEM format. The method returns an array of the keys. The first item is the private key, while the second is the public key.

```
list( $privateKey, $publicKey ) = $gobuy->genKeyPair();
```

Advanced Encryption (CMS and PKCS) Including Chain of Trust and Diffie-Hellman.
===============================================================================

[](#advanced-encryption-cms-and-pkcs-including-chain-of-trust-and-diffie-hellman)

To sign a file
--------------

[](#to-sign-a-file)

You are to set the necessary paths to the files you wish to work with before signing, encrypting, decrypting, and verifying.

```
/**
 *  The input and output files could be ".cms" or ".p7m".
 *  Do not use "file://" just "./folder/file.txt" for example.
 */

// Set the input filename for the data to be signed
$gobuy->setInputFilename($root."app/path/to/the/original/message/data.txt"); // This is the human-readable message you wish to encrypt.

// Set the path to the sender's certificate
$gobuy->setSenderCertPath($root."app/path/to/sender/certificate.pem");

// Set the path to the sender's private key with password. Default pass is "12345", in case you don't specify password.
$gobuy->setSenderPrivateKey($root."app/path/to/sender/private_key.pem", "12345");

// Or
// Set the password for the sender's private key, then call "setSenderPrivateKey" with only first argument.
$gobuy->setPrivateKeyPassword("12345");

// Optional: Set email headers for the S/MIME message
// Below are optional
$gobuy->setCMSEncoding( OPENSSL_ENCODING_SMIME );
$gobuy->setCMSCipherAlgo( OPENSSL_CIPHER_AES_128_CBC );

$gobuy->setHeader([
    "From" => "sender@example.com",
    "To" => "recipient@example.com",
    "Subject" => "Signed Data"
]);
```

Choosing Between .pem, .crt, and .key extensions for data storage
-----------------------------------------------------------------

[](#choosing-between-pem-crt-and-key-extensions-for-data-storage)

- **PEM**: If you need a flexible format that can handle different types of cryptographic data (certificates, private keys, public keys), `.pem` is often the best choice. It is commonly used in various applications because it can store different types of data.
- **CRT**: Use `.crt` when you specifically need to store a public certificate. This format is clear and unambiguous for distributing public certificates.
- **KEY**: Use `.key` when you need to store private keys separately from other data types. This helps in maintaining security and clarity, as the file is specifically understood to contain only private keys.

Example of File Content:
------------------------

[](#example-of-file-content)

- **.pem**:

    ```
    -----BEGIN CERTIFICATE-----
    MIIC+zCCAeOgAwIBAgIJAL3QkuepS6UnMA0GCSqGSIb3DQEBCwUAMIGVMQswCQYD
    ...
    -----END CERTIFICATE-----

    ```
- **.crt**:

    ```
    -----BEGIN CERTIFICATE-----
    MIIC+zCCAeOgAwIBAgIJAL3QkuepS6UnMA0GCSqGSIb3DQEBCwUAMIGVMQswCQYD
    ...
    -----END CERTIFICATE-----

    ```
- **.key**:

    ```
    -----BEGIN RSA PRIVATE KEY-----
    MIIEpAIBAAKCAQEA1zC3qv2upZ5F+3OofOw8uAL5Do2RWPMJv/mh2u83hRxgpT7W
    ...
    -----END RSA PRIVATE KEY-----

    ```

Best Practices
--------------

[](#best-practices)

- Use `.pem` files for flexibility when you need to handle multiple types of cryptographic data.
- Use `.crt` files for clarity when distributing public certificates.
- Use `.key` files to securely store and manage private keys separately.

In case you are new to this and don't know how to get a key and self-signed certificate for both the sender and receiver, follow the below to quickly acquire them:

```
$out = $gobuy->createPrivateKey( sprintf( "%sapp/Output/private_key.pem", $root ) );
```

Generates a private RSA key in PEM format and saves it to your `.pem` file. Returns the contents of the certificate.

```
$out = $gobuy->createPublicKey( sprintf( "%sapp/Output/private_key.pem", $root ),
                sprintf( "%sapp/Output/public_key.pem", $root ) );
```

```
```

Extracts the public key from the private key and saves it to your specified file.

```
$out = $gobuy->createCSR( sprintf( "%spath/to//private_key.pem", $root ),
                sprintf( "%sapp/Output/crs.pem", $root ),
                sprintf( "%spath/to/openssl.cnf", $root ) );
```

Where `openssl.cnf` should look something like below:

```
[ req ]
default_bits       = 2048
default_md         = sha256
default_keyfile    = private.pem
prompt             = no
encrypt_key        = no

# distinguished_name section
distinguished_name = req_distinguished_name

# attributes section
attributes = req_attributes

# x509 extensions section
x509_extensions = v3_req

[ req_distinguished_name ]
countryName            = DE
stateOrProvinceName    = Hessen
localityName           = Frankfurt
organizationName       = GoBuy
organizationalUnitName = Tech Team
commonName             = www.gobuy.cheap
emailAddress           = info@gobuy.cheap

[ req_attributes ]
challengePassword              = A3D3GHP
unstructuredName               = My Unstructured Name

[ v3_req ]
subjectAltName = @alt_names

[ alt_names ]
DNS.1 = example.com
DNS.2 = www.example.com
```

Explanation of the `openssl.cnf` file Contents
----------------------------------------------

[](#explanation-of-the-opensslcnf-file-contents)

### \[req\] Section

[](#req-section)

```
[ req ]
```

This section defines the settings for the OpenSSL "req" command, which is used to create certificate requests (CSRs).

```
default_bits       = 2048
```

This sets the default key size for the RSA key to 2048 bits. This is a good balance between security and performance.

```
default_md         = sha256
```

This sets the default message digest algorithm to SHA-256. SHA-256 is widely used and provides a good level of security.

```
default_keyfile    = private.pem
```

This specifies the default file name for the private key if one is not provided explicitly. In this case, the key will be named `private.pem`.

```
prompt             = no
```

This option tells OpenSSL not to prompt the user for the distinguished name fields. Instead, it will use the values specified in the configuration file.

```
encrypt_key        = no
```

This option specifies whether the private key should be encrypted. `no` means the private key will not be encrypted. Change to `yes` if you want to encrypt the private key.

### Distinguished Name Section

[](#distinguished-name-section)

```
distinguished_name = req_distinguished_name
```

This specifies the section in the configuration file that contains the distinguished name fields. It refers to the `[req_distinguished_name]` section.

### Attributes Section

[](#attributes-section)

```
attributes = req_attributes
```

This specifies the section in the configuration file that contains optional attributes. It refers to the `[req_attributes]` section.

### X.509 Extensions Section

[](#x509-extensions-section)

```
x509_extensions = v3_req
```

This specifies the section in the configuration file that contains X.509 v3 extensions. It refers to the `[v3_req]` section.

### \[req\_distinguished\_name\] Section

[](#req_distinguished_name-section)

```
[ req_distinguished_name ]
```

This section defines the fields for the distinguished name (DN) that will be included in the certificate request.

```
countryName            = DE
```

The country code, which is a two-letter ISO country code. For example, `DE` for the United States.

```
stateOrProvinceName    = Hessen
```

The full name of the state or province.

```
localityName           = Frankfurt
```

The name of the city or locality.

```
organizationName       = GoBuy
```

The legal name of the organization.

```
organizationalUnitName = Tech Team
```

The name of the organizational unit or department within the organization.

```
commonName             = www.gobuy.cheap
```

The common name (CN), typically the fully qualified domain name (FQDN) of the server or user.

```
emailAddress           = info@gobuy.cheap
```

The email address associated with the certificate request.

### \[req\_attributes\] Section

[](#req_attributes-section)

```
[ req_attributes ]
```

This section defines optional attributes that can be included in the certificate request.

```
challengePassword              = A3D3GHP
```

An optional challenge password that can be used to authenticate certificate revocation requests.

```
unstructuredName               = My Unstructured Name
```

An optional unstructured name that can be used for additional information.

### \[v3\_req\] Section

[](#v3_req-section)

```
[ v3_req ]
```

This section defines the X.509 v3 extensions that can be included in the certificate request.

```
subjectAltName = @alt_names
```

This specifies that the subject alternative names (SANs) should be included in the certificate. It refers to the `[alt_names]` section.

### \[alt\_names\] Section

[](#alt_names-section)

```
[ alt_names ]
```

This section defines the subject alternative names (SANs) that can be included in the certificate.

```
DNS.1 = example.com
```

This specifies the first SAN, which is a DNS name. Here, it is set to `example.com`.

```
DNS.2 = www.example.com
```

This specifies the second SAN, which is a DNS name. Here, it is set to `www.example.com`.

The `openssl.cnf` file is used to configure various aspects of creating a certificate request. The `[req]` section sets general options for the request, such as key size, message digest, and file names. The `[req_distinguished_name]` section specifies the fields for the distinguished name, while the `[req_attributes]` section allows for optional attributes. The `[v3_req]` section is used to include X.509 v3 extensions, such as subject alternative names, which are defined in the `[alt_names]` section. This configuration ensures that the CSR contains all the necessary information in a standardized format.

```
$out = $gobuy->generateSelfSignedCert( sprintf( "%sapp/Output/private_key.pem", $root ),
            sprintf( "%sapp/Output/root_cert.pem", $root ),
                sprintf( "%sapp/Output/openssl.cnf", $root ), $days );
```

Generate self-signed certificate with the above API.

We are securing you with chain of trust. So we generate an intermediate certificate for the `$untrusted_certificates_filename`. This is typically done to provide additional layer of security and also more certificates that will be needed to complete the verification stage.

```
list( $caCert, $caKey, $csr ) = $gobuy->generateCACertAndPrivateKey( $certOutPath,  $keyOutPath,  $csrOutPath); // Self-signed CA certificate needed to sign the intermediates.
```

You may find this CA certificat in a `CA` folder in your outer structure.

```
$dn= array( [
                'countryName' => 'AU',
                'stateOrProvinceName' => 'State',
                'localityName' => 'City',
                'organizationName' => 'Organization',
                'organizationalUnitName' => 'Organizational Unit',
                'commonName' => 'intermediateCA',
                'emailAddress' => 'email@example.com'
            ], [
                'countryName' => 'US',
                'stateOrProvinceName' => 'State',
                //...
            ],
            [
                'countryName' => 'DE',
                'stateOrProvinceName' => 'State',
                //...
            ]
        );
$bundleArr = $gobuy->generateIntermediates( $caCert, $caKey, $dn,  3 );
```

The forth argument is the iteration count - the number of intermediate certificates that will be generate. As you increase, you monitor power consumpption and CPU performance. Also monitor memory usage. The length of `$dn` array must match the iteration count or an error is thrown.

```
$intermediatCert = $gobuy->getInterCert( $bundleArr );
$intermediatePrivateKey = $gobuy->getInterKey( $bundleArr );
```

With the above two methods, you get the last intermediate certificate in the bundle and its respective key. These are necessary for signing/creating the end-entity (sender) certificate

```
// Now the end entity's certificate can be created. End entity is also the sender. The sender needs to submit a Certificate Signing Request (CSR) for a certificate to be issued to them.
$days = 365; // How long the certificate will be valid. You can increase this further
$serial = rand(); // The serial number of issued certificate. If not specified it will default to 0.
$gobuy->endEntityCertPath = $gobuy->root."app/endEntityCert.pem"; // endEntity is same as sender
list( $endEntityCert, $endEntityCertPath ) = $gobuy->signEndEntityCert( "path/to/stored/end_entity/csr.pem",
                                $intermediatCert, $intermediatePrivateKey,
                                  $days, $serial );
```

For end entity's CSR, you may use the sender's CSR generated above. The sender certificate will look something like below. This is a PEM format.

```
-----BEGIN CERTIFICATE-----
MIID1DCCArygAwIBAgIEBiKpijANBgkqhkiG9w0BAQsFADCBnDELMAkGA1UEBhMC
VVMxDjAMBgNVBAgMBVN0YXRlMQ0wCwYDVQQHDARDaXR5MRUwEwYDVQQKDAxPcmdh
bml6YXRpb24xHDAaBgNVBAsME09yZ2FuaXphdGlvbmFsIFVuaXQxFzAVBgNVBAMM
DmludGVybWVkaWF0ZUN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tPknmwSL4H2zUK7FzbZRK+OkfvFLgNO1mb
kfNwUfGUxzkIpYd2s4k8NbuZzrlHzPFe
-----END CERTIFICATE-----
```

Cascading intermediate certificate
----------------------------------

[](#cascading-intermediate-certificate)

```
$gobuy->cascadeUntrustedCertificate( $bundleArr[0], "path/to/store/concatenated_cert.pem" );
```

### output

[](#output)

The output will look like so:

```
-----BEGIN CERTIFICATE-----
MIIDwzCCAqugAwIBAgIEKy4j1jANBgkqhkiG9w0BAQsFADBVMQ4wDAYDVQQDDAVN
eSBDQTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM
GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDA2MjIwOTMyNTFaFw0yNTA2
MjIwOTMyNTFaMIGcMQswCQYDVQQGEwJVUzEOMAwGA1UECAwFU3RhdGUxDTALBgNV
BAcMBENpdHkxFTATBgNVBAoMDE9yZ2FuaXphdGlvbjEcMBoGA1UECwwTT3JnYW5p
emF0aW9uYWwgVW5pdDEXMBUGA1UEAwwOaW50ZXJtZWRpYXRlQ0ExIDAeBgkqhkiG
9w0BCQEWEWVtYWlsQGV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAxjZkwvojmHy0248+BqPCrKYt7BbsKAQ9NcdUh0vjvDST8sjIC0Hp
z3xpMUa8j4M3akeiUyGzO/vVapNQWEhll5yMgf5YcKsaDLE6Ia8syBud+QwY4QKA
H/cDtfU+No2ciBaO9mmLQb93SnVJC6ugSf69psrSruxqp9aZXBZiUHRqy1I7+zVZ
DiKdeb30GFg44KN8sJojvgq8Rsp3htxfq+uv7NStQqux8G+YGzB8GKhwuzlLkxPc
GfKNL9w7imftCpo4o8+y31Y6O7BzFPPb/BRe/UqJJ0xTFRhzZMdh8OFEFzAuLEP7
2XAgOj09utbcpD8Zgc0uTJK9cGv5nQ5KrwIDAQABo1MwUTAdBgNVHQ4EFgQUBb5J
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MBoGA1UECwwTT3JnYW5p
emF0aW9uYWwgVW5pdDEXMBUGA1UEAwwOaW50ZXJtZWRpYXRlQ0ExIDAeBgkqhkiG
9w0BCQEWEWVtYWlsQGV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAr4ZLkUn25bRoyh4pOyfEWJI34hfa4oMEJAyLkdljekEURMN5wk12
KH3nckqaoXl51s3jaExvrqkkfOydg7P6tP5xiaQI96j9G+8KsFVcn6WcHIghIQbs
RyjVieZpZWscKVrYWIxMQnfX0pIlTAWzS/S24qv19g1zBgzuGpsUMQUgcLe9Qepu
+YLHHAUpWfpaKztrNuBST3tNXnWQO2Kcj5zwAwFYP4GPg5ka7dv9BPT5gT0YVc51
iPpspXwisE3Zy2S3IpvH3q4AZWQPb1/Oh7jKED1aceevUKysWtNRF5ic9yD1LF/M
zl1ZIngzmQpPJrjKYi8qwPi5qN2ZU/LLSQIDAQABo1MwUTAdBgNVHQ4EFgQUkn35
fx64ludckSCrrkhFma9TKRQwHwYDVR0jBBgwFoAUu9zlf1GvYr906Fu0/JfyfIel
8XAwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAgWL0FeW85J/D
190YTX1ZjFV2T2YRhy9Q3cdbqJllgL4ejjP5ihQvp/+1yGDS+mJ4iPXa435VmQAM
r+drL5vn8f+1b9dnMKL56ReE/uVkPIw6uI5+L+6IxwAb2tROH4ZFFO9L57nCXAXe
2F5MVWMJLBkhETk8Y/HsSZ1dREn/ukBUhrt8NMYXUeWLw7+URW3hK2jI8lN0hKx+
rN+T6ZesidS+XsUDIO2OLdHrYyu7amm5j/vzQxvmceHShZVTC25xPKBaNyviBUzZ
6XoyZMQ9MlCUmMDls8ev1ec0OHKLBDc+LN5/CvgDuW3DS1ffpUf9zoC4qZbHkroG
qP2eCOA24g==
-----END CERTIFICATE-----

```

The above stage is necessary to bundle all the intermediate certificates you have generated. This bundling plays a great roll during signature verification. The client wants as much information as possible, if trust will be estalished.

```
// set $untrusted_certificates_filename. This is needed to verify the sender's signature.
$gobuy->setUntrustedCertificatesFilename( "path/to/concatenated_cert.pem" );
```

```
$gobuy->createCertChain(sprintf( "%sapp/CMS/concatenated_cert.pem", $root ),
        sprintf( "%sCA/ca.crt", $root ),
                        sprintf( "%sapp/Output/chain.pem", $root ) );
```

Remember: in the context of OpenSSL and certificates, the term "bundle" can refer to different types of certificate collections depending on the specific context and use case. Here's a detailed explanation:

### Types of Certificate Bundles

[](#types-of-certificate-bundles)

1. **Cascaded Intermediate Certificates**

    - This refers to a collection of intermediate certificates (`concatenated_cert.pem`) that form a bundle from the first-signed intermediate certificate by the root CA certificate up to the last intermediate certificate. The "leaf" certificate is not included, that is: `intermediate1.pem + intermediate2.pem + intermediate3.pem ...`. Do not include the end-entity certificate in this bundle, unless in the case of Nginx configuration where for `ssl_certificate` you may concatenate end-entity and an already existing bundle of intermediates: `cat server_certificate.crt intermediate_bundle.crt > chain.crt`.
    - It is often used in scenarios where you want to present the chain of trust without including the root CA, which is typically already trusted by the recipient.
2. **Certificate Chain**

    - This includes both the cascaded intermediate certificates and the root CA certificate.
    - This full chain is often used in scenarios where you need to ensure the complete chain of trust is presented, including the root CA, especially when the root CA might not be pre-installed or trusted by default by the recipient.

Usage Contexts
--------------

[](#usage-contexts)

### Only Cascaded Intermediate Certificates

[](#only-cascaded-intermediate-certificates)

1. **Web Servers (e.g., Apache, Nginx)**

    - When configuring a web server, you usually provide the server (end-entity) certificate along with the intermediate certificates in a bundle. The root CA is not included because browsers and operating systems already have a store of trusted root CA certificates.
    - Example: ```
        SSLCertificateFile /path/to/your_server_certificate.crt
        SSLCertificateChainFile /path/to/your_intermediate_certificates_bundle.crt
        ```
2. **Client Certificate Authentication**

    - In some client authentication setups, only the intermediate certificates are needed to verify the client's certificate, assuming the root CA is already trusted by the server.

#### Certificate Chain (Including Root CA)

[](#certificate-chain-including-root-ca)

1. **Email (S/MIME)**

    - When sending an S/MIME signed email, including the full chain (intermediates + root) ensures the recipient's email client can validate the entire chain of trust, especially if the root CA is not already trusted.
2. **Mobile Devices and Embedded Systems**

    - These devices may not have a comprehensive set of trusted root certificates installed. Including the full chain ensures the certificate can be validated without relying on the device's existing trust store.
3. **Certificate Installation on Some Systems**

    - Some systems, especially older or less common ones, may require the full chain, including the root CA, to be presented during installation or validation processes.

### in Summary

[](#in-summary)

- **Cascaded Intermediate Certificates**: Used when the root CA is assumed to be already trusted, such as in web server configurations.
- **Certificate Chain (Including Root CA)**: Used when the full chain of trust needs to be presented, such as in email communications, mobile devices, and some specific systems where the root CA might not be pre-installed or trusted by default.

By understanding these distinctions and usage contexts, you can ensure proper handling and presentation of certificate bundles in your applications and systems.

### Optionals

[](#optionals)

Below are optional. You may set them before signing your data:

```
$gobuy->setCMSFlag( OPENSSL_CMS_BINARY );
$gobuy->setCMSEncoding( OPENSSL_ENCODING_SMIME );
$gobuy->setHeader([
    "From" => "sender@example.com",
    "To" => "recipient@example.com",
    "Subject" => "Signed Data"
]);
```

To encrypt a file
-----------------

[](#to-encrypt-a-file)

```
// Set the output filename where the CMS signed data will be saved
$gobuy->setCMSOutputFilename($root."app/path/to/store/signed_data.cms");

// Here you must have invoked the setters like above
if ( $gobuy->cmsSign( $endEntityCert ) ) {
// This scope means a digital signature was established successfully.
$data = $gobuy->getCMSSigned(); // Get signed certificate data;

// Preparing for encryption
// Set the output filename where the CMS. encrypted data will be saved
$gobuy->setCMSEncryptedOutput( $root."app/path/to/encrypted_data.cms" );
// Set the path to recipient's certificate.
$gobuy->setRecipientCertPath( $root."app/path/to/recievers/certificate.pem" );

// Optional
$gobuy->setCMSCipherAlgo( OPENSSL_CIPHER_AES_128_CBC );

// Encrypt the signed data using CMS.
if ($gobuy->cmsEncrypt($root."path/to/signed_data.cms") ) {

$gobuy->output( $gobuy->getCMSEncrypted(), "Original" );

}

} else {
throw new \Exception( "Signing failed: " . openssl_error_string() );
}
```

Signed data will look something like below. This signature can still be detached from the main message to have them staying separately.

```
MIME-Version: 1.0
Content-Disposition: attachment; filename="smime.p7m"
Content-Type: application/pkcs7-mime; smime-type=signed-data; name="smime.p7m"
Content-Transfer-Encoding: base64

MIISsQYJKoZIhvcNAQcCoIISojCCEp4CAQExDTALBglghkgBZQMEAgEwDwYJKoZI
hvcNAQcBoAIEAKCCD70wggPDMIICq6ADAgECAgR5nsLKMA0GCSqGSIb3DQEBCwUA
MFUxDjAMBgNVBAMMBU15IENBMQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1T
dGF0ZTEhMB8GA1UECgwYSW50ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMB4XDTI0MDcx
MzE2NTExMVoXDTI1MDcxMzE2NTExMVowgZwxCzAJBgNVBAYTAlVTMQ4wDAYDVQQI
DAVTdGF0ZTENMAsGA1UEBwwEQ2l0eTEVMBMGA1UECgwMT3JnYW5pemF0aW9uMRww
GgYDVQQLDBNPcmdhbml6YXRpb25hbCBVbml0MRcwFQYDVQQDDA5pbnRlcm1lZGlh
dGVDQTEgMB4GCSqGSIb3DQEJARYRZW1haWxAZXhhbXBsZS5jb20wggEiMA0GCSqG
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2a8s1ckl1dt5lygY50fMYQMArwpWsjdxv
RAbq1JtoHTo9Elc9Bcf4RpSmna3UFlYY8DmQHVPiL6h0OZ9QkxoFQMdJDes/O3rW
kPvrZNJWrF/JGCAeukHUXJ6duWkMnmfXW+4fsnO4Z4tscbug6++B5CSzVi9I+/QD
knCEt/JTTLPEUtd+nMtYBUStHcEgDxMhajvbAvy364TrD6l4uZ3lEuE8iIeQYMeq
rYJJEwgb/DLNktiz1MrG/JP+6REDV+UOib7dRimaiFqNBiUNJQnyaQInTNPQ2nH+

....
```

The header is used to define how the message should be processed, interpreted, and handled by email clients and other software that can read S/MIME (Secure/Multipurpose Internet Mail Extensions) messages.

### 1. MIME-Version: 1.0

[](#1-mime-version-10)

- **Purpose**: This indicates that the message is formatted according to the MIME standard, version 1.0. MIME (Multipurpose Internet Mail Extensions) is a standard that allows for the inclusion of various content types, such as text, images, and other media types, in email.

### 2. Content-Disposition: attachment; filename="smime.p7m"

[](#2-content-disposition-attachment-filenamesmimep7m)

- **Purpose**: This header suggests how the content should be presented to the user.
    - `attachment` means that the content should be presented as a downloadable file rather than inline within the email body.
    - `filename="smime.p7m"` indicates the name of the file attachment, which is commonly used for S/MIME encrypted messages.

### 3. Content-Type: application/pkcs7-mime; smime-type=enveloped-data; name="smime.p7m"

[](#3-content-type-applicationpkcs7-mime-smime-typeenveloped-data-namesmimep7m)

- **Purpose**: This header specifies the MIME type of the content.
    - `application/pkcs7-mime` indicates that the content is a PKCS #7 MIME, which is used for S/MIME messages.
    - `smime-type=enveloped-data` specifies that the message is encrypted (enveloped data) as opposed to being signed or containing other S/MIME data types.
    - `name="smime.p7m"` is another way to indicate the filename associated with this MIME part.

### 4. Content-Transfer-Encoding: base64

[](#4-content-transfer-encoding-base64)

- **Purpose**: This header specifies the encoding used to safely transmit the binary content over protocols that are designed to handle text, such as SMTP (Simple Mail Transfer Protocol) for email.
    - `base64` means that the binary content of the encrypted message has been encoded in base64, which ensures that it remains intact during transmission.

### Putting It All Together

[](#putting-it-all-together)

These headers collectively ensure that:

1. The message is recognized as a MIME message by email clients.
2. The content is treated as an attachment and saved with the specified filename.
3. The email client knows that the attachment is an encrypted S/MIME message.
4. The email client decodes the base64 content back into its original binary form before processing it.

### Usage in S/MIME

[](#usage-in-smime)

S/MIME uses these headers to facilitate secure email communication by allowing messages to be encrypted, signed, or both. Encrypted messages ensure confidentiality, meaning that only the intended recipient can decrypt and read the message. When combined with signing, it also provides authentication and integrity, ensuring the message has not been tampered with and verifying the sender's identity.

In summary, these headers are crucial for ensuring the proper handling of S/MIME encrypted messages, providing clear instructions to email clients on how to process and display the message content.

Padding
-------

[](#padding)

We will effortlessly pad your encrypted data. This stage is well recommended to give you more complex structure and randomness. This is to make the encrypted more resistant to brute force attack, and other attacks that exploit the simplicity of cryptographic cipher texts.

```
$padded = $gobuy->paddCMSEncrypted( $strongKey ); // Pad the encrypted data before sending (recommended)
```

```
@inject('gobuy', 'App\Services\GoBuy')
// Blade
@php
    $gobuy->unPadCMSEncrypted( $padded, $strongKey ); // unpad the padded encrypted data before the decryption stage.
@endphp
```

Where GoBuy Service class is as below:

```
