Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JWE AES-256-GCM encoding #5

Open
Nemo64 opened this issue Dec 2, 2021 · 0 comments
Open

JWE AES-256-GCM encoding #5

Nemo64 opened this issue Dec 2, 2021 · 0 comments

Comments

@Nemo64
Copy link

Nemo64 commented Dec 2, 2021

I had a situation where I got a JWE object from an external source that used A256GCM encoding.

Most other php libraries had trouble even reading my private key, and since this here is using openssl directly, it could. But the encoding was unknown.
So I digged a bit and managed to add decoding support.

$context = (new DefaultContextFactory())->get();
$context->jweEncryptions()->add('A256GCM', new AESGCM(256));
class AESGCM implements JweEncryption
{
    private $keySize;

    public function __construct(int $keySize)
    {
        $this->keySize = $keySize;
    }

    public function getKeySize()
    {
        return $this->keySize;
    }

    private function getIVSize()
    {
        return 96;
    }

    public function encrypt($aad, $plainText, $cek)
    {
    }

    public function decrypt($aad, $cek, $iv, $cipherText, $authTag)
    {
        if (strlen($cek) !== $this->getKeySize() / 8) {
            throw new JoseJwtException('Incorrect key length ' . strlen($cek));
        }

        if (strlen($iv) !== $this->getIVSize() / 8) {
            throw new JoseJwtException('Incorrect IV length ' . strlen($iv));
        }

        if (strlen($authTag) !== 16) {
            throw new JoseJwtException('Incorrect authentication tag length ' . strlen($authTag));
        }

        $plaintext = openssl_decrypt($cipherText, "aes-$this->keySize-gcm", $cek, OPENSSL_RAW_DATA, $iv, $authTag, $aad);
        if ($plaintext === false) {
            throw new JoseJwtException('Authentication tag does not match: ' . openssl_error_string());
        }

        return $plaintext;
    }
}

It's probably pretty easy to go from there but I don't have time to write tests and am happy enough that it works at all.
Maybe it'll help someone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant