<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

class CCGAL_Encryption {

	private static function get_key() {
		$key = defined( 'AUTH_KEY' ) ? AUTH_KEY : '';
		$key .= defined( 'SECURE_AUTH_KEY' ) ? SECURE_AUTH_KEY : '';
		if ( empty( $key ) ) {
			$key = wp_salt( 'auth' );
		}
		return hash( 'sha256', $key, true );
	}

	public static function encrypt( $plaintext ) {
		if ( ! function_exists( 'openssl_encrypt' ) ) {
			return '';
		}

		$key    = self::get_key();
		$iv_len = openssl_cipher_iv_length( 'aes-256-cbc' );
		$iv     = openssl_random_pseudo_bytes( $iv_len );
		$cipher = openssl_encrypt( $plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );

		if ( false === $cipher ) {
			return '';
		}

		return base64_encode( $iv . $cipher );
	}

	public static function decrypt( $ciphertext ) {
		if ( empty( $ciphertext ) ) {
			return '';
		}

		if ( ! function_exists( 'openssl_decrypt' ) ) {
			return '';
		}

		$data = base64_decode( $ciphertext, true );
		if ( false === $data ) {
			return '';
		}

		$iv_len = openssl_cipher_iv_length( 'aes-256-cbc' );
		if ( strlen( $data ) < $iv_len ) {
			return '';
		}

		$iv     = substr( $data, 0, $iv_len );
		$cipher = substr( $data, $iv_len );
		$key    = self::get_key();

		$plain = openssl_decrypt( $cipher, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv );
		return ( false === $plain ) ? '' : $plain;
	}
}
