brianbak.dk

brianbak.dk

profile-pic
Ipsum
Kryptéring og Dekryptéring

Kryptér og dekryptér tekster med SODIUM CRYPTO

Januar 12, 2019



Nulstil


PHP eksempel


private function getKeyFromPassword($password, $keysize = 32)
{
    return hash_pbkdf2(
        'sha256',
        $password,
        "MegetHemmeligSalt", // salt
        100000, // Antal iterationer
        $keysize,
        true
    );
}

public function encryptString(string $message, string $key): string
{
    $key = $this->getKeyFromPassword($key);
    if (mb_strlen($key, '8bit') !== SODIUM_CRYPTO_SECRETBOX_KEYBYTES) {
        throw new \RangeException('Key is not the correct size (must be 32 bytes).');
    }
    $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);

    $cipher = base64_encode(
        $nonce.
        sodium_crypto_secretbox(
            $message,
            $nonce,
            $key
        )
    );
    sodium_memzero($message);
    sodium_memzero($key);
    return $cipher;
}

public function decryptString(string $encrypted, string $key): string
{   
    $key = $this->getKeyFromPassword($key);
    $decoded = base64_decode($encrypted);
    $nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
    $ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

    $plain = sodium_crypto_secretbox_open(
        $ciphertext,
        $nonce,
        $key
    );
    if (!is_string($plain)) {
        $plain = "Kunne ikke dekryptere med den valgte nøgle";
    }
    sodium_memzero($ciphertext);
    sodium_memzero($key);
    return $plain;
}