Kotchasan Framework Documentation

Kotchasan Framework Documentation

Password Class - Security Management

EN 03 Feb 2026 16:41

Password Class - Security Management

The Password class provides methods for Encryption, Decryption, Digital Signatures, and Unique ID generation.

Namespace

Kotchasan\Password

Security Features

  • Uses AES-256-CBC for encode/decode
  • Uses HMAC-SHA256 for generateSign
  • Uses OpenSSL or random_bytes for secure random generation

Public Methods (4 methods)

encode()

Encrypt a string

public static function encode(string $string, string $password): string

Parameters:

  • $string - String to encrypt
  • $password - Encryption key

Returns: Encrypted string (Base64 encoded)

Example:

use Kotchasan\Password;

$secret = 'MySecretMessage';
$key = 'my-secret-key';
$encrypted = Password::encode($secret, $key);
// Result: Encrypted string (e.g., "U2FsdGVkX1...")

decode()

Decrypt a string

public static function decode(string $string, string $password): string

Parameters:

  • $string - Encrypted string (from encode())
  • $password - Encryption key used

Returns: Original string

Exceptions:

  • Exception - If decryption fails or data is invalid

Example:

try {
    $decrypted = Password::decode($encrypted, $key);
    echo $decrypted; // "MySecretMessage"
} catch (\Exception $e) {
    echo "Decryption failed: " . $e->getMessage();
}

generateSign()

Generate Signature for API Authentication

public static function generateSign(array $params, string $secret): string

Parameters:

  • $params - Array of parameters
  • $secret - Secret Key

Returns: Signature string (Uppercase SHA-256 HMAC)

Mechanic:

  1. Sorts parameters by key (ksort)
  2. Creates query string (http_build_query)
  3. Hashes with HMAC-SHA256
  4. Converts to uppercase

Example:

$params = [
    'id' => 123,
    'timestamp' => 1630000000,
    'action' => 'update'
];
$secret = 'api_secret_key';

$sign = Password::generateSign($params, $secret);
// Use sign to verify request integrity

uniqid()

Generate Secure Random String

public static function uniqid(int $length = 13): string

Parameters:

  • $length - Desired length (default 13)

Returns: Random hexadecimal string

Example:

// Generate 13-char token
$token = Password::uniqid();

// Generate 32-char ID
$id = Password::uniqid(32);

Complete Usage Examples

1. Secure Data Storage

Encrypting sensitive data before database storage

use Kotchasan\Password;

class SecureStorage
{
    private $key = 'app-secret-key-123';

    public function saveSensitiveData($userId, $data)
    {
        // Encrypt first
        $encrypted = Password::encode($data, $this->key);

        // Save to DB
        $db->insert('user_secrets', [
            'user_id' => $userId,
            'data' => $encrypted
        ]);
    }

    public function getSensitiveData($userId)
    {
        $record = $db->find($userId);

        try {
            // Decrypt for use
            return Password::decode($record->data, $this->key);
        } catch (\Exception $e) {
            return null;
        }
    }
}

2. API Authentication

Verifying API requests with signatures

use Kotchasan\Password;

class ApiController
{
    private $apiSecret = 'my-api-secret';

    public function handleRequest($requestParams)
    {
        // Extract client signature
        $clientSign = $requestParams['sign'];
        unset($requestParams['sign']);

        // Generate server signature to verify
        $serverSign = Password::generateSign($requestParams, $this->apiSecret);

        if ($clientSign !== $serverSign) {
            throw new \Exception('Invalid Signature');
        }

        // Valid signature - proceed
        return "Success";
    }
}

3. Token Generation

Creating CSRF tokens or Session IDs

use Kotchasan\Password;

class TokenManager
{
    public static function createCsrfToken()
    {
        if (empty($_SESSION['csrf_token'])) {
            // Generate 32-char token
            $_SESSION['csrf_token'] = Password::uniqid(32);
        }
        return $_SESSION['csrf_token'];
    }

    public static function verifyCsrfToken($token)
    {
        return isset($_SESSION['csrf_token']) &&
               hash_equals($_SESSION['csrf_token'], $token);
    }
}

Creating secure time-limited links

use Kotchasan\Password;

class ResetPassword
{
    private $appKey = 'secure-app-key';

    public function createLink($email)
    {
        // Combine data and timestamp
        $data = json_encode([
            'email' => $email,
            'expire' => time() + 3600 // 1 hour
        ]);

        // Encrypt
        $token = Password::encode($data, $this->appKey);

        // Create URL (urlencode needed due to base64 chars)
        return "https://site.com/reset?token=" . urlencode($token);
    }

    public function verifyToken($token)
    {
        try {
            $json = Password::decode($token, $this->appKey);
            $data = json_decode($json);

            if ($data->expire < time()) {
                return "Token expired";
            }

            return $data->email; // Valid
        } catch (\Exception $e) {
            return "Invalid token";
        }
    }
}

Important Notes

  1. Key Management: Security depends on protecting the $password or $secret. Never expose or commit keys to public repositories.
  2. Encryption Method: Uses AES-256-CBC which requires an IV (Initialization Vector). The class handles IV generation and storage automatically (prepended to output).
  3. Exceptions: The decode method throws an Exception if data is invalid. Always wrap calls in a try-catch block.

Summary

The Password class is essential for security implementation:

  • Encryption: AES-256-CBC (High security)
  • API Security: HMAC Signature
  • Randomness: Cryptographically secure random bytes
  • 🔒 Integrity: Built-in validation

Suitable for:

  • Sensitive data storage
  • API Authentication
  • Token Generation
  • Secure Links

File Size: 93 lines
Public Methods: 4 methods
Pattern: Static utility class