OAUTH SUPPORT
This commit is contained in:
Vendored
+1
@@ -25,6 +25,7 @@ return array(
|
||||
'253c157292f75eb38082b5acb06f3f01' => $vendorDir . '/nikic/fast-route/src/functions.php',
|
||||
'2df68f9e79c919e2d88506611769ed2e' => $vendorDir . '/respect/stringifier/src/stringify.php',
|
||||
'ef65a1626449d89d0811cf9befce46f0' => $vendorDir . '/illuminate/events/functions.php',
|
||||
'3109cb1a231dcd04bee1f9f620d46975' => $vendorDir . '/paragonie/sodium_compat/autoload.php',
|
||||
'667aeda72477189d0494fecd327c3641' => $vendorDir . '/symfony/var-dumper/Resources/functions/dump.php',
|
||||
'da5b71a9ad8465d48da441e2f36823b6' => $baseDir . '/support/helpers.php',
|
||||
);
|
||||
|
||||
Vendored
+3
-2
@@ -41,7 +41,7 @@ return array(
|
||||
'Respect\\Stringifier\\' => array($vendorDir . '/respect/stringifier/src'),
|
||||
'Psr\\SimpleCache\\' => array($vendorDir . '/psr/simple-cache/src'),
|
||||
'Psr\\Log\\' => array($vendorDir . '/psr/log/src'),
|
||||
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-message/src', $vendorDir . '/psr/http-factory/src'),
|
||||
'Psr\\Http\\Message\\' => array($vendorDir . '/psr/http-factory/src', $vendorDir . '/psr/http-message/src'),
|
||||
'Psr\\Http\\Client\\' => array($vendorDir . '/psr/http-client/src'),
|
||||
'Psr\\Container\\' => array($vendorDir . '/psr/container/src'),
|
||||
'Psr\\Clock\\' => array($vendorDir . '/psr/clock/src'),
|
||||
@@ -49,7 +49,7 @@ return array(
|
||||
'PhpOption\\' => array($vendorDir . '/phpoption/phpoption/src/PhpOption'),
|
||||
'Phinx\\' => array($vendorDir . '/robmorgan/phinx/src/Phinx'),
|
||||
'Monolog\\' => array($vendorDir . '/monolog/monolog/src/Monolog'),
|
||||
'Illuminate\\Support\\' => array($vendorDir . '/illuminate/macroable', $vendorDir . '/illuminate/conditionable', $vendorDir . '/illuminate/collections', $vendorDir . '/illuminate/support'),
|
||||
'Illuminate\\Support\\' => array($vendorDir . '/illuminate/collections', $vendorDir . '/illuminate/conditionable', $vendorDir . '/illuminate/macroable', $vendorDir . '/illuminate/support'),
|
||||
'Illuminate\\Redis\\' => array($vendorDir . '/illuminate/redis'),
|
||||
'Illuminate\\Pipeline\\' => array($vendorDir . '/illuminate/pipeline'),
|
||||
'Illuminate\\Pagination\\' => array($vendorDir . '/illuminate/pagination'),
|
||||
@@ -62,6 +62,7 @@ return array(
|
||||
'GuzzleHttp\\Promise\\' => array($vendorDir . '/guzzlehttp/promises/src'),
|
||||
'GuzzleHttp\\' => array($vendorDir . '/guzzlehttp/guzzle/src'),
|
||||
'GrahamCampbell\\ResultType\\' => array($vendorDir . '/graham-campbell/result-type/src'),
|
||||
'Firebase\\JWT\\' => array($vendorDir . '/firebase/php-jwt/src'),
|
||||
'FastRoute\\' => array($vendorDir . '/nikic/fast-route/src'),
|
||||
'Dotenv\\' => array($vendorDir . '/vlucas/phpdotenv/src'),
|
||||
'Doctrine\\Inflector\\' => array($vendorDir . '/doctrine/inflector/lib/Doctrine/Inflector'),
|
||||
|
||||
Vendored
+10
-4
@@ -26,6 +26,7 @@ class ComposerStaticInitd3b2156d13053c4f5c49b090883e3785
|
||||
'253c157292f75eb38082b5acb06f3f01' => __DIR__ . '/..' . '/nikic/fast-route/src/functions.php',
|
||||
'2df68f9e79c919e2d88506611769ed2e' => __DIR__ . '/..' . '/respect/stringifier/src/stringify.php',
|
||||
'ef65a1626449d89d0811cf9befce46f0' => __DIR__ . '/..' . '/illuminate/events/functions.php',
|
||||
'3109cb1a231dcd04bee1f9f620d46975' => __DIR__ . '/..' . '/paragonie/sodium_compat/autoload.php',
|
||||
'667aeda72477189d0494fecd327c3641' => __DIR__ . '/..' . '/symfony/var-dumper/Resources/functions/dump.php',
|
||||
'da5b71a9ad8465d48da441e2f36823b6' => __DIR__ . '/../..' . '/support/helpers.php',
|
||||
);
|
||||
@@ -122,6 +123,7 @@ class ComposerStaticInitd3b2156d13053c4f5c49b090883e3785
|
||||
),
|
||||
'F' =>
|
||||
array (
|
||||
'Firebase\\JWT\\' => 13,
|
||||
'FastRoute\\' => 10,
|
||||
),
|
||||
'D' =>
|
||||
@@ -291,8 +293,8 @@ class ComposerStaticInitd3b2156d13053c4f5c49b090883e3785
|
||||
),
|
||||
'Psr\\Http\\Message\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/psr/http-message/src',
|
||||
1 => __DIR__ . '/..' . '/psr/http-factory/src',
|
||||
0 => __DIR__ . '/..' . '/psr/http-factory/src',
|
||||
1 => __DIR__ . '/..' . '/psr/http-message/src',
|
||||
),
|
||||
'Psr\\Http\\Client\\' =>
|
||||
array (
|
||||
@@ -324,9 +326,9 @@ class ComposerStaticInitd3b2156d13053c4f5c49b090883e3785
|
||||
),
|
||||
'Illuminate\\Support\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/illuminate/macroable',
|
||||
0 => __DIR__ . '/..' . '/illuminate/collections',
|
||||
1 => __DIR__ . '/..' . '/illuminate/conditionable',
|
||||
2 => __DIR__ . '/..' . '/illuminate/collections',
|
||||
2 => __DIR__ . '/..' . '/illuminate/macroable',
|
||||
3 => __DIR__ . '/..' . '/illuminate/support',
|
||||
),
|
||||
'Illuminate\\Redis\\' =>
|
||||
@@ -377,6 +379,10 @@ class ComposerStaticInitd3b2156d13053c4f5c49b090883e3785
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/graham-campbell/result-type/src',
|
||||
),
|
||||
'Firebase\\JWT\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/firebase/php-jwt/src',
|
||||
),
|
||||
'FastRoute\\' =>
|
||||
array (
|
||||
0 => __DIR__ . '/..' . '/nikic/fast-route/src',
|
||||
|
||||
Vendored
+226
@@ -511,6 +511,78 @@
|
||||
],
|
||||
"install-path": "../doctrine/inflector"
|
||||
},
|
||||
{
|
||||
"name": "firebase/php-jwt",
|
||||
"version": "v6.10.0",
|
||||
"version_normalized": "6.10.0.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/firebase/php-jwt.git",
|
||||
"reference": "a49db6f0a5033aef5143295342f1c95521b075ff"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/firebase/php-jwt/zipball/a49db6f0a5033aef5143295342f1c95521b075ff",
|
||||
"reference": "a49db6f0a5033aef5143295342f1c95521b075ff",
|
||||
"shasum": "",
|
||||
"mirrors": [
|
||||
{
|
||||
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
|
||||
"preferred": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"require": {
|
||||
"php": "^7.4||^8.0"
|
||||
},
|
||||
"require-dev": {
|
||||
"guzzlehttp/guzzle": "^6.5||^7.4",
|
||||
"phpspec/prophecy-phpunit": "^2.0",
|
||||
"phpunit/phpunit": "^9.5",
|
||||
"psr/cache": "^1.0||^2.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-sodium": "Support EdDSA (Ed25519) signatures",
|
||||
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present"
|
||||
},
|
||||
"time": "2023-12-01T16:26:39+00:00",
|
||||
"type": "library",
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Firebase\\JWT\\": "src"
|
||||
}
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"BSD-3-Clause"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Neuman Vong",
|
||||
"email": "neuman+pear@twilio.com",
|
||||
"role": "Developer"
|
||||
},
|
||||
{
|
||||
"name": "Anant Narayanan",
|
||||
"email": "anant@php.net",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
|
||||
"homepage": "https://github.com/firebase/php-jwt",
|
||||
"keywords": [
|
||||
"jwt",
|
||||
"php"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/firebase/php-jwt/issues",
|
||||
"source": "https://github.com/firebase/php-jwt/tree/v6.10.0"
|
||||
},
|
||||
"install-path": "../firebase/php-jwt"
|
||||
},
|
||||
{
|
||||
"name": "graham-campbell/result-type",
|
||||
"version": "v1.1.2",
|
||||
@@ -2029,6 +2101,160 @@
|
||||
},
|
||||
"install-path": "../nikic/fast-route"
|
||||
},
|
||||
{
|
||||
"name": "paragonie/random_compat",
|
||||
"version": "v9.99.100",
|
||||
"version_normalized": "9.99.100.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/paragonie/random_compat.git",
|
||||
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/paragonie/random_compat/zipball/996434e5492cb4c3edcb9168db6fbb1359ef965a",
|
||||
"reference": "996434e5492cb4c3edcb9168db6fbb1359ef965a",
|
||||
"shasum": "",
|
||||
"mirrors": [
|
||||
{
|
||||
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
|
||||
"preferred": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"require": {
|
||||
"php": ">= 7"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "4.*|5.*",
|
||||
"vimeo/psalm": "^1"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
|
||||
},
|
||||
"time": "2020-10-15T08:29:30+00:00",
|
||||
"type": "library",
|
||||
"installation-source": "dist",
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"MIT"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Paragon Initiative Enterprises",
|
||||
"email": "security@paragonie.com",
|
||||
"homepage": "https://paragonie.com"
|
||||
}
|
||||
],
|
||||
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
|
||||
"keywords": [
|
||||
"csprng",
|
||||
"polyfill",
|
||||
"pseudorandom",
|
||||
"random"
|
||||
],
|
||||
"support": {
|
||||
"email": "info@paragonie.com",
|
||||
"issues": "https://github.com/paragonie/random_compat/issues",
|
||||
"source": "https://github.com/paragonie/random_compat"
|
||||
},
|
||||
"install-path": "../paragonie/random_compat"
|
||||
},
|
||||
{
|
||||
"name": "paragonie/sodium_compat",
|
||||
"version": "v1.21.1",
|
||||
"version_normalized": "1.21.1.0",
|
||||
"source": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/paragonie/sodium_compat.git",
|
||||
"reference": "bb312875dcdd20680419564fe42ba1d9564b9e37"
|
||||
},
|
||||
"dist": {
|
||||
"type": "zip",
|
||||
"url": "https://api.github.com/repos/paragonie/sodium_compat/zipball/bb312875dcdd20680419564fe42ba1d9564b9e37",
|
||||
"reference": "bb312875dcdd20680419564fe42ba1d9564b9e37",
|
||||
"shasum": "",
|
||||
"mirrors": [
|
||||
{
|
||||
"url": "https://mirrors.aliyun.com/composer/dists/%package%/%reference%.%type%",
|
||||
"preferred": true
|
||||
}
|
||||
]
|
||||
},
|
||||
"require": {
|
||||
"paragonie/random_compat": ">=1",
|
||||
"php": "^5.2.4|^5.3|^5.4|^5.5|^5.6|^7|^8"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^3|^4|^5|^6|^7|^8|^9"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-libsodium": "PHP < 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security.",
|
||||
"ext-sodium": "PHP >= 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security."
|
||||
},
|
||||
"time": "2024-04-22T22:05:04+00:00",
|
||||
"type": "library",
|
||||
"installation-source": "dist",
|
||||
"autoload": {
|
||||
"files": [
|
||||
"autoload.php"
|
||||
]
|
||||
},
|
||||
"notification-url": "https://packagist.org/downloads/",
|
||||
"license": [
|
||||
"ISC"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Paragon Initiative Enterprises",
|
||||
"email": "security@paragonie.com"
|
||||
},
|
||||
{
|
||||
"name": "Frank Denis",
|
||||
"email": "jedisct1@pureftpd.org"
|
||||
}
|
||||
],
|
||||
"description": "Pure PHP implementation of libsodium; uses the PHP extension if it exists",
|
||||
"keywords": [
|
||||
"Authentication",
|
||||
"BLAKE2b",
|
||||
"ChaCha20",
|
||||
"ChaCha20-Poly1305",
|
||||
"Chapoly",
|
||||
"Curve25519",
|
||||
"Ed25519",
|
||||
"EdDSA",
|
||||
"Edwards-curve Digital Signature Algorithm",
|
||||
"Elliptic Curve Diffie-Hellman",
|
||||
"Poly1305",
|
||||
"Pure-PHP cryptography",
|
||||
"RFC 7748",
|
||||
"RFC 8032",
|
||||
"Salpoly",
|
||||
"Salsa20",
|
||||
"X25519",
|
||||
"XChaCha20-Poly1305",
|
||||
"XSalsa20-Poly1305",
|
||||
"Xchacha20",
|
||||
"Xsalsa20",
|
||||
"aead",
|
||||
"cryptography",
|
||||
"ecdh",
|
||||
"elliptic curve",
|
||||
"elliptic curve cryptography",
|
||||
"encryption",
|
||||
"libsodium",
|
||||
"php",
|
||||
"public-key cryptography",
|
||||
"secret-key cryptography",
|
||||
"side-channel resistant"
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/paragonie/sodium_compat/issues",
|
||||
"source": "https://github.com/paragonie/sodium_compat/tree/v1.21.1"
|
||||
},
|
||||
"install-path": "../paragonie/sodium_compat"
|
||||
},
|
||||
{
|
||||
"name": "phpoption/phpoption",
|
||||
"version": "1.9.3",
|
||||
|
||||
Vendored
+35
-8
@@ -1,9 +1,9 @@
|
||||
<?php return array(
|
||||
'root' => array(
|
||||
'name' => 'workerman/webman',
|
||||
'pretty_version' => '1.0.0+no-version-set',
|
||||
'version' => '1.0.0.0',
|
||||
'reference' => null,
|
||||
'pretty_version' => 'dev-main',
|
||||
'version' => 'dev-main',
|
||||
'reference' => 'd78b38e80f348db25511c37191ce154edc7ea094',
|
||||
'type' => 'project',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
@@ -73,6 +73,15 @@
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'firebase/php-jwt' => array(
|
||||
'pretty_version' => 'v6.10.0',
|
||||
'version' => '6.10.0.0',
|
||||
'reference' => 'a49db6f0a5033aef5143295342f1c95521b075ff',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../firebase/php-jwt',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'graham-campbell/result-type' => array(
|
||||
'pretty_version' => 'v1.1.2',
|
||||
'version' => '1.1.2.0',
|
||||
@@ -253,6 +262,24 @@
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'paragonie/random_compat' => array(
|
||||
'pretty_version' => 'v9.99.100',
|
||||
'version' => '9.99.100.0',
|
||||
'reference' => '996434e5492cb4c3edcb9168db6fbb1359ef965a',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../paragonie/random_compat',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'paragonie/sodium_compat' => array(
|
||||
'pretty_version' => 'v1.21.1',
|
||||
'version' => '1.21.1.0',
|
||||
'reference' => 'bb312875dcdd20680419564fe42ba1d9564b9e37',
|
||||
'type' => 'library',
|
||||
'install_path' => __DIR__ . '/../paragonie/sodium_compat',
|
||||
'aliases' => array(),
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'phpoption/phpoption' => array(
|
||||
'pretty_version' => '1.9.3',
|
||||
'version' => '1.9.3.0',
|
||||
@@ -365,8 +392,8 @@
|
||||
'psr/log-implementation' => array(
|
||||
'dev_requirement' => false,
|
||||
'provided' => array(
|
||||
0 => '1.0|2.0|3.0',
|
||||
1 => '1.0.0 || 2.0.0 || 3.0.0',
|
||||
0 => '1.0.0 || 2.0.0 || 3.0.0',
|
||||
1 => '1.0|2.0|3.0',
|
||||
),
|
||||
),
|
||||
'psr/simple-cache' => array(
|
||||
@@ -640,9 +667,9 @@
|
||||
'dev_requirement' => false,
|
||||
),
|
||||
'workerman/webman' => array(
|
||||
'pretty_version' => '1.0.0+no-version-set',
|
||||
'version' => '1.0.0.0',
|
||||
'reference' => null,
|
||||
'pretty_version' => 'dev-main',
|
||||
'version' => 'dev-main',
|
||||
'reference' => 'd78b38e80f348db25511c37191ce154edc7ea094',
|
||||
'type' => 'project',
|
||||
'install_path' => __DIR__ . '/../../',
|
||||
'aliases' => array(),
|
||||
|
||||
Vendored
+170
@@ -0,0 +1,170 @@
|
||||
# Changelog
|
||||
|
||||
## [6.10.0](https://github.com/firebase/php-jwt/compare/v6.9.0...v6.10.0) (2023-11-28)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow typ header override ([#546](https://github.com/firebase/php-jwt/issues/546)) ([79cb30b](https://github.com/firebase/php-jwt/commit/79cb30b729a22931b2fbd6b53f20629a83031ba9))
|
||||
|
||||
## [6.9.0](https://github.com/firebase/php-jwt/compare/v6.8.1...v6.9.0) (2023-10-04)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add payload to jwt exception ([#521](https://github.com/firebase/php-jwt/issues/521)) ([175edf9](https://github.com/firebase/php-jwt/commit/175edf958bb61922ec135b2333acf5622f2238a2))
|
||||
|
||||
## [6.8.1](https://github.com/firebase/php-jwt/compare/v6.8.0...v6.8.1) (2023-07-14)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* accept float claims but round down to ignore them ([#492](https://github.com/firebase/php-jwt/issues/492)) ([3936842](https://github.com/firebase/php-jwt/commit/39368423beeaacb3002afa7dcb75baebf204fe7e))
|
||||
* different BeforeValidException messages for nbf and iat ([#526](https://github.com/firebase/php-jwt/issues/526)) ([0a53cf2](https://github.com/firebase/php-jwt/commit/0a53cf2986e45c2bcbf1a269f313ebf56a154ee4))
|
||||
|
||||
## [6.8.0](https://github.com/firebase/php-jwt/compare/v6.7.0...v6.8.0) (2023-06-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for P-384 curve ([#515](https://github.com/firebase/php-jwt/issues/515)) ([5de4323](https://github.com/firebase/php-jwt/commit/5de4323f4baf4d70bca8663bd87682a69c656c3d))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* handle invalid http responses ([#508](https://github.com/firebase/php-jwt/issues/508)) ([91c39c7](https://github.com/firebase/php-jwt/commit/91c39c72b22fc3e1191e574089552c1f2041c718))
|
||||
|
||||
## [6.7.0](https://github.com/firebase/php-jwt/compare/v6.6.0...v6.7.0) (2023-06-14)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add ed25519 support to JWK (public keys) ([#452](https://github.com/firebase/php-jwt/issues/452)) ([e53979a](https://github.com/firebase/php-jwt/commit/e53979abae927de916a75b9d239cfda8ce32be2a))
|
||||
|
||||
## [6.6.0](https://github.com/firebase/php-jwt/compare/v6.5.0...v6.6.0) (2023-06-13)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* allow get headers when decoding token ([#442](https://github.com/firebase/php-jwt/issues/442)) ([fb85f47](https://github.com/firebase/php-jwt/commit/fb85f47cfaeffdd94faf8defdf07164abcdad6c3))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* only check iat if nbf is not used ([#493](https://github.com/firebase/php-jwt/issues/493)) ([398ccd2](https://github.com/firebase/php-jwt/commit/398ccd25ea12fa84b9e4f1085d5ff448c21ec797))
|
||||
|
||||
## [6.5.0](https://github.com/firebase/php-jwt/compare/v6.4.0...v6.5.0) (2023-05-12)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* allow KID of '0' ([#505](https://github.com/firebase/php-jwt/issues/505)) ([9dc46a9](https://github.com/firebase/php-jwt/commit/9dc46a9c3e5801294249cfd2554c5363c9f9326a))
|
||||
|
||||
|
||||
### Miscellaneous Chores
|
||||
|
||||
* drop support for PHP 7.3 ([#495](https://github.com/firebase/php-jwt/issues/495))
|
||||
|
||||
## [6.4.0](https://github.com/firebase/php-jwt/compare/v6.3.2...v6.4.0) (2023-02-08)
|
||||
|
||||
|
||||
### Features
|
||||
|
||||
* add support for W3C ES256K ([#462](https://github.com/firebase/php-jwt/issues/462)) ([213924f](https://github.com/firebase/php-jwt/commit/213924f51936291fbbca99158b11bd4ae56c2c95))
|
||||
* improve caching by only decoding jwks when necessary ([#486](https://github.com/firebase/php-jwt/issues/486)) ([78d3ed1](https://github.com/firebase/php-jwt/commit/78d3ed1073553f7d0bbffa6c2010009a0d483d5c))
|
||||
|
||||
## [6.3.2](https://github.com/firebase/php-jwt/compare/v6.3.1...v6.3.2) (2022-11-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* check kid before using as array index ([bad1b04](https://github.com/firebase/php-jwt/commit/bad1b040d0c736bbf86814c6b5ae614f517cf7bd))
|
||||
|
||||
## [6.3.1](https://github.com/firebase/php-jwt/compare/v6.3.0...v6.3.1) (2022-11-01)
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* casing of GET for PSR compat ([#451](https://github.com/firebase/php-jwt/issues/451)) ([60b52b7](https://github.com/firebase/php-jwt/commit/60b52b71978790eafcf3b95cfbd83db0439e8d22))
|
||||
* string interpolation format for php 8.2 ([#446](https://github.com/firebase/php-jwt/issues/446)) ([2e07d8a](https://github.com/firebase/php-jwt/commit/2e07d8a1524d12b69b110ad649f17461d068b8f2))
|
||||
|
||||
## 6.3.0 / 2022-07-15
|
||||
|
||||
- Added ES256 support to JWK parsing ([#399](https://github.com/firebase/php-jwt/pull/399))
|
||||
- Fixed potential caching error in `CachedKeySet` by caching jwks as strings ([#435](https://github.com/firebase/php-jwt/pull/435))
|
||||
|
||||
## 6.2.0 / 2022-05-14
|
||||
|
||||
- Added `CachedKeySet` ([#397](https://github.com/firebase/php-jwt/pull/397))
|
||||
- Added `$defaultAlg` parameter to `JWT::parseKey` and `JWT::parseKeySet` ([#426](https://github.com/firebase/php-jwt/pull/426)).
|
||||
|
||||
## 6.1.0 / 2022-03-23
|
||||
|
||||
- Drop support for PHP 5.3, 5.4, 5.5, 5.6, and 7.0
|
||||
- Add parameter typing and return types where possible
|
||||
|
||||
## 6.0.0 / 2022-01-24
|
||||
|
||||
- **Backwards-Compatibility Breaking Changes**: See the [Release Notes](https://github.com/firebase/php-jwt/releases/tag/v6.0.0) for more information.
|
||||
- New Key object to prevent key/algorithm type confusion (#365)
|
||||
- Add JWK support (#273)
|
||||
- Add ES256 support (#256)
|
||||
- Add ES384 support (#324)
|
||||
- Add Ed25519 support (#343)
|
||||
|
||||
## 5.0.0 / 2017-06-26
|
||||
- Support RS384 and RS512.
|
||||
See [#117](https://github.com/firebase/php-jwt/pull/117). Thanks [@joostfaassen](https://github.com/joostfaassen)!
|
||||
- Add an example for RS256 openssl.
|
||||
See [#125](https://github.com/firebase/php-jwt/pull/125). Thanks [@akeeman](https://github.com/akeeman)!
|
||||
- Detect invalid Base64 encoding in signature.
|
||||
See [#162](https://github.com/firebase/php-jwt/pull/162). Thanks [@psignoret](https://github.com/psignoret)!
|
||||
- Update `JWT::verify` to handle OpenSSL errors.
|
||||
See [#159](https://github.com/firebase/php-jwt/pull/159). Thanks [@bshaffer](https://github.com/bshaffer)!
|
||||
- Add `array` type hinting to `decode` method
|
||||
See [#101](https://github.com/firebase/php-jwt/pull/101). Thanks [@hywak](https://github.com/hywak)!
|
||||
- Add all JSON error types.
|
||||
See [#110](https://github.com/firebase/php-jwt/pull/110). Thanks [@gbalduzzi](https://github.com/gbalduzzi)!
|
||||
- Bugfix 'kid' not in given key list.
|
||||
See [#129](https://github.com/firebase/php-jwt/pull/129). Thanks [@stampycode](https://github.com/stampycode)!
|
||||
- Miscellaneous cleanup, documentation and test fixes.
|
||||
See [#107](https://github.com/firebase/php-jwt/pull/107), [#115](https://github.com/firebase/php-jwt/pull/115),
|
||||
[#160](https://github.com/firebase/php-jwt/pull/160), [#161](https://github.com/firebase/php-jwt/pull/161), and
|
||||
[#165](https://github.com/firebase/php-jwt/pull/165). Thanks [@akeeman](https://github.com/akeeman),
|
||||
[@chinedufn](https://github.com/chinedufn), and [@bshaffer](https://github.com/bshaffer)!
|
||||
|
||||
## 4.0.0 / 2016-07-17
|
||||
- Add support for late static binding. See [#88](https://github.com/firebase/php-jwt/pull/88) for details. Thanks to [@chappy84](https://github.com/chappy84)!
|
||||
- Use static `$timestamp` instead of `time()` to improve unit testing. See [#93](https://github.com/firebase/php-jwt/pull/93) for details. Thanks to [@josephmcdermott](https://github.com/josephmcdermott)!
|
||||
- Fixes to exceptions classes. See [#81](https://github.com/firebase/php-jwt/pull/81) for details. Thanks to [@Maks3w](https://github.com/Maks3w)!
|
||||
- Fixes to PHPDoc. See [#76](https://github.com/firebase/php-jwt/pull/76) for details. Thanks to [@akeeman](https://github.com/akeeman)!
|
||||
|
||||
## 3.0.0 / 2015-07-22
|
||||
- Minimum PHP version updated from `5.2.0` to `5.3.0`.
|
||||
- Add `\Firebase\JWT` namespace. See
|
||||
[#59](https://github.com/firebase/php-jwt/pull/59) for details. Thanks to
|
||||
[@Dashron](https://github.com/Dashron)!
|
||||
- Require a non-empty key to decode and verify a JWT. See
|
||||
[#60](https://github.com/firebase/php-jwt/pull/60) for details. Thanks to
|
||||
[@sjones608](https://github.com/sjones608)!
|
||||
- Cleaner documentation blocks in the code. See
|
||||
[#62](https://github.com/firebase/php-jwt/pull/62) for details. Thanks to
|
||||
[@johanderuijter](https://github.com/johanderuijter)!
|
||||
|
||||
## 2.2.0 / 2015-06-22
|
||||
- Add support for adding custom, optional JWT headers to `JWT::encode()`. See
|
||||
[#53](https://github.com/firebase/php-jwt/pull/53/files) for details. Thanks to
|
||||
[@mcocaro](https://github.com/mcocaro)!
|
||||
|
||||
## 2.1.0 / 2015-05-20
|
||||
- Add support for adding a leeway to `JWT:decode()` that accounts for clock skew
|
||||
between signing and verifying entities. Thanks to [@lcabral](https://github.com/lcabral)!
|
||||
- Add support for passing an object implementing the `ArrayAccess` interface for
|
||||
`$keys` argument in `JWT::decode()`. Thanks to [@aztech-dev](https://github.com/aztech-dev)!
|
||||
|
||||
## 2.0.0 / 2015-04-01
|
||||
- **Note**: It is strongly recommended that you update to > v2.0.0 to address
|
||||
known security vulnerabilities in prior versions when both symmetric and
|
||||
asymmetric keys are used together.
|
||||
- Update signature for `JWT::decode(...)` to require an array of supported
|
||||
algorithms to use when verifying token signatures.
|
||||
Vendored
+30
@@ -0,0 +1,30 @@
|
||||
Copyright (c) 2011, Neuman Vong
|
||||
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following
|
||||
disclaimer in the documentation and/or other materials provided
|
||||
with the distribution.
|
||||
|
||||
* Neither the name of the copyright holder nor the names of other
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
Vendored
+424
@@ -0,0 +1,424 @@
|
||||

|
||||
[](https://packagist.org/packages/firebase/php-jwt)
|
||||
[](https://packagist.org/packages/firebase/php-jwt)
|
||||
[](https://packagist.org/packages/firebase/php-jwt)
|
||||
|
||||
PHP-JWT
|
||||
=======
|
||||
A simple library to encode and decode JSON Web Tokens (JWT) in PHP, conforming to [RFC 7519](https://tools.ietf.org/html/rfc7519).
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
Use composer to manage your dependencies and download PHP-JWT:
|
||||
|
||||
```bash
|
||||
composer require firebase/php-jwt
|
||||
```
|
||||
|
||||
Optionally, install the `paragonie/sodium_compat` package from composer if your
|
||||
php is < 7.2 or does not have libsodium installed:
|
||||
|
||||
```bash
|
||||
composer require paragonie/sodium_compat
|
||||
```
|
||||
|
||||
Example
|
||||
-------
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
$key = 'example_key';
|
||||
$payload = [
|
||||
'iss' => 'http://example.org',
|
||||
'aud' => 'http://example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
/**
|
||||
* IMPORTANT:
|
||||
* You must specify supported algorithms for your application. See
|
||||
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
|
||||
* for a list of spec-compliant algorithms.
|
||||
*/
|
||||
$jwt = JWT::encode($payload, $key, 'HS256');
|
||||
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
|
||||
print_r($decoded);
|
||||
|
||||
// Pass a stdClass in as the third parameter to get the decoded header values
|
||||
$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers = new stdClass());
|
||||
print_r($headers);
|
||||
|
||||
/*
|
||||
NOTE: This will now be an object instead of an associative array. To get
|
||||
an associative array, you will need to cast it as such:
|
||||
*/
|
||||
|
||||
$decoded_array = (array) $decoded;
|
||||
|
||||
/**
|
||||
* You can add a leeway to account for when there is a clock skew times between
|
||||
* the signing and verifying servers. It is recommended that this leeway should
|
||||
* not be bigger than a few minutes.
|
||||
*
|
||||
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
|
||||
*/
|
||||
JWT::$leeway = 60; // $leeway in seconds
|
||||
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
|
||||
```
|
||||
Example encode/decode headers
|
||||
-------
|
||||
Decoding the JWT headers without verifying the JWT first is NOT recommended, and is not supported by
|
||||
this library. This is because without verifying the JWT, the header values could have been tampered with.
|
||||
Any value pulled from an unverified header should be treated as if it could be any string sent in from an
|
||||
attacker. If this is something you still want to do in your application for whatever reason, it's possible to
|
||||
decode the header values manually simply by calling `json_decode` and `base64_decode` on the JWT
|
||||
header part:
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
$key = 'example_key';
|
||||
$payload = [
|
||||
'iss' => 'http://example.org',
|
||||
'aud' => 'http://example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$headers = [
|
||||
'x-forwarded-for' => 'www.google.com'
|
||||
];
|
||||
|
||||
// Encode headers in the JWT string
|
||||
$jwt = JWT::encode($payload, $key, 'HS256', null, $headers);
|
||||
|
||||
// Decode headers from the JWT string WITHOUT validation
|
||||
// **IMPORTANT**: This operation is vulnerable to attacks, as the JWT has not yet been verified.
|
||||
// These headers could be any value sent by an attacker.
|
||||
list($headersB64, $payloadB64, $sig) = explode('.', $jwt);
|
||||
$decoded = json_decode(base64_decode($headersB64), true);
|
||||
|
||||
print_r($decoded);
|
||||
```
|
||||
Example with RS256 (openssl)
|
||||
----------------------------
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
$privateKey = <<<EOD
|
||||
-----BEGIN RSA PRIVATE KEY-----
|
||||
MIIEowIBAAKCAQEAuzWHNM5f+amCjQztc5QTfJfzCC5J4nuW+L/aOxZ4f8J3Frew
|
||||
M2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJhzkPYLae7bTVro3hok0zDITR8F6S
|
||||
JGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548tu4czCuqU8BGVOlnp6IqBHhAswNMM
|
||||
78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vSopcT51koWOgiTf3C7nJUoMWZHZI5
|
||||
HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTzTTqo1SCSH2pooJl9O8at6kkRYsrZ
|
||||
WwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/BwQIDAQABAoIBAFtGaOqNKGwggn9k
|
||||
6yzr6GhZ6Wt2rh1Xpq8XUz514UBhPxD7dFRLpbzCrLVpzY80LbmVGJ9+1pJozyWc
|
||||
VKeCeUdNwbqkr240Oe7GTFmGjDoxU+5/HX/SJYPpC8JZ9oqgEA87iz+WQX9hVoP2
|
||||
oF6EB4ckDvXmk8FMwVZW2l2/kd5mrEVbDaXKxhvUDf52iVD+sGIlTif7mBgR99/b
|
||||
c3qiCnxCMmfYUnT2eh7Vv2LhCR/G9S6C3R4lA71rEyiU3KgsGfg0d82/XWXbegJW
|
||||
h3QbWNtQLxTuIvLq5aAryV3PfaHlPgdgK0ft6ocU2de2FagFka3nfVEyC7IUsNTK
|
||||
bq6nhAECgYEA7d/0DPOIaItl/8BWKyCuAHMss47j0wlGbBSHdJIiS55akMvnAG0M
|
||||
39y22Qqfzh1at9kBFeYeFIIU82ZLF3xOcE3z6pJZ4Dyvx4BYdXH77odo9uVK9s1l
|
||||
3T3BlMcqd1hvZLMS7dviyH79jZo4CXSHiKzc7pQ2YfK5eKxKqONeXuECgYEAyXlG
|
||||
vonaus/YTb1IBei9HwaccnQ/1HRn6MvfDjb7JJDIBhNClGPt6xRlzBbSZ73c2QEC
|
||||
6Fu9h36K/HZ2qcLd2bXiNyhIV7b6tVKk+0Psoj0dL9EbhsD1OsmE1nTPyAc9XZbb
|
||||
OPYxy+dpBCUA8/1U9+uiFoCa7mIbWcSQ+39gHuECgYAz82pQfct30aH4JiBrkNqP
|
||||
nJfRq05UY70uk5k1u0ikLTRoVS/hJu/d4E1Kv4hBMqYCavFSwAwnvHUo51lVCr/y
|
||||
xQOVYlsgnwBg2MX4+GjmIkqpSVCC8D7j/73MaWb746OIYZervQ8dbKahi2HbpsiG
|
||||
8AHcVSA/agxZr38qvWV54QKBgCD5TlDE8x18AuTGQ9FjxAAd7uD0kbXNz2vUYg9L
|
||||
hFL5tyL3aAAtUrUUw4xhd9IuysRhW/53dU+FsG2dXdJu6CxHjlyEpUJl2iZu/j15
|
||||
YnMzGWHIEX8+eWRDsw/+Ujtko/B7TinGcWPz3cYl4EAOiCeDUyXnqnO1btCEUU44
|
||||
DJ1BAoGBAJuPD27ErTSVtId90+M4zFPNibFP50KprVdc8CR37BE7r8vuGgNYXmnI
|
||||
RLnGP9p3pVgFCktORuYS2J/6t84I3+A17nEoB4xvhTLeAinAW/uTQOUmNicOP4Ek
|
||||
2MsLL2kHgL8bLTmvXV4FX+PXphrDKg1XxzOYn0otuoqdAQrkK4og
|
||||
-----END RSA PRIVATE KEY-----
|
||||
EOD;
|
||||
|
||||
$publicKey = <<<EOD
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzWHNM5f+amCjQztc5QT
|
||||
fJfzCC5J4nuW+L/aOxZ4f8J3FrewM2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJ
|
||||
hzkPYLae7bTVro3hok0zDITR8F6SJGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548t
|
||||
u4czCuqU8BGVOlnp6IqBHhAswNMM78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vS
|
||||
opcT51koWOgiTf3C7nJUoMWZHZI5HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTz
|
||||
TTqo1SCSH2pooJl9O8at6kkRYsrZWwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/B
|
||||
wQIDAQAB
|
||||
-----END PUBLIC KEY-----
|
||||
EOD;
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt = JWT::encode($payload, $privateKey, 'RS256');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
|
||||
|
||||
/*
|
||||
NOTE: This will now be an object instead of an associative array. To get
|
||||
an associative array, you will need to cast it as such:
|
||||
*/
|
||||
|
||||
$decoded_array = (array) $decoded;
|
||||
echo "Decode:\n" . print_r($decoded_array, true) . "\n";
|
||||
```
|
||||
|
||||
Example with a passphrase
|
||||
-------------------------
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
// Your passphrase
|
||||
$passphrase = '[YOUR_PASSPHRASE]';
|
||||
|
||||
// Your private key file with passphrase
|
||||
// Can be generated with "ssh-keygen -t rsa -m pem"
|
||||
$privateKeyFile = '/path/to/key-with-passphrase.pem';
|
||||
|
||||
// Create a private key of type "resource"
|
||||
$privateKey = openssl_pkey_get_private(
|
||||
file_get_contents($privateKeyFile),
|
||||
$passphrase
|
||||
);
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt = JWT::encode($payload, $privateKey, 'RS256');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
// Get public key from the private key, or pull from from a file.
|
||||
$publicKey = openssl_pkey_get_details($privateKey)['key'];
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));
|
||||
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||
```
|
||||
|
||||
Example with EdDSA (libsodium and Ed25519 signature)
|
||||
----------------------------
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
// Public and private keys are expected to be Base64 encoded. The last
|
||||
// non-empty line is used so that keys can be generated with
|
||||
// sodium_crypto_sign_keypair(). The secret keys generated by other tools may
|
||||
// need to be adjusted to match the input expected by libsodium.
|
||||
|
||||
$keyPair = sodium_crypto_sign_keypair();
|
||||
|
||||
$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));
|
||||
|
||||
$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair));
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt = JWT::encode($payload, $privateKey, 'EdDSA');
|
||||
echo "Encode:\n" . print_r($jwt, true) . "\n";
|
||||
|
||||
$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA'));
|
||||
echo "Decode:\n" . print_r((array) $decoded, true) . "\n";
|
||||
````
|
||||
|
||||
Example with multiple keys
|
||||
--------------------------
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
|
||||
// Example RSA keys from previous example
|
||||
// $privateKey1 = '...';
|
||||
// $publicKey1 = '...';
|
||||
|
||||
// Example EdDSA keys from previous example
|
||||
// $privateKey2 = '...';
|
||||
// $publicKey2 = '...';
|
||||
|
||||
$payload = [
|
||||
'iss' => 'example.org',
|
||||
'aud' => 'example.com',
|
||||
'iat' => 1356999524,
|
||||
'nbf' => 1357000000
|
||||
];
|
||||
|
||||
$jwt1 = JWT::encode($payload, $privateKey1, 'RS256', 'kid1');
|
||||
$jwt2 = JWT::encode($payload, $privateKey2, 'EdDSA', 'kid2');
|
||||
echo "Encode 1:\n" . print_r($jwt1, true) . "\n";
|
||||
echo "Encode 2:\n" . print_r($jwt2, true) . "\n";
|
||||
|
||||
$keys = [
|
||||
'kid1' => new Key($publicKey1, 'RS256'),
|
||||
'kid2' => new Key($publicKey2, 'EdDSA'),
|
||||
];
|
||||
|
||||
$decoded1 = JWT::decode($jwt1, $keys);
|
||||
$decoded2 = JWT::decode($jwt2, $keys);
|
||||
|
||||
echo "Decode 1:\n" . print_r((array) $decoded1, true) . "\n";
|
||||
echo "Decode 2:\n" . print_r((array) $decoded2, true) . "\n";
|
||||
```
|
||||
|
||||
Using JWKs
|
||||
----------
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWK;
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
// Set of keys. The "keys" key is required. For example, the JSON response to
|
||||
// this endpoint: https://www.gstatic.com/iap/verify/public_key-jwk
|
||||
$jwks = ['keys' => []];
|
||||
|
||||
// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\JWT\Key
|
||||
// objects. Pass this as the second parameter to JWT::decode.
|
||||
JWT::decode($payload, JWK::parseKeySet($jwks));
|
||||
```
|
||||
|
||||
Using Cached Key Sets
|
||||
---------------------
|
||||
|
||||
The `CachedKeySet` class can be used to fetch and cache JWKS (JSON Web Key Sets) from a public URI.
|
||||
This has the following advantages:
|
||||
|
||||
1. The results are cached for performance.
|
||||
2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation.
|
||||
3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second.
|
||||
|
||||
```php
|
||||
use Firebase\JWT\CachedKeySet;
|
||||
use Firebase\JWT\JWT;
|
||||
|
||||
// The URI for the JWKS you wish to cache the results from
|
||||
$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk';
|
||||
|
||||
// Create an HTTP client (can be any PSR-7 compatible HTTP client)
|
||||
$httpClient = new GuzzleHttp\Client();
|
||||
|
||||
// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory)
|
||||
$httpFactory = new GuzzleHttp\Psr\HttpFactory();
|
||||
|
||||
// Create a cache item pool (can be any PSR-6 compatible cache item pool)
|
||||
$cacheItemPool = Phpfastcache\CacheManager::getInstance('files');
|
||||
|
||||
$keySet = new CachedKeySet(
|
||||
$jwksUri,
|
||||
$httpClient,
|
||||
$httpFactory,
|
||||
$cacheItemPool,
|
||||
null, // $expiresAfter int seconds to set the JWKS to expire
|
||||
true // $rateLimit true to enable rate limit of 10 RPS on lookup of invalid keys
|
||||
);
|
||||
|
||||
$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above
|
||||
$decoded = JWT::decode($jwt, $keySet);
|
||||
```
|
||||
|
||||
Miscellaneous
|
||||
-------------
|
||||
|
||||
#### Exception Handling
|
||||
|
||||
When a call to `JWT::decode` is invalid, it will throw one of the following exceptions:
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\SignatureInvalidException;
|
||||
use Firebase\JWT\BeforeValidException;
|
||||
use Firebase\JWT\ExpiredException;
|
||||
use DomainException;
|
||||
use InvalidArgumentException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
try {
|
||||
$decoded = JWT::decode($payload, $keys);
|
||||
} catch (InvalidArgumentException $e) {
|
||||
// provided key/key-array is empty or malformed.
|
||||
} catch (DomainException $e) {
|
||||
// provided algorithm is unsupported OR
|
||||
// provided key is invalid OR
|
||||
// unknown error thrown in openSSL or libsodium OR
|
||||
// libsodium is required but not available.
|
||||
} catch (SignatureInvalidException $e) {
|
||||
// provided JWT signature verification failed.
|
||||
} catch (BeforeValidException $e) {
|
||||
// provided JWT is trying to be used before "nbf" claim OR
|
||||
// provided JWT is trying to be used before "iat" claim.
|
||||
} catch (ExpiredException $e) {
|
||||
// provided JWT is trying to be used after "exp" claim.
|
||||
} catch (UnexpectedValueException $e) {
|
||||
// provided JWT is malformed OR
|
||||
// provided JWT is missing an algorithm / using an unsupported algorithm OR
|
||||
// provided JWT algorithm does not match provided key OR
|
||||
// provided key ID in key/key-array is empty or invalid.
|
||||
}
|
||||
```
|
||||
|
||||
All exceptions in the `Firebase\JWT` namespace extend `UnexpectedValueException`, and can be simplified
|
||||
like this:
|
||||
|
||||
```php
|
||||
use Firebase\JWT\JWT;
|
||||
use UnexpectedValueException;
|
||||
try {
|
||||
$decoded = JWT::decode($payload, $keys);
|
||||
} catch (LogicException $e) {
|
||||
// errors having to do with environmental setup or malformed JWT Keys
|
||||
} catch (UnexpectedValueException $e) {
|
||||
// errors having to do with JWT signature and claims
|
||||
}
|
||||
```
|
||||
|
||||
#### Casting to array
|
||||
|
||||
The return value of `JWT::decode` is the generic PHP object `stdClass`. If you'd like to handle with arrays
|
||||
instead, you can do the following:
|
||||
|
||||
```php
|
||||
// return type is stdClass
|
||||
$decoded = JWT::decode($payload, $keys);
|
||||
|
||||
// cast to array
|
||||
$decoded = json_decode(json_encode($decoded), true);
|
||||
```
|
||||
|
||||
Tests
|
||||
-----
|
||||
Run the tests using phpunit:
|
||||
|
||||
```bash
|
||||
$ pear install PHPUnit
|
||||
$ phpunit --configuration phpunit.xml.dist
|
||||
PHPUnit 3.7.10 by Sebastian Bergmann.
|
||||
.....
|
||||
Time: 0 seconds, Memory: 2.50Mb
|
||||
OK (5 tests, 5 assertions)
|
||||
```
|
||||
|
||||
New Lines in private keys
|
||||
-----
|
||||
|
||||
If your private key contains `\n` characters, be sure to wrap it in double quotes `""`
|
||||
and not single quotes `''` in order to properly interpret the escaped characters.
|
||||
|
||||
License
|
||||
-------
|
||||
[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause).
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"name": "firebase/php-jwt",
|
||||
"description": "A simple library to encode and decode JSON Web Tokens (JWT) in PHP. Should conform to the current spec.",
|
||||
"homepage": "https://github.com/firebase/php-jwt",
|
||||
"keywords": [
|
||||
"php",
|
||||
"jwt"
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"name": "Neuman Vong",
|
||||
"email": "neuman+pear@twilio.com",
|
||||
"role": "Developer"
|
||||
},
|
||||
{
|
||||
"name": "Anant Narayanan",
|
||||
"email": "anant@php.net",
|
||||
"role": "Developer"
|
||||
}
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"require": {
|
||||
"php": "^7.4||^8.0"
|
||||
},
|
||||
"suggest": {
|
||||
"paragonie/sodium_compat": "Support EdDSA (Ed25519) signatures when libsodium is not present",
|
||||
"ext-sodium": "Support EdDSA (Ed25519) signatures"
|
||||
},
|
||||
"autoload": {
|
||||
"psr-4": {
|
||||
"Firebase\\JWT\\": "src"
|
||||
}
|
||||
},
|
||||
"require-dev": {
|
||||
"guzzlehttp/guzzle": "^6.5||^7.4",
|
||||
"phpspec/prophecy-phpunit": "^2.0",
|
||||
"phpunit/phpunit": "^9.5",
|
||||
"psr/cache": "^1.0||^2.0",
|
||||
"psr/http-client": "^1.0",
|
||||
"psr/http-factory": "^1.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
class BeforeValidException extends \UnexpectedValueException implements JWTExceptionWithPayloadInterface
|
||||
{
|
||||
private object $payload;
|
||||
|
||||
public function setPayload(object $payload): void
|
||||
{
|
||||
$this->payload = $payload;
|
||||
}
|
||||
|
||||
public function getPayload(): object
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
}
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use ArrayAccess;
|
||||
use InvalidArgumentException;
|
||||
use LogicException;
|
||||
use OutOfBoundsException;
|
||||
use Psr\Cache\CacheItemInterface;
|
||||
use Psr\Cache\CacheItemPoolInterface;
|
||||
use Psr\Http\Client\ClientInterface;
|
||||
use Psr\Http\Message\RequestFactoryInterface;
|
||||
use RuntimeException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* @implements ArrayAccess<string, Key>
|
||||
*/
|
||||
class CachedKeySet implements ArrayAccess
|
||||
{
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $jwksUri;
|
||||
/**
|
||||
* @var ClientInterface
|
||||
*/
|
||||
private $httpClient;
|
||||
/**
|
||||
* @var RequestFactoryInterface
|
||||
*/
|
||||
private $httpFactory;
|
||||
/**
|
||||
* @var CacheItemPoolInterface
|
||||
*/
|
||||
private $cache;
|
||||
/**
|
||||
* @var ?int
|
||||
*/
|
||||
private $expiresAfter;
|
||||
/**
|
||||
* @var ?CacheItemInterface
|
||||
*/
|
||||
private $cacheItem;
|
||||
/**
|
||||
* @var array<string, array<mixed>>
|
||||
*/
|
||||
private $keySet;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $cacheKey;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $cacheKeyPrefix = 'jwks';
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $maxKeyLength = 64;
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $rateLimit;
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $rateLimitCacheKey;
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
private $maxCallsPerMinute = 10;
|
||||
/**
|
||||
* @var string|null
|
||||
*/
|
||||
private $defaultAlg;
|
||||
|
||||
public function __construct(
|
||||
string $jwksUri,
|
||||
ClientInterface $httpClient,
|
||||
RequestFactoryInterface $httpFactory,
|
||||
CacheItemPoolInterface $cache,
|
||||
int $expiresAfter = null,
|
||||
bool $rateLimit = false,
|
||||
string $defaultAlg = null
|
||||
) {
|
||||
$this->jwksUri = $jwksUri;
|
||||
$this->httpClient = $httpClient;
|
||||
$this->httpFactory = $httpFactory;
|
||||
$this->cache = $cache;
|
||||
$this->expiresAfter = $expiresAfter;
|
||||
$this->rateLimit = $rateLimit;
|
||||
$this->defaultAlg = $defaultAlg;
|
||||
$this->setCacheKeys();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $keyId
|
||||
* @return Key
|
||||
*/
|
||||
public function offsetGet($keyId): Key
|
||||
{
|
||||
if (!$this->keyIdExists($keyId)) {
|
||||
throw new OutOfBoundsException('Key ID not found');
|
||||
}
|
||||
return JWK::parseKey($this->keySet[$keyId], $this->defaultAlg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $keyId
|
||||
* @return bool
|
||||
*/
|
||||
public function offsetExists($keyId): bool
|
||||
{
|
||||
return $this->keyIdExists($keyId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $offset
|
||||
* @param Key $value
|
||||
*/
|
||||
public function offsetSet($offset, $value): void
|
||||
{
|
||||
throw new LogicException('Method not implemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $offset
|
||||
*/
|
||||
public function offsetUnset($offset): void
|
||||
{
|
||||
throw new LogicException('Method not implemented');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<mixed>
|
||||
*/
|
||||
private function formatJwksForCache(string $jwks): array
|
||||
{
|
||||
$jwks = json_decode($jwks, true);
|
||||
|
||||
if (!isset($jwks['keys'])) {
|
||||
throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
|
||||
}
|
||||
|
||||
if (empty($jwks['keys'])) {
|
||||
throw new InvalidArgumentException('JWK Set did not contain any keys');
|
||||
}
|
||||
|
||||
$keys = [];
|
||||
foreach ($jwks['keys'] as $k => $v) {
|
||||
$kid = isset($v['kid']) ? $v['kid'] : $k;
|
||||
$keys[(string) $kid] = $v;
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
private function keyIdExists(string $keyId): bool
|
||||
{
|
||||
if (null === $this->keySet) {
|
||||
$item = $this->getCacheItem();
|
||||
// Try to load keys from cache
|
||||
if ($item->isHit()) {
|
||||
// item found! retrieve it
|
||||
$this->keySet = $item->get();
|
||||
// If the cached item is a string, the JWKS response was cached (previous behavior).
|
||||
// Parse this into expected format array<kid, jwk> instead.
|
||||
if (\is_string($this->keySet)) {
|
||||
$this->keySet = $this->formatJwksForCache($this->keySet);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!isset($this->keySet[$keyId])) {
|
||||
if ($this->rateLimitExceeded()) {
|
||||
return false;
|
||||
}
|
||||
$request = $this->httpFactory->createRequest('GET', $this->jwksUri);
|
||||
$jwksResponse = $this->httpClient->sendRequest($request);
|
||||
if ($jwksResponse->getStatusCode() !== 200) {
|
||||
throw new UnexpectedValueException(
|
||||
sprintf('HTTP Error: %d %s for URI "%s"',
|
||||
$jwksResponse->getStatusCode(),
|
||||
$jwksResponse->getReasonPhrase(),
|
||||
$this->jwksUri,
|
||||
),
|
||||
$jwksResponse->getStatusCode()
|
||||
);
|
||||
}
|
||||
$this->keySet = $this->formatJwksForCache((string) $jwksResponse->getBody());
|
||||
|
||||
if (!isset($this->keySet[$keyId])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$item = $this->getCacheItem();
|
||||
$item->set($this->keySet);
|
||||
if ($this->expiresAfter) {
|
||||
$item->expiresAfter($this->expiresAfter);
|
||||
}
|
||||
$this->cache->save($item);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function rateLimitExceeded(): bool
|
||||
{
|
||||
if (!$this->rateLimit) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$cacheItem = $this->cache->getItem($this->rateLimitCacheKey);
|
||||
if (!$cacheItem->isHit()) {
|
||||
$cacheItem->expiresAfter(1); // # of calls are cached each minute
|
||||
}
|
||||
|
||||
$callsPerMinute = (int) $cacheItem->get();
|
||||
if (++$callsPerMinute > $this->maxCallsPerMinute) {
|
||||
return true;
|
||||
}
|
||||
$cacheItem->set($callsPerMinute);
|
||||
$this->cache->save($cacheItem);
|
||||
return false;
|
||||
}
|
||||
|
||||
private function getCacheItem(): CacheItemInterface
|
||||
{
|
||||
if (\is_null($this->cacheItem)) {
|
||||
$this->cacheItem = $this->cache->getItem($this->cacheKey);
|
||||
}
|
||||
|
||||
return $this->cacheItem;
|
||||
}
|
||||
|
||||
private function setCacheKeys(): void
|
||||
{
|
||||
if (empty($this->jwksUri)) {
|
||||
throw new RuntimeException('JWKS URI is empty');
|
||||
}
|
||||
|
||||
// ensure we do not have illegal characters
|
||||
$key = preg_replace('|[^a-zA-Z0-9_\.!]|', '', $this->jwksUri);
|
||||
|
||||
// add prefix
|
||||
$key = $this->cacheKeyPrefix . $key;
|
||||
|
||||
// Hash keys if they exceed $maxKeyLength of 64
|
||||
if (\strlen($key) > $this->maxKeyLength) {
|
||||
$key = substr(hash('sha256', $key), 0, $this->maxKeyLength);
|
||||
}
|
||||
|
||||
$this->cacheKey = $key;
|
||||
|
||||
if ($this->rateLimit) {
|
||||
// add prefix
|
||||
$rateLimitKey = $this->cacheKeyPrefix . 'ratelimit' . $key;
|
||||
|
||||
// Hash keys if they exceed $maxKeyLength of 64
|
||||
if (\strlen($rateLimitKey) > $this->maxKeyLength) {
|
||||
$rateLimitKey = substr(hash('sha256', $rateLimitKey), 0, $this->maxKeyLength);
|
||||
}
|
||||
|
||||
$this->rateLimitCacheKey = $rateLimitKey;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
class ExpiredException extends \UnexpectedValueException implements JWTExceptionWithPayloadInterface
|
||||
{
|
||||
private object $payload;
|
||||
|
||||
public function setPayload(object $payload): void
|
||||
{
|
||||
$this->payload = $payload;
|
||||
}
|
||||
|
||||
public function getPayload(): object
|
||||
{
|
||||
return $this->payload;
|
||||
}
|
||||
}
|
||||
Vendored
+349
@@ -0,0 +1,349 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use DomainException;
|
||||
use InvalidArgumentException;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* JSON Web Key implementation, based on this spec:
|
||||
* https://tools.ietf.org/html/draft-ietf-jose-json-web-key-41
|
||||
*
|
||||
* PHP version 5
|
||||
*
|
||||
* @category Authentication
|
||||
* @package Authentication_JWT
|
||||
* @author Bui Sy Nguyen <nguyenbs@gmail.com>
|
||||
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||
* @link https://github.com/firebase/php-jwt
|
||||
*/
|
||||
class JWK
|
||||
{
|
||||
private const OID = '1.2.840.10045.2.1';
|
||||
private const ASN1_OBJECT_IDENTIFIER = 0x06;
|
||||
private const ASN1_SEQUENCE = 0x10; // also defined in JWT
|
||||
private const ASN1_BIT_STRING = 0x03;
|
||||
private const EC_CURVES = [
|
||||
'P-256' => '1.2.840.10045.3.1.7', // Len: 64
|
||||
'secp256k1' => '1.3.132.0.10', // Len: 64
|
||||
'P-384' => '1.3.132.0.34', // Len: 96
|
||||
// 'P-521' => '1.3.132.0.35', // Len: 132 (not supported)
|
||||
];
|
||||
|
||||
// For keys with "kty" equal to "OKP" (Octet Key Pair), the "crv" parameter must contain the key subtype.
|
||||
// This library supports the following subtypes:
|
||||
private const OKP_SUBTYPES = [
|
||||
'Ed25519' => true, // RFC 8037
|
||||
];
|
||||
|
||||
/**
|
||||
* Parse a set of JWK keys
|
||||
*
|
||||
* @param array<mixed> $jwks The JSON Web Key Set as an associative array
|
||||
* @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
|
||||
* JSON Web Key Set
|
||||
*
|
||||
* @return array<string, Key> An associative array of key IDs (kid) to Key objects
|
||||
*
|
||||
* @throws InvalidArgumentException Provided JWK Set is empty
|
||||
* @throws UnexpectedValueException Provided JWK Set was invalid
|
||||
* @throws DomainException OpenSSL failure
|
||||
*
|
||||
* @uses parseKey
|
||||
*/
|
||||
public static function parseKeySet(array $jwks, string $defaultAlg = null): array
|
||||
{
|
||||
$keys = [];
|
||||
|
||||
if (!isset($jwks['keys'])) {
|
||||
throw new UnexpectedValueException('"keys" member must exist in the JWK Set');
|
||||
}
|
||||
|
||||
if (empty($jwks['keys'])) {
|
||||
throw new InvalidArgumentException('JWK Set did not contain any keys');
|
||||
}
|
||||
|
||||
foreach ($jwks['keys'] as $k => $v) {
|
||||
$kid = isset($v['kid']) ? $v['kid'] : $k;
|
||||
if ($key = self::parseKey($v, $defaultAlg)) {
|
||||
$keys[(string) $kid] = $key;
|
||||
}
|
||||
}
|
||||
|
||||
if (0 === \count($keys)) {
|
||||
throw new UnexpectedValueException('No supported algorithms found in JWK Set');
|
||||
}
|
||||
|
||||
return $keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a JWK key
|
||||
*
|
||||
* @param array<mixed> $jwk An individual JWK
|
||||
* @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
|
||||
* JSON Web Key Set
|
||||
*
|
||||
* @return Key The key object for the JWK
|
||||
*
|
||||
* @throws InvalidArgumentException Provided JWK is empty
|
||||
* @throws UnexpectedValueException Provided JWK was invalid
|
||||
* @throws DomainException OpenSSL failure
|
||||
*
|
||||
* @uses createPemFromModulusAndExponent
|
||||
*/
|
||||
public static function parseKey(array $jwk, string $defaultAlg = null): ?Key
|
||||
{
|
||||
if (empty($jwk)) {
|
||||
throw new InvalidArgumentException('JWK must not be empty');
|
||||
}
|
||||
|
||||
if (!isset($jwk['kty'])) {
|
||||
throw new UnexpectedValueException('JWK must contain a "kty" parameter');
|
||||
}
|
||||
|
||||
if (!isset($jwk['alg'])) {
|
||||
if (\is_null($defaultAlg)) {
|
||||
// The "alg" parameter is optional in a KTY, but an algorithm is required
|
||||
// for parsing in this library. Use the $defaultAlg parameter when parsing the
|
||||
// key set in order to prevent this error.
|
||||
// @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
|
||||
throw new UnexpectedValueException('JWK must contain an "alg" parameter');
|
||||
}
|
||||
$jwk['alg'] = $defaultAlg;
|
||||
}
|
||||
|
||||
switch ($jwk['kty']) {
|
||||
case 'RSA':
|
||||
if (!empty($jwk['d'])) {
|
||||
throw new UnexpectedValueException('RSA private keys are not supported');
|
||||
}
|
||||
if (!isset($jwk['n']) || !isset($jwk['e'])) {
|
||||
throw new UnexpectedValueException('RSA keys must contain values for both "n" and "e"');
|
||||
}
|
||||
|
||||
$pem = self::createPemFromModulusAndExponent($jwk['n'], $jwk['e']);
|
||||
$publicKey = \openssl_pkey_get_public($pem);
|
||||
if (false === $publicKey) {
|
||||
throw new DomainException(
|
||||
'OpenSSL error: ' . \openssl_error_string()
|
||||
);
|
||||
}
|
||||
return new Key($publicKey, $jwk['alg']);
|
||||
case 'EC':
|
||||
if (isset($jwk['d'])) {
|
||||
// The key is actually a private key
|
||||
throw new UnexpectedValueException('Key data must be for a public key');
|
||||
}
|
||||
|
||||
if (empty($jwk['crv'])) {
|
||||
throw new UnexpectedValueException('crv not set');
|
||||
}
|
||||
|
||||
if (!isset(self::EC_CURVES[$jwk['crv']])) {
|
||||
throw new DomainException('Unrecognised or unsupported EC curve');
|
||||
}
|
||||
|
||||
if (empty($jwk['x']) || empty($jwk['y'])) {
|
||||
throw new UnexpectedValueException('x and y not set');
|
||||
}
|
||||
|
||||
$publicKey = self::createPemFromCrvAndXYCoordinates($jwk['crv'], $jwk['x'], $jwk['y']);
|
||||
return new Key($publicKey, $jwk['alg']);
|
||||
case 'OKP':
|
||||
if (isset($jwk['d'])) {
|
||||
// The key is actually a private key
|
||||
throw new UnexpectedValueException('Key data must be for a public key');
|
||||
}
|
||||
|
||||
if (!isset($jwk['crv'])) {
|
||||
throw new UnexpectedValueException('crv not set');
|
||||
}
|
||||
|
||||
if (empty(self::OKP_SUBTYPES[$jwk['crv']])) {
|
||||
throw new DomainException('Unrecognised or unsupported OKP key subtype');
|
||||
}
|
||||
|
||||
if (empty($jwk['x'])) {
|
||||
throw new UnexpectedValueException('x not set');
|
||||
}
|
||||
|
||||
// This library works internally with EdDSA keys (Ed25519) encoded in standard base64.
|
||||
$publicKey = JWT::convertBase64urlToBase64($jwk['x']);
|
||||
return new Key($publicKey, $jwk['alg']);
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts the EC JWK values to pem format.
|
||||
*
|
||||
* @param string $crv The EC curve (only P-256 & P-384 is supported)
|
||||
* @param string $x The EC x-coordinate
|
||||
* @param string $y The EC y-coordinate
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
private static function createPemFromCrvAndXYCoordinates(string $crv, string $x, string $y): string
|
||||
{
|
||||
$pem =
|
||||
self::encodeDER(
|
||||
self::ASN1_SEQUENCE,
|
||||
self::encodeDER(
|
||||
self::ASN1_SEQUENCE,
|
||||
self::encodeDER(
|
||||
self::ASN1_OBJECT_IDENTIFIER,
|
||||
self::encodeOID(self::OID)
|
||||
)
|
||||
. self::encodeDER(
|
||||
self::ASN1_OBJECT_IDENTIFIER,
|
||||
self::encodeOID(self::EC_CURVES[$crv])
|
||||
)
|
||||
) .
|
||||
self::encodeDER(
|
||||
self::ASN1_BIT_STRING,
|
||||
\chr(0x00) . \chr(0x04)
|
||||
. JWT::urlsafeB64Decode($x)
|
||||
. JWT::urlsafeB64Decode($y)
|
||||
)
|
||||
);
|
||||
|
||||
return sprintf(
|
||||
"-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n",
|
||||
wordwrap(base64_encode($pem), 64, "\n", true)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a public key represented in PEM format from RSA modulus and exponent information
|
||||
*
|
||||
* @param string $n The RSA modulus encoded in Base64
|
||||
* @param string $e The RSA exponent encoded in Base64
|
||||
*
|
||||
* @return string The RSA public key represented in PEM format
|
||||
*
|
||||
* @uses encodeLength
|
||||
*/
|
||||
private static function createPemFromModulusAndExponent(
|
||||
string $n,
|
||||
string $e
|
||||
): string {
|
||||
$mod = JWT::urlsafeB64Decode($n);
|
||||
$exp = JWT::urlsafeB64Decode($e);
|
||||
|
||||
$modulus = \pack('Ca*a*', 2, self::encodeLength(\strlen($mod)), $mod);
|
||||
$publicExponent = \pack('Ca*a*', 2, self::encodeLength(\strlen($exp)), $exp);
|
||||
|
||||
$rsaPublicKey = \pack(
|
||||
'Ca*a*a*',
|
||||
48,
|
||||
self::encodeLength(\strlen($modulus) + \strlen($publicExponent)),
|
||||
$modulus,
|
||||
$publicExponent
|
||||
);
|
||||
|
||||
// sequence(oid(1.2.840.113549.1.1.1), null)) = rsaEncryption.
|
||||
$rsaOID = \pack('H*', '300d06092a864886f70d0101010500'); // hex version of MA0GCSqGSIb3DQEBAQUA
|
||||
$rsaPublicKey = \chr(0) . $rsaPublicKey;
|
||||
$rsaPublicKey = \chr(3) . self::encodeLength(\strlen($rsaPublicKey)) . $rsaPublicKey;
|
||||
|
||||
$rsaPublicKey = \pack(
|
||||
'Ca*a*',
|
||||
48,
|
||||
self::encodeLength(\strlen($rsaOID . $rsaPublicKey)),
|
||||
$rsaOID . $rsaPublicKey
|
||||
);
|
||||
|
||||
return "-----BEGIN PUBLIC KEY-----\r\n" .
|
||||
\chunk_split(\base64_encode($rsaPublicKey), 64) .
|
||||
'-----END PUBLIC KEY-----';
|
||||
}
|
||||
|
||||
/**
|
||||
* DER-encode the length
|
||||
*
|
||||
* DER supports lengths up to (2**8)**127, however, we'll only support lengths up to (2**8)**4. See
|
||||
* {@link http://itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf#p=13 X.690 paragraph 8.1.3} for more information.
|
||||
*
|
||||
* @param int $length
|
||||
* @return string
|
||||
*/
|
||||
private static function encodeLength(int $length): string
|
||||
{
|
||||
if ($length <= 0x7F) {
|
||||
return \chr($length);
|
||||
}
|
||||
|
||||
$temp = \ltrim(\pack('N', $length), \chr(0));
|
||||
|
||||
return \pack('Ca*', 0x80 | \strlen($temp), $temp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a value into a DER object.
|
||||
* Also defined in Firebase\JWT\JWT
|
||||
*
|
||||
* @param int $type DER tag
|
||||
* @param string $value the value to encode
|
||||
* @return string the encoded object
|
||||
*/
|
||||
private static function encodeDER(int $type, string $value): string
|
||||
{
|
||||
$tag_header = 0;
|
||||
if ($type === self::ASN1_SEQUENCE) {
|
||||
$tag_header |= 0x20;
|
||||
}
|
||||
|
||||
// Type
|
||||
$der = \chr($tag_header | $type);
|
||||
|
||||
// Length
|
||||
$der .= \chr(\strlen($value));
|
||||
|
||||
return $der . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a string into a DER-encoded OID.
|
||||
*
|
||||
* @param string $oid the OID string
|
||||
* @return string the binary DER-encoded OID
|
||||
*/
|
||||
private static function encodeOID(string $oid): string
|
||||
{
|
||||
$octets = explode('.', $oid);
|
||||
|
||||
// Get the first octet
|
||||
$first = (int) array_shift($octets);
|
||||
$second = (int) array_shift($octets);
|
||||
$oid = \chr($first * 40 + $second);
|
||||
|
||||
// Iterate over subsequent octets
|
||||
foreach ($octets as $octet) {
|
||||
if ($octet == 0) {
|
||||
$oid .= \chr(0x00);
|
||||
continue;
|
||||
}
|
||||
$bin = '';
|
||||
|
||||
while ($octet) {
|
||||
$bin .= \chr(0x80 | ($octet & 0x7f));
|
||||
$octet >>= 7;
|
||||
}
|
||||
$bin[0] = $bin[0] & \chr(0x7f);
|
||||
|
||||
// Convert to big endian if necessary
|
||||
if (pack('V', 65534) == pack('L', 65534)) {
|
||||
$oid .= strrev($bin);
|
||||
} else {
|
||||
$oid .= $bin;
|
||||
}
|
||||
}
|
||||
|
||||
return $oid;
|
||||
}
|
||||
}
|
||||
Vendored
+669
@@ -0,0 +1,669 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use ArrayAccess;
|
||||
use DateTime;
|
||||
use DomainException;
|
||||
use Exception;
|
||||
use InvalidArgumentException;
|
||||
use OpenSSLAsymmetricKey;
|
||||
use OpenSSLCertificate;
|
||||
use stdClass;
|
||||
use UnexpectedValueException;
|
||||
|
||||
/**
|
||||
* JSON Web Token implementation, based on this spec:
|
||||
* https://tools.ietf.org/html/rfc7519
|
||||
*
|
||||
* PHP version 5
|
||||
*
|
||||
* @category Authentication
|
||||
* @package Authentication_JWT
|
||||
* @author Neuman Vong <neuman@twilio.com>
|
||||
* @author Anant Narayanan <anant@php.net>
|
||||
* @license http://opensource.org/licenses/BSD-3-Clause 3-clause BSD
|
||||
* @link https://github.com/firebase/php-jwt
|
||||
*/
|
||||
class JWT
|
||||
{
|
||||
private const ASN1_INTEGER = 0x02;
|
||||
private const ASN1_SEQUENCE = 0x10;
|
||||
private const ASN1_BIT_STRING = 0x03;
|
||||
|
||||
/**
|
||||
* When checking nbf, iat or expiration times,
|
||||
* we want to provide some extra leeway time to
|
||||
* account for clock skew.
|
||||
*
|
||||
* @var int
|
||||
*/
|
||||
public static $leeway = 0;
|
||||
|
||||
/**
|
||||
* Allow the current timestamp to be specified.
|
||||
* Useful for fixing a value within unit testing.
|
||||
* Will default to PHP time() value if null.
|
||||
*
|
||||
* @var ?int
|
||||
*/
|
||||
public static $timestamp = null;
|
||||
|
||||
/**
|
||||
* @var array<string, string[]>
|
||||
*/
|
||||
public static $supported_algs = [
|
||||
'ES384' => ['openssl', 'SHA384'],
|
||||
'ES256' => ['openssl', 'SHA256'],
|
||||
'ES256K' => ['openssl', 'SHA256'],
|
||||
'HS256' => ['hash_hmac', 'SHA256'],
|
||||
'HS384' => ['hash_hmac', 'SHA384'],
|
||||
'HS512' => ['hash_hmac', 'SHA512'],
|
||||
'RS256' => ['openssl', 'SHA256'],
|
||||
'RS384' => ['openssl', 'SHA384'],
|
||||
'RS512' => ['openssl', 'SHA512'],
|
||||
'EdDSA' => ['sodium_crypto', 'EdDSA'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Decodes a JWT string into a PHP object.
|
||||
*
|
||||
* @param string $jwt The JWT
|
||||
* @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray The Key or associative array of key IDs
|
||||
* (kid) to Key objects.
|
||||
* If the algorithm used is asymmetric, this is
|
||||
* the public key.
|
||||
* Each Key object contains an algorithm and
|
||||
* matching key.
|
||||
* Supported algorithms are 'ES384','ES256',
|
||||
* 'HS256', 'HS384', 'HS512', 'RS256', 'RS384'
|
||||
* and 'RS512'.
|
||||
* @param stdClass $headers Optional. Populates stdClass with headers.
|
||||
*
|
||||
* @return stdClass The JWT's payload as a PHP object
|
||||
*
|
||||
* @throws InvalidArgumentException Provided key/key-array was empty or malformed
|
||||
* @throws DomainException Provided JWT is malformed
|
||||
* @throws UnexpectedValueException Provided JWT was invalid
|
||||
* @throws SignatureInvalidException Provided JWT was invalid because the signature verification failed
|
||||
* @throws BeforeValidException Provided JWT is trying to be used before it's eligible as defined by 'nbf'
|
||||
* @throws BeforeValidException Provided JWT is trying to be used before it's been created as defined by 'iat'
|
||||
* @throws ExpiredException Provided JWT has since expired, as defined by the 'exp' claim
|
||||
*
|
||||
* @uses jsonDecode
|
||||
* @uses urlsafeB64Decode
|
||||
*/
|
||||
public static function decode(
|
||||
string $jwt,
|
||||
$keyOrKeyArray,
|
||||
stdClass &$headers = null
|
||||
): stdClass {
|
||||
// Validate JWT
|
||||
$timestamp = \is_null(static::$timestamp) ? \time() : static::$timestamp;
|
||||
|
||||
if (empty($keyOrKeyArray)) {
|
||||
throw new InvalidArgumentException('Key may not be empty');
|
||||
}
|
||||
$tks = \explode('.', $jwt);
|
||||
if (\count($tks) !== 3) {
|
||||
throw new UnexpectedValueException('Wrong number of segments');
|
||||
}
|
||||
list($headb64, $bodyb64, $cryptob64) = $tks;
|
||||
$headerRaw = static::urlsafeB64Decode($headb64);
|
||||
if (null === ($header = static::jsonDecode($headerRaw))) {
|
||||
throw new UnexpectedValueException('Invalid header encoding');
|
||||
}
|
||||
if ($headers !== null) {
|
||||
$headers = $header;
|
||||
}
|
||||
$payloadRaw = static::urlsafeB64Decode($bodyb64);
|
||||
if (null === ($payload = static::jsonDecode($payloadRaw))) {
|
||||
throw new UnexpectedValueException('Invalid claims encoding');
|
||||
}
|
||||
if (\is_array($payload)) {
|
||||
// prevent PHP Fatal Error in edge-cases when payload is empty array
|
||||
$payload = (object) $payload;
|
||||
}
|
||||
if (!$payload instanceof stdClass) {
|
||||
throw new UnexpectedValueException('Payload must be a JSON object');
|
||||
}
|
||||
$sig = static::urlsafeB64Decode($cryptob64);
|
||||
if (empty($header->alg)) {
|
||||
throw new UnexpectedValueException('Empty algorithm');
|
||||
}
|
||||
if (empty(static::$supported_algs[$header->alg])) {
|
||||
throw new UnexpectedValueException('Algorithm not supported');
|
||||
}
|
||||
|
||||
$key = self::getKey($keyOrKeyArray, property_exists($header, 'kid') ? $header->kid : null);
|
||||
|
||||
// Check the algorithm
|
||||
if (!self::constantTimeEquals($key->getAlgorithm(), $header->alg)) {
|
||||
// See issue #351
|
||||
throw new UnexpectedValueException('Incorrect key for this algorithm');
|
||||
}
|
||||
if (\in_array($header->alg, ['ES256', 'ES256K', 'ES384'], true)) {
|
||||
// OpenSSL expects an ASN.1 DER sequence for ES256/ES256K/ES384 signatures
|
||||
$sig = self::signatureToDER($sig);
|
||||
}
|
||||
if (!self::verify("{$headb64}.{$bodyb64}", $sig, $key->getKeyMaterial(), $header->alg)) {
|
||||
throw new SignatureInvalidException('Signature verification failed');
|
||||
}
|
||||
|
||||
// Check the nbf if it is defined. This is the time that the
|
||||
// token can actually be used. If it's not yet that time, abort.
|
||||
if (isset($payload->nbf) && floor($payload->nbf) > ($timestamp + static::$leeway)) {
|
||||
$ex = new BeforeValidException(
|
||||
'Cannot handle token with nbf prior to ' . \date(DateTime::ISO8601, (int) $payload->nbf)
|
||||
);
|
||||
$ex->setPayload($payload);
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
// Check that this token has been created before 'now'. This prevents
|
||||
// using tokens that have been created for later use (and haven't
|
||||
// correctly used the nbf claim).
|
||||
if (!isset($payload->nbf) && isset($payload->iat) && floor($payload->iat) > ($timestamp + static::$leeway)) {
|
||||
$ex = new BeforeValidException(
|
||||
'Cannot handle token with iat prior to ' . \date(DateTime::ISO8601, (int) $payload->iat)
|
||||
);
|
||||
$ex->setPayload($payload);
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
// Check if this token has expired.
|
||||
if (isset($payload->exp) && ($timestamp - static::$leeway) >= $payload->exp) {
|
||||
$ex = new ExpiredException('Expired token');
|
||||
$ex->setPayload($payload);
|
||||
throw $ex;
|
||||
}
|
||||
|
||||
return $payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts and signs a PHP array into a JWT string.
|
||||
*
|
||||
* @param array<mixed> $payload PHP array
|
||||
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
|
||||
* @param string $alg Supported algorithms are 'ES384','ES256', 'ES256K', 'HS256',
|
||||
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
|
||||
* @param string $keyId
|
||||
* @param array<string, string> $head An array with header elements to attach
|
||||
*
|
||||
* @return string A signed JWT
|
||||
*
|
||||
* @uses jsonEncode
|
||||
* @uses urlsafeB64Encode
|
||||
*/
|
||||
public static function encode(
|
||||
array $payload,
|
||||
$key,
|
||||
string $alg,
|
||||
string $keyId = null,
|
||||
array $head = null
|
||||
): string {
|
||||
$header = ['typ' => 'JWT'];
|
||||
if (isset($head) && \is_array($head)) {
|
||||
$header = \array_merge($header, $head);
|
||||
}
|
||||
$header['alg'] = $alg;
|
||||
if ($keyId !== null) {
|
||||
$header['kid'] = $keyId;
|
||||
}
|
||||
$segments = [];
|
||||
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($header));
|
||||
$segments[] = static::urlsafeB64Encode((string) static::jsonEncode($payload));
|
||||
$signing_input = \implode('.', $segments);
|
||||
|
||||
$signature = static::sign($signing_input, $key, $alg);
|
||||
$segments[] = static::urlsafeB64Encode($signature);
|
||||
|
||||
return \implode('.', $segments);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a string with a given key and algorithm.
|
||||
*
|
||||
* @param string $msg The message to sign
|
||||
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $key The secret key.
|
||||
* @param string $alg Supported algorithms are 'EdDSA', 'ES384', 'ES256', 'ES256K', 'HS256',
|
||||
* 'HS384', 'HS512', 'RS256', 'RS384', and 'RS512'
|
||||
*
|
||||
* @return string An encrypted message
|
||||
*
|
||||
* @throws DomainException Unsupported algorithm or bad key was specified
|
||||
*/
|
||||
public static function sign(
|
||||
string $msg,
|
||||
$key,
|
||||
string $alg
|
||||
): string {
|
||||
if (empty(static::$supported_algs[$alg])) {
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
list($function, $algorithm) = static::$supported_algs[$alg];
|
||||
switch ($function) {
|
||||
case 'hash_hmac':
|
||||
if (!\is_string($key)) {
|
||||
throw new InvalidArgumentException('key must be a string when using hmac');
|
||||
}
|
||||
return \hash_hmac($algorithm, $msg, $key, true);
|
||||
case 'openssl':
|
||||
$signature = '';
|
||||
$success = \openssl_sign($msg, $signature, $key, $algorithm); // @phpstan-ignore-line
|
||||
if (!$success) {
|
||||
throw new DomainException('OpenSSL unable to sign data');
|
||||
}
|
||||
if ($alg === 'ES256' || $alg === 'ES256K') {
|
||||
$signature = self::signatureFromDER($signature, 256);
|
||||
} elseif ($alg === 'ES384') {
|
||||
$signature = self::signatureFromDER($signature, 384);
|
||||
}
|
||||
return $signature;
|
||||
case 'sodium_crypto':
|
||||
if (!\function_exists('sodium_crypto_sign_detached')) {
|
||||
throw new DomainException('libsodium is not available');
|
||||
}
|
||||
if (!\is_string($key)) {
|
||||
throw new InvalidArgumentException('key must be a string when using EdDSA');
|
||||
}
|
||||
try {
|
||||
// The last non-empty line is used as the key.
|
||||
$lines = array_filter(explode("\n", $key));
|
||||
$key = base64_decode((string) end($lines));
|
||||
if (\strlen($key) === 0) {
|
||||
throw new DomainException('Key cannot be empty string');
|
||||
}
|
||||
return sodium_crypto_sign_detached($msg, $key);
|
||||
} catch (Exception $e) {
|
||||
throw new DomainException($e->getMessage(), 0, $e);
|
||||
}
|
||||
}
|
||||
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify a signature with the message, key and method. Not all methods
|
||||
* are symmetric, so we must have a separate verify and sign method.
|
||||
*
|
||||
* @param string $msg The original message (header and body)
|
||||
* @param string $signature The original signature
|
||||
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial For Ed*, ES*, HS*, a string key works. for RS*, must be an instance of OpenSSLAsymmetricKey
|
||||
* @param string $alg The algorithm
|
||||
*
|
||||
* @return bool
|
||||
*
|
||||
* @throws DomainException Invalid Algorithm, bad key, or OpenSSL failure
|
||||
*/
|
||||
private static function verify(
|
||||
string $msg,
|
||||
string $signature,
|
||||
$keyMaterial,
|
||||
string $alg
|
||||
): bool {
|
||||
if (empty(static::$supported_algs[$alg])) {
|
||||
throw new DomainException('Algorithm not supported');
|
||||
}
|
||||
|
||||
list($function, $algorithm) = static::$supported_algs[$alg];
|
||||
switch ($function) {
|
||||
case 'openssl':
|
||||
$success = \openssl_verify($msg, $signature, $keyMaterial, $algorithm); // @phpstan-ignore-line
|
||||
if ($success === 1) {
|
||||
return true;
|
||||
}
|
||||
if ($success === 0) {
|
||||
return false;
|
||||
}
|
||||
// returns 1 on success, 0 on failure, -1 on error.
|
||||
throw new DomainException(
|
||||
'OpenSSL error: ' . \openssl_error_string()
|
||||
);
|
||||
case 'sodium_crypto':
|
||||
if (!\function_exists('sodium_crypto_sign_verify_detached')) {
|
||||
throw new DomainException('libsodium is not available');
|
||||
}
|
||||
if (!\is_string($keyMaterial)) {
|
||||
throw new InvalidArgumentException('key must be a string when using EdDSA');
|
||||
}
|
||||
try {
|
||||
// The last non-empty line is used as the key.
|
||||
$lines = array_filter(explode("\n", $keyMaterial));
|
||||
$key = base64_decode((string) end($lines));
|
||||
if (\strlen($key) === 0) {
|
||||
throw new DomainException('Key cannot be empty string');
|
||||
}
|
||||
if (\strlen($signature) === 0) {
|
||||
throw new DomainException('Signature cannot be empty string');
|
||||
}
|
||||
return sodium_crypto_sign_verify_detached($signature, $msg, $key);
|
||||
} catch (Exception $e) {
|
||||
throw new DomainException($e->getMessage(), 0, $e);
|
||||
}
|
||||
case 'hash_hmac':
|
||||
default:
|
||||
if (!\is_string($keyMaterial)) {
|
||||
throw new InvalidArgumentException('key must be a string when using hmac');
|
||||
}
|
||||
$hash = \hash_hmac($algorithm, $msg, $keyMaterial, true);
|
||||
return self::constantTimeEquals($hash, $signature);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a JSON string into a PHP object.
|
||||
*
|
||||
* @param string $input JSON string
|
||||
*
|
||||
* @return mixed The decoded JSON string
|
||||
*
|
||||
* @throws DomainException Provided string was invalid JSON
|
||||
*/
|
||||
public static function jsonDecode(string $input)
|
||||
{
|
||||
$obj = \json_decode($input, false, 512, JSON_BIGINT_AS_STRING);
|
||||
|
||||
if ($errno = \json_last_error()) {
|
||||
self::handleJsonError($errno);
|
||||
} elseif ($obj === null && $input !== 'null') {
|
||||
throw new DomainException('Null result with non-null input');
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a PHP array into a JSON string.
|
||||
*
|
||||
* @param array<mixed> $input A PHP array
|
||||
*
|
||||
* @return string JSON representation of the PHP array
|
||||
*
|
||||
* @throws DomainException Provided object could not be encoded to valid JSON
|
||||
*/
|
||||
public static function jsonEncode(array $input): string
|
||||
{
|
||||
if (PHP_VERSION_ID >= 50400) {
|
||||
$json = \json_encode($input, \JSON_UNESCAPED_SLASHES);
|
||||
} else {
|
||||
// PHP 5.3 only
|
||||
$json = \json_encode($input);
|
||||
}
|
||||
if ($errno = \json_last_error()) {
|
||||
self::handleJsonError($errno);
|
||||
} elseif ($json === 'null') {
|
||||
throw new DomainException('Null result with non-null input');
|
||||
}
|
||||
if ($json === false) {
|
||||
throw new DomainException('Provided object could not be encoded to valid JSON');
|
||||
}
|
||||
return $json;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a string with URL-safe Base64.
|
||||
*
|
||||
* @param string $input A Base64 encoded string
|
||||
*
|
||||
* @return string A decoded string
|
||||
*
|
||||
* @throws InvalidArgumentException invalid base64 characters
|
||||
*/
|
||||
public static function urlsafeB64Decode(string $input): string
|
||||
{
|
||||
return \base64_decode(self::convertBase64UrlToBase64($input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a string in the base64url (URL-safe Base64) encoding to standard base64.
|
||||
*
|
||||
* @param string $input A Base64 encoded string with URL-safe characters (-_ and no padding)
|
||||
*
|
||||
* @return string A Base64 encoded string with standard characters (+/) and padding (=), when
|
||||
* needed.
|
||||
*
|
||||
* @see https://www.rfc-editor.org/rfc/rfc4648
|
||||
*/
|
||||
public static function convertBase64UrlToBase64(string $input): string
|
||||
{
|
||||
$remainder = \strlen($input) % 4;
|
||||
if ($remainder) {
|
||||
$padlen = 4 - $remainder;
|
||||
$input .= \str_repeat('=', $padlen);
|
||||
}
|
||||
return \strtr($input, '-_', '+/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a string with URL-safe Base64.
|
||||
*
|
||||
* @param string $input The string you want encoded
|
||||
*
|
||||
* @return string The base64 encode of what you passed in
|
||||
*/
|
||||
public static function urlsafeB64Encode(string $input): string
|
||||
{
|
||||
return \str_replace('=', '', \strtr(\base64_encode($input), '+/', '-_'));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Determine if an algorithm has been provided for each Key
|
||||
*
|
||||
* @param Key|ArrayAccess<string,Key>|array<string,Key> $keyOrKeyArray
|
||||
* @param string|null $kid
|
||||
*
|
||||
* @throws UnexpectedValueException
|
||||
*
|
||||
* @return Key
|
||||
*/
|
||||
private static function getKey(
|
||||
$keyOrKeyArray,
|
||||
?string $kid
|
||||
): Key {
|
||||
if ($keyOrKeyArray instanceof Key) {
|
||||
return $keyOrKeyArray;
|
||||
}
|
||||
|
||||
if (empty($kid) && $kid !== '0') {
|
||||
throw new UnexpectedValueException('"kid" empty, unable to lookup correct key');
|
||||
}
|
||||
|
||||
if ($keyOrKeyArray instanceof CachedKeySet) {
|
||||
// Skip "isset" check, as this will automatically refresh if not set
|
||||
return $keyOrKeyArray[$kid];
|
||||
}
|
||||
|
||||
if (!isset($keyOrKeyArray[$kid])) {
|
||||
throw new UnexpectedValueException('"kid" invalid, unable to lookup correct key');
|
||||
}
|
||||
|
||||
return $keyOrKeyArray[$kid];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $left The string of known length to compare against
|
||||
* @param string $right The user-supplied string
|
||||
* @return bool
|
||||
*/
|
||||
public static function constantTimeEquals(string $left, string $right): bool
|
||||
{
|
||||
if (\function_exists('hash_equals')) {
|
||||
return \hash_equals($left, $right);
|
||||
}
|
||||
$len = \min(self::safeStrlen($left), self::safeStrlen($right));
|
||||
|
||||
$status = 0;
|
||||
for ($i = 0; $i < $len; $i++) {
|
||||
$status |= (\ord($left[$i]) ^ \ord($right[$i]));
|
||||
}
|
||||
$status |= (self::safeStrlen($left) ^ self::safeStrlen($right));
|
||||
|
||||
return ($status === 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to create a JSON error.
|
||||
*
|
||||
* @param int $errno An error number from json_last_error()
|
||||
*
|
||||
* @throws DomainException
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
private static function handleJsonError(int $errno): void
|
||||
{
|
||||
$messages = [
|
||||
JSON_ERROR_DEPTH => 'Maximum stack depth exceeded',
|
||||
JSON_ERROR_STATE_MISMATCH => 'Invalid or malformed JSON',
|
||||
JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
|
||||
JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
|
||||
JSON_ERROR_UTF8 => 'Malformed UTF-8 characters' //PHP >= 5.3.3
|
||||
];
|
||||
throw new DomainException(
|
||||
isset($messages[$errno])
|
||||
? $messages[$errno]
|
||||
: 'Unknown JSON error: ' . $errno
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of bytes in cryptographic strings.
|
||||
*
|
||||
* @param string $str
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
private static function safeStrlen(string $str): int
|
||||
{
|
||||
if (\function_exists('mb_strlen')) {
|
||||
return \mb_strlen($str, '8bit');
|
||||
}
|
||||
return \strlen($str);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an ECDSA signature to an ASN.1 DER sequence
|
||||
*
|
||||
* @param string $sig The ECDSA signature to convert
|
||||
* @return string The encoded DER object
|
||||
*/
|
||||
private static function signatureToDER(string $sig): string
|
||||
{
|
||||
// Separate the signature into r-value and s-value
|
||||
$length = max(1, (int) (\strlen($sig) / 2));
|
||||
list($r, $s) = \str_split($sig, $length);
|
||||
|
||||
// Trim leading zeros
|
||||
$r = \ltrim($r, "\x00");
|
||||
$s = \ltrim($s, "\x00");
|
||||
|
||||
// Convert r-value and s-value from unsigned big-endian integers to
|
||||
// signed two's complement
|
||||
if (\ord($r[0]) > 0x7f) {
|
||||
$r = "\x00" . $r;
|
||||
}
|
||||
if (\ord($s[0]) > 0x7f) {
|
||||
$s = "\x00" . $s;
|
||||
}
|
||||
|
||||
return self::encodeDER(
|
||||
self::ASN1_SEQUENCE,
|
||||
self::encodeDER(self::ASN1_INTEGER, $r) .
|
||||
self::encodeDER(self::ASN1_INTEGER, $s)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes a value into a DER object.
|
||||
*
|
||||
* @param int $type DER tag
|
||||
* @param string $value the value to encode
|
||||
*
|
||||
* @return string the encoded object
|
||||
*/
|
||||
private static function encodeDER(int $type, string $value): string
|
||||
{
|
||||
$tag_header = 0;
|
||||
if ($type === self::ASN1_SEQUENCE) {
|
||||
$tag_header |= 0x20;
|
||||
}
|
||||
|
||||
// Type
|
||||
$der = \chr($tag_header | $type);
|
||||
|
||||
// Length
|
||||
$der .= \chr(\strlen($value));
|
||||
|
||||
return $der . $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes signature from a DER object.
|
||||
*
|
||||
* @param string $der binary signature in DER format
|
||||
* @param int $keySize the number of bits in the key
|
||||
*
|
||||
* @return string the signature
|
||||
*/
|
||||
private static function signatureFromDER(string $der, int $keySize): string
|
||||
{
|
||||
// OpenSSL returns the ECDSA signatures as a binary ASN.1 DER SEQUENCE
|
||||
list($offset, $_) = self::readDER($der);
|
||||
list($offset, $r) = self::readDER($der, $offset);
|
||||
list($offset, $s) = self::readDER($der, $offset);
|
||||
|
||||
// Convert r-value and s-value from signed two's compliment to unsigned
|
||||
// big-endian integers
|
||||
$r = \ltrim($r, "\x00");
|
||||
$s = \ltrim($s, "\x00");
|
||||
|
||||
// Pad out r and s so that they are $keySize bits long
|
||||
$r = \str_pad($r, $keySize / 8, "\x00", STR_PAD_LEFT);
|
||||
$s = \str_pad($s, $keySize / 8, "\x00", STR_PAD_LEFT);
|
||||
|
||||
return $r . $s;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads binary DER-encoded data and decodes into a single object
|
||||
*
|
||||
* @param string $der the binary data in DER format
|
||||
* @param int $offset the offset of the data stream containing the object
|
||||
* to decode
|
||||
*
|
||||
* @return array{int, string|null} the new offset and the decoded object
|
||||
*/
|
||||
private static function readDER(string $der, int $offset = 0): array
|
||||
{
|
||||
$pos = $offset;
|
||||
$size = \strlen($der);
|
||||
$constructed = (\ord($der[$pos]) >> 5) & 0x01;
|
||||
$type = \ord($der[$pos++]) & 0x1f;
|
||||
|
||||
// Length
|
||||
$len = \ord($der[$pos++]);
|
||||
if ($len & 0x80) {
|
||||
$n = $len & 0x1f;
|
||||
$len = 0;
|
||||
while ($n-- && $pos < $size) {
|
||||
$len = ($len << 8) | \ord($der[$pos++]);
|
||||
}
|
||||
}
|
||||
|
||||
// Value
|
||||
if ($type === self::ASN1_BIT_STRING) {
|
||||
$pos++; // Skip the first contents octet (padding indicator)
|
||||
$data = \substr($der, $pos, $len - 1);
|
||||
$pos += $len - 1;
|
||||
} elseif (!$constructed) {
|
||||
$data = \substr($der, $pos, $len);
|
||||
$pos += $len;
|
||||
} else {
|
||||
$data = null;
|
||||
}
|
||||
|
||||
return [$pos, $data];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
namespace Firebase\JWT;
|
||||
|
||||
interface JWTExceptionWithPayloadInterface
|
||||
{
|
||||
/**
|
||||
* Get the payload that caused this exception.
|
||||
*
|
||||
* @return object
|
||||
*/
|
||||
public function getPayload(): object;
|
||||
|
||||
/**
|
||||
* Get the payload that caused this exception.
|
||||
*
|
||||
* @param object $payload
|
||||
* @return void
|
||||
*/
|
||||
public function setPayload(object $payload): void;
|
||||
}
|
||||
Vendored
+64
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
use InvalidArgumentException;
|
||||
use OpenSSLAsymmetricKey;
|
||||
use OpenSSLCertificate;
|
||||
use TypeError;
|
||||
|
||||
class Key
|
||||
{
|
||||
/** @var string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate */
|
||||
private $keyMaterial;
|
||||
/** @var string */
|
||||
private $algorithm;
|
||||
|
||||
/**
|
||||
* @param string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate $keyMaterial
|
||||
* @param string $algorithm
|
||||
*/
|
||||
public function __construct(
|
||||
$keyMaterial,
|
||||
string $algorithm
|
||||
) {
|
||||
if (
|
||||
!\is_string($keyMaterial)
|
||||
&& !$keyMaterial instanceof OpenSSLAsymmetricKey
|
||||
&& !$keyMaterial instanceof OpenSSLCertificate
|
||||
&& !\is_resource($keyMaterial)
|
||||
) {
|
||||
throw new TypeError('Key material must be a string, resource, or OpenSSLAsymmetricKey');
|
||||
}
|
||||
|
||||
if (empty($keyMaterial)) {
|
||||
throw new InvalidArgumentException('Key material must not be empty');
|
||||
}
|
||||
|
||||
if (empty($algorithm)) {
|
||||
throw new InvalidArgumentException('Algorithm must not be empty');
|
||||
}
|
||||
|
||||
// TODO: Remove in PHP 8.0 in favor of class constructor property promotion
|
||||
$this->keyMaterial = $keyMaterial;
|
||||
$this->algorithm = $algorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the algorithm valid for this key
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getAlgorithm(): string
|
||||
{
|
||||
return $this->algorithm;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string|resource|OpenSSLAsymmetricKey|OpenSSLCertificate
|
||||
*/
|
||||
public function getKeyMaterial()
|
||||
{
|
||||
return $this->keyMaterial;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace Firebase\JWT;
|
||||
|
||||
class SignatureInvalidException extends \UnexpectedValueException
|
||||
{
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2015 Paragon Initiative Enterprises
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
basedir=$( dirname $( readlink -f ${BASH_SOURCE[0]} ) )
|
||||
|
||||
php -dphar.readonly=0 "$basedir/other/build_phar.php" $*
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "paragonie/random_compat",
|
||||
"description": "PHP 5.x polyfill for random_bytes() and random_int() from PHP 7",
|
||||
"keywords": [
|
||||
"csprng",
|
||||
"random",
|
||||
"polyfill",
|
||||
"pseudorandom"
|
||||
],
|
||||
"license": "MIT",
|
||||
"type": "library",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Paragon Initiative Enterprises",
|
||||
"email": "security@paragonie.com",
|
||||
"homepage": "https://paragonie.com"
|
||||
}
|
||||
],
|
||||
"support": {
|
||||
"issues": "https://github.com/paragonie/random_compat/issues",
|
||||
"email": "info@paragonie.com",
|
||||
"source": "https://github.com/paragonie/random_compat"
|
||||
},
|
||||
"require": {
|
||||
"php": ">= 7"
|
||||
},
|
||||
"require-dev": {
|
||||
"vimeo/psalm": "^1",
|
||||
"phpunit/phpunit": "4.*|5.*"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-libsodium": "Provides a modern crypto API that can be used to generate random bytes."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
-----BEGIN PUBLIC KEY-----
|
||||
MHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEEd+wCqJDrx5B4OldM0dQE0ZMX+lx1ZWm
|
||||
pui0SUqD4G29L3NGsz9UhJ/0HjBdbnkhIK5xviT0X5vtjacF6ajgcCArbTB+ds+p
|
||||
+h7Q084NuSuIpNb6YPfoUFgC/CL9kAoc
|
||||
-----END PUBLIC KEY-----
|
||||
@@ -0,0 +1,11 @@
|
||||
-----BEGIN PGP SIGNATURE-----
|
||||
Version: GnuPG v2.0.22 (MingW32)
|
||||
|
||||
iQEcBAABAgAGBQJWtW1hAAoJEGuXocKCZATaJf0H+wbZGgskK1dcRTsuVJl9IWip
|
||||
QwGw/qIKI280SD6/ckoUMxKDCJiFuPR14zmqnS36k7N5UNPnpdTJTS8T11jttSpg
|
||||
1LCmgpbEIpgaTah+cELDqFCav99fS+bEiAL5lWDAHBTE/XPjGVCqeehyPYref4IW
|
||||
NDBIEsvnHPHPLsn6X5jq4+Yj5oUixgxaMPiR+bcO4Sh+RzOVB6i2D0upWfRXBFXA
|
||||
NNnsg9/zjvoC7ZW73y9uSH+dPJTt/Vgfeiv52/v41XliyzbUyLalf02GNPY+9goV
|
||||
JHG1ulEEBJOCiUD9cE1PUIJwHA/HqyhHIvV350YoEFiHl8iSwm7SiZu5kPjaq74=
|
||||
=B6+8
|
||||
-----END PGP SIGNATURE-----
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
/**
|
||||
* Random_* Compatibility Library
|
||||
* for using the new PHP 7 random_* API in PHP 5 projects
|
||||
*
|
||||
* @version 2.99.99
|
||||
* @released 2018-06-06
|
||||
*
|
||||
* The MIT License (MIT)
|
||||
*
|
||||
* Copyright (c) 2015 - 2018 Paragon Initiative Enterprises
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*/
|
||||
|
||||
// NOP
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
$dist = dirname(__DIR__).'/dist';
|
||||
if (!is_dir($dist)) {
|
||||
mkdir($dist, 0755);
|
||||
}
|
||||
if (file_exists($dist.'/random_compat.phar')) {
|
||||
unlink($dist.'/random_compat.phar');
|
||||
}
|
||||
$phar = new Phar(
|
||||
$dist.'/random_compat.phar',
|
||||
FilesystemIterator::CURRENT_AS_FILEINFO | \FilesystemIterator::KEY_AS_FILENAME,
|
||||
'random_compat.phar'
|
||||
);
|
||||
rename(
|
||||
dirname(__DIR__).'/lib/random.php',
|
||||
dirname(__DIR__).'/lib/index.php'
|
||||
);
|
||||
$phar->buildFromDirectory(dirname(__DIR__).'/lib');
|
||||
rename(
|
||||
dirname(__DIR__).'/lib/index.php',
|
||||
dirname(__DIR__).'/lib/random.php'
|
||||
);
|
||||
|
||||
/**
|
||||
* If we pass an (optional) path to a private key as a second argument, we will
|
||||
* sign the Phar with OpenSSL.
|
||||
*
|
||||
* If you leave this out, it will produce an unsigned .phar!
|
||||
*/
|
||||
if ($argc > 1) {
|
||||
if (!@is_readable($argv[1])) {
|
||||
echo 'Could not read the private key file:', $argv[1], "\n";
|
||||
exit(255);
|
||||
}
|
||||
$pkeyFile = file_get_contents($argv[1]);
|
||||
|
||||
$private = openssl_get_privatekey($pkeyFile);
|
||||
if ($private !== false) {
|
||||
$pkey = '';
|
||||
openssl_pkey_export($private, $pkey);
|
||||
$phar->setSignatureAlgorithm(Phar::OPENSSL, $pkey);
|
||||
|
||||
/**
|
||||
* Save the corresponding public key to the file
|
||||
*/
|
||||
if (!@is_readable($dist.'/random_compat.phar.pubkey')) {
|
||||
$details = openssl_pkey_get_details($private);
|
||||
file_put_contents(
|
||||
$dist.'/random_compat.phar.pubkey',
|
||||
$details['key']
|
||||
);
|
||||
}
|
||||
} else {
|
||||
echo 'An error occurred reading the private key from OpenSSL.', "\n";
|
||||
exit(255);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
|
||||
require_once 'lib/byte_safe_strings.php';
|
||||
require_once 'lib/cast_to_int.php';
|
||||
require_once 'lib/error_polyfill.php';
|
||||
require_once 'other/ide_stubs/libsodium.php';
|
||||
require_once 'lib/random.php';
|
||||
|
||||
$int = random_int(0, 65536);
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
<?xml version="1.0"?>
|
||||
<psalm
|
||||
autoloader="psalm-autoload.php"
|
||||
stopOnFirstError="false"
|
||||
useDocblockTypes="true"
|
||||
>
|
||||
<projectFiles>
|
||||
<directory name="lib" />
|
||||
</projectFiles>
|
||||
<issueHandlers>
|
||||
<RedundantConditionGivenDocblockType errorLevel="info" />
|
||||
<UnresolvableInclude errorLevel="info" />
|
||||
<DuplicateClass errorLevel="info" />
|
||||
<InvalidOperand errorLevel="info" />
|
||||
<UndefinedConstant errorLevel="info" />
|
||||
<MissingReturnType errorLevel="info" />
|
||||
<InvalidReturnType errorLevel="info" />
|
||||
</issueHandlers>
|
||||
</psalm>
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
ISC License
|
||||
|
||||
Copyright (c) 2016-2023, Paragon Initiative Enterprises <security at paragonie dot com>
|
||||
Copyright (c) 2013-2019, Frank Denis <j at pureftpd dot org>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
+415
@@ -0,0 +1,415 @@
|
||||
# Sodium Compat
|
||||
|
||||
[](https://github.com/paragonie/sodium_compat/actions)
|
||||
[](https://github.com/paragonie/sodium_compat/actions)
|
||||
[](https://ci.appveyor.com/project/paragonie-scott/sodium-compat)
|
||||
[](https://packagist.org/packages/paragonie/sodium_compat)
|
||||
[](https://packagist.org/packages/paragonie/sodium_compat)
|
||||
[](https://packagist.org/packages/paragonie/sodium_compat)
|
||||
[](https://packagist.org/packages/paragonie/sodium_compat)
|
||||
|
||||
Sodium Compat is a pure PHP polyfill for the Sodium cryptography library
|
||||
(libsodium), a core extension in PHP 7.2.0+ and otherwise [available in PECL](https://pecl.php.net/package/libsodium).
|
||||
|
||||
If you have the PHP extension installed, Sodium Compat will opportunistically
|
||||
and transparently use the PHP extension instead of our implementation.
|
||||
|
||||
## Major Versions and Branches
|
||||
|
||||
sodium_compat v1.21.0 was the last v1.x release from the master branch. From now
|
||||
on, all future releases that support PHP 5.2 - 5.6 and 32-bit integers will be
|
||||
[in the `v1.x` branch](v1.x).
|
||||
|
||||
Newer versions of sodium_compat (i.e., v2.0.0) will continue to live in the master
|
||||
branch, unless a new major version is needed. The goal of this work is to improve
|
||||
code readability and performance, while reducing boilerplate code.
|
||||
|
||||
When in doubt, refer to the README file in [the master branch](https://github.com/paragonie/sodium_compat/blob/master/README.md)
|
||||
for the latest in version information.
|
||||
|
||||
### Which version should I use?
|
||||
|
||||
| sodium_compat version | PHP versions supported | 32-bit support? | Branch |
|
||||
|-----------------------|------------------------|-----------------|---------------------------------------------------------------|
|
||||
| `v1.x.y` | 5.2.4 - LATEST | YES | [v1.x](https://github.com/paragonie/sodium_compat/tree/v1.x) |
|
||||
| `v2.x.y` | 7.2 - LATEST | NO | **master** |
|
||||
|
||||
If you need 32-bit PHP support (`PHP_INT_SIZE == 4`), continue using sodium_compat v1.x.
|
||||
If you want improved performance and smaller dependencies, use v2.x.
|
||||
|
||||
We recommend libraries and frameworks set a Composer version constraint as follows:
|
||||
|
||||
```javascript
|
||||
{
|
||||
"require": {
|
||||
/* ... */
|
||||
"paragonie/sodium_compat": ">= 1"
|
||||
/* ... */
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Applications should, conversely, specify the actual version that matters to them
|
||||
and their deployments.
|
||||
|
||||
## IMPORTANT!
|
||||
|
||||
This cryptography library has not been formally audited by an independent third
|
||||
party that specializes in cryptography or cryptanalysis.
|
||||
|
||||
If you require such an audit before you can use sodium_compat in your projects
|
||||
and have the funds for such an audit, please open an issue or contact
|
||||
`security at paragonie dot com` so we can help get the ball rolling.
|
||||
|
||||
However, sodium_compat has been adopted by high profile open source projects,
|
||||
such as [Joomla!](https://github.com/joomla/joomla-cms/blob/459d74686d2a638ec51149d7c44ddab8075852be/composer.json#L40)
|
||||
and [Magento](https://github.com/magento/magento2/blob/8fd89cfdf52c561ac0ca7bc20fd38ef688e201b0/composer.json#L44).
|
||||
Furthermore, sodium_compat was developed by Paragon Initiative Enterprises, a
|
||||
company that *specializes* in secure PHP development and PHP cryptography, and
|
||||
has been informally reviewed by many other security experts who also specialize
|
||||
in PHP.
|
||||
|
||||
If you'd like to learn more about the defensive security measures we've taken
|
||||
to prevent sodium_compat from being a source of vulnerability in your systems,
|
||||
please read [*Cryptographically Secure PHP Development*](https://paragonie.com/blog/2017/02/cryptographically-secure-php-development).
|
||||
|
||||
# Installing Sodium Compat
|
||||
|
||||
If you're using Composer:
|
||||
|
||||
```bash
|
||||
composer require paragonie/sodium_compat
|
||||
```
|
||||
|
||||
### Install From Source
|
||||
|
||||
If you're not using Composer, download a [release tarball](https://github.com/paragonie/sodium_compat/releases)
|
||||
(which should be signed with [our GnuPG public key](https://paragonie.com/static/gpg-public-key.txt)), extract
|
||||
its contents, then include our `autoload.php` script in your project.
|
||||
|
||||
```php
|
||||
<?php
|
||||
require_once "/path/to/sodium_compat/autoload.php";
|
||||
```
|
||||
|
||||
### PHP Archives (Phar) Releases
|
||||
|
||||
Since version 1.3.0, [sodium_compat releases](https://github.com/paragonie/sodium_compat/releases) include a
|
||||
PHP Archive (.phar file) and associated GPG signature. First, download both files and verify them with our
|
||||
GPG public key, like so:
|
||||
|
||||
```bash
|
||||
# Getting our public key from the keyserver:
|
||||
gpg --fingerprint 7F52D5C61D1255C731362E826B97A1C2826404DA
|
||||
if [ $? -ne 0 ]; then
|
||||
echo -e "\033[33mDownloading PGP Public Key...\033[0m"
|
||||
gpg --keyserver pgp.mit.edu --recv-keys 7F52D5C61D1255C731362E826B97A1C2826404DA
|
||||
# Security <security@paragonie.com>
|
||||
gpg --fingerprint 7F52D5C61D1255C731362E826B97A1C2826404DA
|
||||
if [ $? -ne 0 ]; then
|
||||
echo -e "\033[31mCould not download PGP public key for verification\033[0m"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
# Verifying the PHP Archive
|
||||
gpg --verify sodium-compat.phar.sig sodium-compat.phar
|
||||
```
|
||||
|
||||
Now, simply include this .phar file in your application.
|
||||
|
||||
```php
|
||||
<?php
|
||||
require_once "/path/to/sodium-compat.phar";
|
||||
```
|
||||
|
||||
# Support
|
||||
|
||||
[Commercial support for libsodium](https://download.libsodium.org/doc/commercial_support/) is available
|
||||
from multiple vendors. If you need help using sodium_compat in one of your projects, [contact Paragon Initiative Enterprises](https://paragonie.com/contact).
|
||||
|
||||
Non-commercial report will be facilitated through [Github issues](https://github.com/paragonie/sodium_compat/issues).
|
||||
We offer no guarantees of our availability to resolve questions about integrating sodium_compat into third-party
|
||||
software for free, but will strive to fix any bugs (security-related or otherwise) in our library.
|
||||
|
||||
## Support Contracts
|
||||
|
||||
If your company uses this library in their products or services, you may be
|
||||
interested in [purchasing a support contract from Paragon Initiative Enterprises](https://paragonie.com/enterprise).
|
||||
|
||||
# Using Sodium Compat
|
||||
|
||||
## True Polyfill
|
||||
|
||||
As per the [second vote on the libsodium RFC](https://wiki.php.net/rfc/libsodium#proposed_voting_choices),
|
||||
PHP 7.2 uses `sodium_*` instead of `\Sodium\*`.
|
||||
|
||||
```php
|
||||
<?php
|
||||
require_once "/path/to/sodium_compat/autoload.php";
|
||||
|
||||
$alice_kp = sodium_crypto_sign_keypair();
|
||||
$alice_sk = sodium_crypto_sign_secretkey($alice_kp);
|
||||
$alice_pk = sodium_crypto_sign_publickey($alice_kp);
|
||||
|
||||
$message = 'This is a test message.';
|
||||
$signature = sodium_crypto_sign_detached($message, $alice_sk);
|
||||
if (sodium_crypto_sign_verify_detached($signature, $message, $alice_pk)) {
|
||||
echo 'OK', PHP_EOL;
|
||||
} else {
|
||||
throw new Exception('Invalid signature');
|
||||
}
|
||||
```
|
||||
|
||||
## Polyfill For the Old PECL Extension API
|
||||
|
||||
If you're using PHP 5.3.0 or newer and do not have the PECL extension installed,
|
||||
you can just use the [standard ext/sodium API features as-is](https://paragonie.com/book/pecl-libsodium)
|
||||
and the polyfill will work its magic.
|
||||
|
||||
```php
|
||||
<?php
|
||||
require_once "/path/to/sodium_compat/autoload.php";
|
||||
|
||||
$alice_kp = \Sodium\crypto_sign_keypair();
|
||||
$alice_sk = \Sodium\crypto_sign_secretkey($alice_kp);
|
||||
$alice_pk = \Sodium\crypto_sign_publickey($alice_kp);
|
||||
|
||||
$message = 'This is a test message.';
|
||||
$signature = \Sodium\crypto_sign_detached($message, $alice_sk);
|
||||
if (\Sodium\crypto_sign_verify_detached($signature, $message, $alice_pk)) {
|
||||
echo 'OK', PHP_EOL;
|
||||
} else {
|
||||
throw new Exception('Invalid signature');
|
||||
}
|
||||
```
|
||||
|
||||
The polyfill does not expose this API on PHP < 5.3, or if you have the PHP
|
||||
extension installed already.
|
||||
|
||||
## General-Use Polyfill
|
||||
|
||||
If your users are on PHP < 5.3, or you want to write code that will work
|
||||
whether or not the PECL extension is available, you'll want to use the
|
||||
**`ParagonIE_Sodium_Compat`** class for most of your libsodium needs.
|
||||
|
||||
The above example, written for general use:
|
||||
|
||||
```php
|
||||
<?php
|
||||
require_once "/path/to/sodium_compat/autoload.php";
|
||||
|
||||
$alice_kp = ParagonIE_Sodium_Compat::crypto_sign_keypair();
|
||||
$alice_sk = ParagonIE_Sodium_Compat::crypto_sign_secretkey($alice_kp);
|
||||
$alice_pk = ParagonIE_Sodium_Compat::crypto_sign_publickey($alice_kp);
|
||||
|
||||
$message = 'This is a test message.';
|
||||
$signature = ParagonIE_Sodium_Compat::crypto_sign_detached($message, $alice_sk);
|
||||
if (ParagonIE_Sodium_Compat::crypto_sign_verify_detached($signature, $message, $alice_pk)) {
|
||||
echo 'OK', PHP_EOL;
|
||||
} else {
|
||||
throw new Exception('Invalid signature');
|
||||
}
|
||||
```
|
||||
|
||||
Generally: If you replace `\Sodium\ ` with `ParagonIE_Sodium_Compat::`, any
|
||||
code already written for the libsodium PHP extension should work with our
|
||||
polyfill without additional code changes.
|
||||
|
||||
Since this doesn't require a namespace, this API *is* exposed on PHP 5.2.
|
||||
|
||||
Since version 0.7.0, we have our own namespaced API (`ParagonIE\Sodium\*`) to allow brevity
|
||||
in software that uses PHP 5.3+. This is useful if you want to use our file cryptography
|
||||
features without writing `ParagonIE_Sodium_File` every time. This is not exposed on PHP < 5.3,
|
||||
so if your project supports PHP < 5.3, use the underscore method instead.
|
||||
|
||||
To learn how to use Libsodium, read [*Using Libsodium in PHP Projects*](https://paragonie.com/book/pecl-libsodium).
|
||||
|
||||
## Help, Sodium_Compat is Slow! How can I make it fast?
|
||||
|
||||
There are three ways to make it fast:
|
||||
|
||||
1. Use a newer version of PHP (at least 7.2).
|
||||
2. [Install the libsodium PHP extension from PECL](https://paragonie.com/book/pecl-libsodium/read/00-intro.md#installing-libsodium).
|
||||
3. Only if the previous two options are not available for you:
|
||||
1. Verify that [the processor you're using actually implements constant-time multiplication](https://bearssl.org/ctmul.html).
|
||||
Sodium_compat does, but it must trade some speed in order to attain cross-platform security.
|
||||
2. Only if you are 100% certain that your processor is safe, you can set `ParagonIE_Sodium_Compat::$fastMult = true;`
|
||||
without harming the security of your cryptography keys. If your processor *isn't* safe, then decide whether you
|
||||
want speed or security because you can't have both.
|
||||
|
||||
### How can I tell if sodium_compat will be slow, at runtime?
|
||||
|
||||
Since version 1.8, you can use the `polyfill_is_fast()` static method to
|
||||
determine if sodium_compat will be slow at runtime.
|
||||
|
||||
```php
|
||||
<?php
|
||||
if (ParagonIE_Sodium_Compat::polyfill_is_fast()) {
|
||||
// Use libsodium now
|
||||
$process->execute();
|
||||
} else {
|
||||
// Defer to a cron job or other sort of asynchronous process
|
||||
$process->enqueue();
|
||||
}
|
||||
```
|
||||
|
||||
### Help, my PHP only has 32-Bit Integers! It's super slow!
|
||||
|
||||
If the `PHP_INT_SIZE` constant equals `4` instead of `8` (PHP 5 on Windows,
|
||||
Linux on i386, etc.), you will run into **significant performance issues**.
|
||||
|
||||
In particular: public-key cryptography (encryption and signatures)
|
||||
is affected. There is nothing we can do about that.
|
||||
|
||||
The root cause of these performance issues has to do with implementing cryptography
|
||||
algorithms in constant-time using 16-bit limbs (to avoid overflow) in pure PHP.
|
||||
|
||||
To mitigate these performance issues, simply install PHP 7.2 or newer and enable
|
||||
the `sodium` extension.
|
||||
|
||||
Affected users are encouraged to install the sodium extension (or libsodium from
|
||||
older version of PHP).
|
||||
|
||||
Windows users on PHP 5 may be able to simply upgrade to PHP 7 and the slowdown
|
||||
will be greatly reduced.
|
||||
|
||||
## Documentation
|
||||
|
||||
First, you'll want to read the [Libsodium Quick Reference](https://paragonie.com/blog/2017/06/libsodium-quick-reference-quick-comparison-similar-functions-and-which-one-use).
|
||||
It aims to answer, "Which function should I use for [common problem]?".
|
||||
|
||||
If you don't find the answers in the Quick Reference page, check out
|
||||
[*Using Libsodium in PHP Projects*](https://paragonie.com/book/pecl-libsodium).
|
||||
|
||||
Finally, the [official libsodium documentation](https://download.libsodium.org/doc/)
|
||||
(which was written for the C library, not the PHP library) also contains a lot of
|
||||
insightful technical information you may find helpful.
|
||||
|
||||
## API Coverage
|
||||
|
||||
**Recommended reading:** [Libsodium Quick Reference](https://paragonie.com/blog/2017/06/libsodium-quick-reference-quick-comparison-similar-functions-and-which-one-use)
|
||||
|
||||
* Mainline NaCl Features
|
||||
* `crypto_auth()`
|
||||
* `crypto_auth_verify()`
|
||||
* `crypto_box()`
|
||||
* `crypto_box_open()`
|
||||
* `crypto_scalarmult()`
|
||||
* `crypto_secretbox()`
|
||||
* `crypto_secretbox_open()`
|
||||
* `crypto_sign()`
|
||||
* `crypto_sign_open()`
|
||||
* PECL Libsodium Features
|
||||
* `crypto_aead_aegis128l_encrypt()`
|
||||
* `crypto_aead_aegis128l_decrypt()`
|
||||
* `crypto_aead_aegis256_encrypt()`
|
||||
* `crypto_aead_aegis256_decrypt()`
|
||||
* `crypto_aead_aes256gcm_encrypt()`
|
||||
* `crypto_aead_aes256gcm_decrypt()`
|
||||
* `crypto_aead_chacha20poly1305_encrypt()`
|
||||
* `crypto_aead_chacha20poly1305_decrypt()`
|
||||
* `crypto_aead_chacha20poly1305_ietf_encrypt()`
|
||||
* `crypto_aead_chacha20poly1305_ietf_decrypt()`
|
||||
* `crypto_aead_xchacha20poly1305_ietf_encrypt()`
|
||||
* `crypto_aead_xchacha20poly1305_ietf_decrypt()`
|
||||
* `crypto_box_xchacha20poly1305()`
|
||||
* `crypto_box_xchacha20poly1305_open()`
|
||||
* `crypto_box_seal()`
|
||||
* `crypto_box_seal_open()`
|
||||
* `crypto_generichash()`
|
||||
* `crypto_generichash_init()`
|
||||
* `crypto_generichash_update()`
|
||||
* `crypto_generichash_final()`
|
||||
* `crypto_kx()`
|
||||
* `crypto_secretbox_xchacha20poly1305()`
|
||||
* `crypto_secretbox_xchacha20poly1305_open()`
|
||||
* `crypto_shorthash()`
|
||||
* `crypto_sign_detached()`
|
||||
* `crypto_sign_ed25519_pk_to_curve25519()`
|
||||
* `crypto_sign_ed25519_sk_to_curve25519()`
|
||||
* `crypto_sign_verify_detached()`
|
||||
* For advanced users only:
|
||||
* `crypto_core_ristretto255_add()`
|
||||
* `crypto_core_ristretto255_from_hash()`
|
||||
* `crypto_core_ristretto255_is_valid_point()`
|
||||
* `crypto_core_ristretto255_random()`
|
||||
* `crypto_core_ristretto255_scalar_add()`
|
||||
* `crypto_core_ristretto255_scalar_complement()`
|
||||
* `crypto_core_ristretto255_scalar_invert()`
|
||||
* `crypto_core_ristretto255_scalar_mul()`
|
||||
* `crypto_core_ristretto255_scalar_negate()`
|
||||
* `crypto_core_ristretto255_scalar_random()`
|
||||
* `crypto_core_ristretto255_scalar_reduce()`
|
||||
* `crypto_core_ristretto255_scalar_sub()`
|
||||
* `crypto_core_ristretto255_sub()`
|
||||
* `crypto_scalarmult_ristretto255_base()`
|
||||
* `crypto_scalarmult_ristretto255()`
|
||||
* `crypto_stream()`
|
||||
* `crypto_stream_keygen()`
|
||||
* `crypto_stream_xor()`
|
||||
* `crypto_stream_xchacha20()`
|
||||
* `crypto_stream_xchacha20_keygen()`
|
||||
* `crypto_stream_xchacha20_xor()`
|
||||
* `crypto_stream_xchacha20_xor_ic()`
|
||||
* Other utilities (e.g. `crypto_*_keypair()`)
|
||||
* `add()`
|
||||
* `base642bin()`
|
||||
* `bin2base64()`
|
||||
* `bin2hex()`
|
||||
* `hex2bin()`
|
||||
* `crypto_kdf_derive_from_key()`
|
||||
* `crypto_kx_client_session_keys()`
|
||||
* `crypto_kx_server_session_keys()`
|
||||
* `crypto_secretstream_xchacha20poly1305_init_push()`
|
||||
* `crypto_secretstream_xchacha20poly1305_push()`
|
||||
* `crypto_secretstream_xchacha20poly1305_init_pull()`
|
||||
* `crypto_secretstream_xchacha20poly1305_pull()`
|
||||
* `crypto_secretstream_xchacha20poly1305_rekey()`
|
||||
* `pad()`
|
||||
* `unpad()`
|
||||
|
||||
### Cryptography Primitives Provided
|
||||
|
||||
* **X25519** - Elliptic Curve Diffie Hellman over Curve25519
|
||||
* **Ed25519** - Edwards curve Digital Signature Algorithm over Curve25519
|
||||
* **Xsalsa20** - Extended-nonce Salsa20 stream cipher
|
||||
* **ChaCha20** - Stream cipher
|
||||
* **Xchacha20** - Extended-nonce ChaCha20 stream cipher
|
||||
* **Poly1305** - Polynomial Evaluation Message Authentication Code modulo 2^130 - 5
|
||||
* **BLAKE2b** - Cryptographic Hash Function
|
||||
* **SipHash-2-4** - Fast hash, but not collision-resistant; ideal for hash tables.
|
||||
|
||||
### Features Excluded from this Polyfill
|
||||
|
||||
* `sodium_memzero()` - Although we expose this API endpoint, we can't reliably
|
||||
zero buffers from PHP.
|
||||
|
||||
If you have the PHP extension installed, sodium_compat
|
||||
will use the native implementation to zero out the string provided. Otherwise
|
||||
it will throw a `SodiumException`.
|
||||
* `sodium_crypto_pwhash()` - It's not feasible to polyfill scrypt or Argon2
|
||||
into PHP and get reasonable performance. Users would feel motivated to select
|
||||
parameters that downgrade security to avoid denial of service (DoS) attacks.
|
||||
|
||||
The only winning move is not to play.
|
||||
|
||||
If ext/sodium or ext/libsodium is installed, these API methods will fallthrough
|
||||
to the extension. Otherwise, our polyfill library will throw a `SodiumException`.
|
||||
|
||||
To detect support for Argon2i at runtime, use
|
||||
`ParagonIE_Sodium_Compat::crypto_pwhash_is_available()`, which returns a
|
||||
boolean value (`TRUE` or `FALSE`).
|
||||
* Libsodium's HKDF API (`crypto_kdf_hkdf_*()`) is not included because PHP has
|
||||
its own [HMAC features](https://php.met/hash_hmac) amd it was not deemed necessary.
|
||||
|
||||
### PHPCompatibility Ruleset
|
||||
|
||||
For sodium_compat users and that utilize [`PHPCompatibility`](https://github.com/PHPCompatibility/PHPCompatibility)
|
||||
in their CI process, there is now a custom ruleset available which can be used
|
||||
to prevent false positives being thrown by `PHPCompatibility` for the native
|
||||
PHP functionality being polyfilled by this repo.
|
||||
|
||||
You can find the repo for the `PHPCompatibilityParagonieSodiumCompat` ruleset
|
||||
here [on Github](https://github.com/PHPCompatibility/PHPCompatibilityParagonie)
|
||||
and [on Packagist](https://packagist.org/packages/phpcompatibility/phpcompatibility-paragonie).
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
/*
|
||||
This file should only ever be loaded on PHP 7+
|
||||
*/
|
||||
if (PHP_VERSION_ID < 70000) {
|
||||
return;
|
||||
}
|
||||
|
||||
spl_autoload_register(function ($class) {
|
||||
$namespace = 'ParagonIE_Sodium_';
|
||||
// Does the class use the namespace prefix?
|
||||
$len = strlen($namespace);
|
||||
if (strncmp($namespace, $class, $len) !== 0) {
|
||||
// no, move to the next registered autoloader
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get the relative class name
|
||||
$relative_class = substr($class, $len);
|
||||
|
||||
// Replace the namespace prefix with the base directory, replace namespace
|
||||
// separators with directory separators in the relative class name, append
|
||||
// with .php
|
||||
$file = dirname(__FILE__) . '/src/' . str_replace('_', '/', $relative_class) . '.php';
|
||||
// if the file exists, require it
|
||||
if (file_exists($file)) {
|
||||
require_once $file;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
if (PHP_VERSION_ID < 70000) {
|
||||
if (!is_callable('sodiumCompatAutoloader')) {
|
||||
/**
|
||||
* Sodium_Compat autoloader.
|
||||
*
|
||||
* @param string $class Class name to be autoloaded.
|
||||
*
|
||||
* @return bool Stop autoloading?
|
||||
*/
|
||||
function sodiumCompatAutoloader($class)
|
||||
{
|
||||
$namespace = 'ParagonIE_Sodium_';
|
||||
// Does the class use the namespace prefix?
|
||||
$len = strlen($namespace);
|
||||
if (strncmp($namespace, $class, $len) !== 0) {
|
||||
// no, move to the next registered autoloader
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get the relative class name
|
||||
$relative_class = substr($class, $len);
|
||||
|
||||
// Replace the namespace prefix with the base directory, replace namespace
|
||||
// separators with directory separators in the relative class name, append
|
||||
// with .php
|
||||
$file = dirname(__FILE__) . '/src/' . str_replace('_', '/', $relative_class) . '.php';
|
||||
// if the file exists, require it
|
||||
if (file_exists($file)) {
|
||||
require_once $file;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now that we have an autoloader, let's register it!
|
||||
spl_autoload_register('sodiumCompatAutoloader');
|
||||
}
|
||||
} else {
|
||||
require_once dirname(__FILE__) . '/autoload-php7.php';
|
||||
}
|
||||
|
||||
/* Explicitly, always load the Compat class: */
|
||||
if (!class_exists('ParagonIE_Sodium_Compat', false)) {
|
||||
require_once dirname(__FILE__) . '/src/Compat.php';
|
||||
}
|
||||
|
||||
if (!class_exists('SodiumException', false)) {
|
||||
require_once dirname(__FILE__) . '/src/SodiumException.php';
|
||||
}
|
||||
if (PHP_VERSION_ID >= 50300) {
|
||||
// Namespaces didn't exist before 5.3.0, so don't even try to use this
|
||||
// unless PHP >= 5.3.0
|
||||
require_once dirname(__FILE__) . '/lib/namespaced.php';
|
||||
require_once dirname(__FILE__) . '/lib/sodium_compat.php';
|
||||
if (!defined('SODIUM_CRYPTO_AEAD_AEGIS128L_KEYBYTES')) {
|
||||
require_once dirname(__FILE__) . '/lib/php84compat_const.php';
|
||||
}
|
||||
} else {
|
||||
require_once dirname(__FILE__) . '/src/PHP52/SplFixedArray.php';
|
||||
}
|
||||
if (PHP_VERSION_ID < 70200 || !extension_loaded('sodium')) {
|
||||
if (PHP_VERSION_ID >= 50300 && !defined('SODIUM_CRYPTO_SCALARMULT_BYTES')) {
|
||||
require_once dirname(__FILE__) . '/lib/php72compat_const.php';
|
||||
}
|
||||
if (PHP_VERSION_ID >= 70000) {
|
||||
assert(class_exists('ParagonIE_Sodium_Compat'), 'Possible filesystem/autoloader bug?');
|
||||
} else {
|
||||
assert(class_exists('ParagonIE_Sodium_Compat'));
|
||||
}
|
||||
require_once(dirname(__FILE__) . '/lib/php72compat.php');
|
||||
} elseif (!function_exists('sodium_crypto_stream_xchacha20_xor')) {
|
||||
// Older versions of {PHP, ext/sodium} will not define these
|
||||
require_once(dirname(__FILE__) . '/lib/php72compat.php');
|
||||
}
|
||||
if (PHP_VERSION_ID < 80400 || !extension_loaded('sodium')) {
|
||||
require_once dirname(__FILE__) . '/lib/php84compat.php';
|
||||
}
|
||||
require_once(dirname(__FILE__) . '/lib/stream-xchacha20.php');
|
||||
require_once(dirname(__FILE__) . '/lib/ristretto255.php');
|
||||
@@ -0,0 +1,87 @@
|
||||
{
|
||||
"name": "paragonie/sodium_compat",
|
||||
"description": "Pure PHP implementation of libsodium; uses the PHP extension if it exists",
|
||||
"keywords": [
|
||||
"PHP",
|
||||
"cryptography",
|
||||
"elliptic curve",
|
||||
"elliptic curve cryptography",
|
||||
"Pure-PHP cryptography",
|
||||
"side-channel resistant",
|
||||
"Curve25519",
|
||||
"X25519",
|
||||
"ECDH",
|
||||
"Elliptic Curve Diffie-Hellman",
|
||||
"Ed25519",
|
||||
"RFC 7748",
|
||||
"RFC 8032",
|
||||
"EdDSA",
|
||||
"Edwards-curve Digital Signature Algorithm",
|
||||
"ChaCha20",
|
||||
"Salsa20",
|
||||
"Xchacha20",
|
||||
"Xsalsa20",
|
||||
"Poly1305",
|
||||
"BLAKE2b",
|
||||
"public-key cryptography",
|
||||
"secret-key cryptography",
|
||||
"AEAD",
|
||||
"Chapoly",
|
||||
"Salpoly",
|
||||
"ChaCha20-Poly1305",
|
||||
"XSalsa20-Poly1305",
|
||||
"XChaCha20-Poly1305",
|
||||
"encryption",
|
||||
"authentication",
|
||||
"libsodium"
|
||||
],
|
||||
"license": "ISC",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Paragon Initiative Enterprises",
|
||||
"email": "security@paragonie.com"
|
||||
},
|
||||
{
|
||||
"name": "Frank Denis",
|
||||
"email": "jedisct1@pureftpd.org"
|
||||
}
|
||||
],
|
||||
"autoload": {
|
||||
"files": ["autoload.php"]
|
||||
},
|
||||
"repositories": [
|
||||
{
|
||||
"type": "git",
|
||||
"url": "https://github.com/garex/phpunit"
|
||||
},
|
||||
{
|
||||
"type": "git",
|
||||
"url": "https://github.com/garex/phpunit-mock-objects"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^5.2.4|^5.3|^5.4|^5.5|^5.6|^7|^8",
|
||||
"xrstf/composer-php52": "1.*",
|
||||
"paragonie/random_compat": ">=1"
|
||||
},
|
||||
"minimum-stability": "dev",
|
||||
"require-dev": {
|
||||
"phpunit/phpunit-php52": "dev-3.6.12-php52",
|
||||
"phpunit/phpunit-mock-objects-php52": "dev-1.1.0-php52"
|
||||
},
|
||||
"scripts": {
|
||||
"post-install-cmd": [
|
||||
"xrstf\\Composer52\\Generator::onPostInstallCmd"
|
||||
],
|
||||
"post-update-cmd": [
|
||||
"xrstf\\Composer52\\Generator::onPostInstallCmd"
|
||||
],
|
||||
"post-autoload-dump": [
|
||||
"xrstf\\Composer52\\Generator::onPostInstallCmd"
|
||||
]
|
||||
},
|
||||
"suggest": {
|
||||
"ext-libsodium": "PHP < 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security.",
|
||||
"ext-sodium": "PHP >= 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security."
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
{
|
||||
"name": "paragonie/sodium_compat",
|
||||
"description": "Pure PHP implementation of libsodium; uses the PHP extension if it exists",
|
||||
"keywords": [
|
||||
"PHP",
|
||||
"cryptography",
|
||||
"elliptic curve",
|
||||
"elliptic curve cryptography",
|
||||
"Pure-PHP cryptography",
|
||||
"side-channel resistant",
|
||||
"Curve25519",
|
||||
"X25519",
|
||||
"ECDH",
|
||||
"Elliptic Curve Diffie-Hellman",
|
||||
"Ed25519",
|
||||
"RFC 7748",
|
||||
"RFC 8032",
|
||||
"EdDSA",
|
||||
"Edwards-curve Digital Signature Algorithm",
|
||||
"ChaCha20",
|
||||
"Salsa20",
|
||||
"Xchacha20",
|
||||
"Xsalsa20",
|
||||
"Poly1305",
|
||||
"BLAKE2b",
|
||||
"public-key cryptography",
|
||||
"secret-key cryptography",
|
||||
"AEAD",
|
||||
"Chapoly",
|
||||
"Salpoly",
|
||||
"ChaCha20-Poly1305",
|
||||
"XSalsa20-Poly1305",
|
||||
"XChaCha20-Poly1305",
|
||||
"encryption",
|
||||
"authentication",
|
||||
"libsodium"
|
||||
],
|
||||
"license": "ISC",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Paragon Initiative Enterprises",
|
||||
"email": "security@paragonie.com"
|
||||
},
|
||||
{
|
||||
"name": "Frank Denis",
|
||||
"email": "jedisct1@pureftpd.org"
|
||||
}
|
||||
],
|
||||
"autoload": {
|
||||
"files": ["autoload.php"]
|
||||
},
|
||||
"require": {
|
||||
"php": "^5.2.4|^5.3|^5.4|^5.5|^5.6|^7|^8",
|
||||
"paragonie/random_compat": ">=1"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^3|^4|^5|^6|^7|^8|^9"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "phpunit"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-libsodium": "PHP < 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security.",
|
||||
"ext-sodium": "PHP >= 7.0: Better performance, password hashing (Argon2i), secure memory management (memzero), and better security."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
namespace Sodium;
|
||||
|
||||
require_once dirname(dirname(__FILE__)) . '/autoload.php';
|
||||
|
||||
use ParagonIE_Sodium_Compat;
|
||||
|
||||
const CRYPTO_AEAD_AES256GCM_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_KEYBYTES;
|
||||
const CRYPTO_AEAD_AES256GCM_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NSECBYTES;
|
||||
const CRYPTO_AEAD_AES256GCM_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_NPUBBYTES;
|
||||
const CRYPTO_AEAD_AES256GCM_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_AES256GCM_ABYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_ABYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES;
|
||||
const CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = ParagonIE_Sodium_Compat::CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES;
|
||||
const CRYPTO_AUTH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_BYTES;
|
||||
const CRYPTO_AUTH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_AUTH_KEYBYTES;
|
||||
const CRYPTO_BOX_SEALBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEALBYTES;
|
||||
const CRYPTO_BOX_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SECRETKEYBYTES;
|
||||
const CRYPTO_BOX_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_PUBLICKEYBYTES;
|
||||
const CRYPTO_BOX_KEYPAIRBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_KEYPAIRBYTES;
|
||||
const CRYPTO_BOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_MACBYTES;
|
||||
const CRYPTO_BOX_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_NONCEBYTES;
|
||||
const CRYPTO_BOX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_BOX_SEEDBYTES;
|
||||
const CRYPTO_KX_BYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_BYTES;
|
||||
const CRYPTO_KX_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SEEDBYTES;
|
||||
const CRYPTO_KX_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_PUBLICKEYBYTES;
|
||||
const CRYPTO_KX_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_KX_SECRETKEYBYTES;
|
||||
const CRYPTO_GENERICHASH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES;
|
||||
const CRYPTO_GENERICHASH_BYTES_MIN = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MIN;
|
||||
const CRYPTO_GENERICHASH_BYTES_MAX = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_BYTES_MAX;
|
||||
const CRYPTO_GENERICHASH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES;
|
||||
const CRYPTO_GENERICHASH_KEYBYTES_MIN = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MIN;
|
||||
const CRYPTO_GENERICHASH_KEYBYTES_MAX = ParagonIE_Sodium_Compat::CRYPTO_GENERICHASH_KEYBYTES_MAX;
|
||||
const CRYPTO_SCALARMULT_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_BYTES;
|
||||
const CRYPTO_SCALARMULT_SCALARBYTES = ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_SCALARBYTES;
|
||||
const CRYPTO_SHORTHASH_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_BYTES;
|
||||
const CRYPTO_SHORTHASH_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SHORTHASH_KEYBYTES;
|
||||
const CRYPTO_SECRETBOX_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_KEYBYTES;
|
||||
const CRYPTO_SECRETBOX_MACBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_MACBYTES;
|
||||
const CRYPTO_SECRETBOX_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_SECRETBOX_NONCEBYTES;
|
||||
const CRYPTO_SIGN_BYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_BYTES;
|
||||
const CRYPTO_SIGN_SEEDBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_SEEDBYTES;
|
||||
const CRYPTO_SIGN_PUBLICKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_PUBLICKEYBYTES;
|
||||
const CRYPTO_SIGN_SECRETKEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_SECRETKEYBYTES;
|
||||
const CRYPTO_SIGN_KEYPAIRBYTES = ParagonIE_Sodium_Compat::CRYPTO_SIGN_KEYPAIRBYTES;
|
||||
const CRYPTO_STREAM_KEYBYTES = ParagonIE_Sodium_Compat::CRYPTO_STREAM_KEYBYTES;
|
||||
const CRYPTO_STREAM_NONCEBYTES = ParagonIE_Sodium_Compat::CRYPTO_STREAM_NONCEBYTES;
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
require_once dirname(dirname(__FILE__)) . '/autoload.php';
|
||||
|
||||
if (PHP_VERSION_ID < 50300) {
|
||||
return;
|
||||
}
|
||||
|
||||
/*
|
||||
* This file is just for convenience, to allow developers to reduce verbosity when
|
||||
* they add this project to their libraries.
|
||||
*
|
||||
* Replace this:
|
||||
*
|
||||
* $x = ParagonIE_Sodium_Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
|
||||
*
|
||||
* with this:
|
||||
*
|
||||
* use ParagonIE\Sodium\Compat;
|
||||
*
|
||||
* $x = Compat::crypto_aead_xchacha20poly1305_encrypt(...$args);
|
||||
*/
|
||||
spl_autoload_register(function ($class) {
|
||||
if ($class[0] === '\\') {
|
||||
$class = substr($class, 1);
|
||||
}
|
||||
$namespace = 'ParagonIE\\Sodium';
|
||||
// Does the class use the namespace prefix?
|
||||
$len = strlen($namespace);
|
||||
if (strncmp($namespace, $class, $len) !== 0) {
|
||||
// no, move to the next registered autoloader
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get the relative class name
|
||||
$relative_class = substr($class, $len);
|
||||
|
||||
// Replace the namespace prefix with the base directory, replace namespace
|
||||
// separators with directory separators in the relative class name, append
|
||||
// with .php
|
||||
$file = dirname(dirname(__FILE__)) . '/namespaced/' . str_replace('\\', '/', $relative_class) . '.php';
|
||||
// if the file exists, require it
|
||||
if (file_exists($file)) {
|
||||
require_once $file;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
+1665
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,92 @@
|
||||
<?php
|
||||
|
||||
const SODIUM_LIBRARY_MAJOR_VERSION = 9;
|
||||
const SODIUM_LIBRARY_MINOR_VERSION = 1;
|
||||
const SODIUM_LIBRARY_VERSION = '1.0.8';
|
||||
|
||||
const SODIUM_BASE64_VARIANT_ORIGINAL = 1;
|
||||
const SODIUM_BASE64_VARIANT_ORIGINAL_NO_PADDING = 3;
|
||||
const SODIUM_BASE64_VARIANT_URLSAFE = 5;
|
||||
const SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING = 7;
|
||||
const SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_AES256GCM_NSECBYTES = 0;
|
||||
const SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES = 12;
|
||||
const SODIUM_CRYPTO_AEAD_AES256GCM_ABYTES = 16;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NSECBYTES = 0;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_NPUBBYTES = 8;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_ABYTES = 16;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NSECBYTES = 0;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_NPUBBYTES = 12;
|
||||
const SODIUM_CRYPTO_AEAD_CHACHA20POLY1305_IETF_ABYTES = 16;
|
||||
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NSECBYTES = 0;
|
||||
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES = 24;
|
||||
const SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_ABYTES = 16;
|
||||
const SODIUM_CRYPTO_AUTH_BYTES = 32;
|
||||
const SODIUM_CRYPTO_AUTH_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_BOX_SEALBYTES = 16;
|
||||
const SODIUM_CRYPTO_BOX_SECRETKEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_BOX_PUBLICKEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_BOX_KEYPAIRBYTES = 64;
|
||||
const SODIUM_CRYPTO_BOX_MACBYTES = 16;
|
||||
const SODIUM_CRYPTO_BOX_NONCEBYTES = 24;
|
||||
const SODIUM_CRYPTO_BOX_SEEDBYTES = 32;
|
||||
const SODIUM_CRYPTO_KDF_BYTES_MIN = 16;
|
||||
const SODIUM_CRYPTO_KDF_BYTES_MAX = 64;
|
||||
const SODIUM_CRYPTO_KDF_CONTEXTBYTES = 8;
|
||||
const SODIUM_CRYPTO_KDF_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_KX_BYTES = 32;
|
||||
const SODIUM_CRYPTO_KX_PRIMITIVE = 'x25519blake2b';
|
||||
const SODIUM_CRYPTO_KX_SEEDBYTES = 32;
|
||||
const SODIUM_CRYPTO_KX_KEYPAIRBYTES = 64;
|
||||
const SODIUM_CRYPTO_KX_PUBLICKEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_KX_SECRETKEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_KX_SESSIONKEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_GENERICHASH_BYTES = 32;
|
||||
const SODIUM_CRYPTO_GENERICHASH_BYTES_MIN = 16;
|
||||
const SODIUM_CRYPTO_GENERICHASH_BYTES_MAX = 64;
|
||||
const SODIUM_CRYPTO_GENERICHASH_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MIN = 16;
|
||||
const SODIUM_CRYPTO_GENERICHASH_KEYBYTES_MAX = 64;
|
||||
const SODIUM_CRYPTO_PWHASH_SALTBYTES = 16;
|
||||
const SODIUM_CRYPTO_PWHASH_STRPREFIX = '$argon2id$';
|
||||
const SODIUM_CRYPTO_PWHASH_ALG_ARGON2I13 = 1;
|
||||
const SODIUM_CRYPTO_PWHASH_ALG_ARGON2ID13 = 2;
|
||||
const SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE = 33554432;
|
||||
const SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE = 4;
|
||||
const SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE = 134217728;
|
||||
const SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE = 6;
|
||||
const SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE = 536870912;
|
||||
const SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE = 8;
|
||||
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_SALTBYTES = 32;
|
||||
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_STRPREFIX = '$7$';
|
||||
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_INTERACTIVE = 534288;
|
||||
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_INTERACTIVE = 16777216;
|
||||
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_OPSLIMIT_SENSITIVE = 33554432;
|
||||
const SODIUM_CRYPTO_PWHASH_SCRYPTSALSA208SHA256_MEMLIMIT_SENSITIVE = 1073741824;
|
||||
const SODIUM_CRYPTO_SCALARMULT_BYTES = 32;
|
||||
const SODIUM_CRYPTO_SCALARMULT_SCALARBYTES = 32;
|
||||
const SODIUM_CRYPTO_SHORTHASH_BYTES = 8;
|
||||
const SODIUM_CRYPTO_SHORTHASH_KEYBYTES = 16;
|
||||
const SODIUM_CRYPTO_SECRETBOX_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_SECRETBOX_MACBYTES = 16;
|
||||
const SODIUM_CRYPTO_SECRETBOX_NONCEBYTES = 24;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_ABYTES = 17;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_HEADERBYTES = 24;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PUSH = 0;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_PULL = 1;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_REKEY = 2;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_TAG_FINAL = 3;
|
||||
const SODIUM_CRYPTO_SECRETSTREAM_XCHACHA20POLY1305_MESSAGEBYTES_MAX = 0x3fffffff80;
|
||||
const SODIUM_CRYPTO_SIGN_BYTES = 64;
|
||||
const SODIUM_CRYPTO_SIGN_SEEDBYTES = 32;
|
||||
const SODIUM_CRYPTO_SIGN_PUBLICKEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_SIGN_SECRETKEYBYTES = 64;
|
||||
const SODIUM_CRYPTO_SIGN_KEYPAIRBYTES = 96;
|
||||
const SODIUM_CRYPTO_STREAM_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_STREAM_NONCEBYTES = 24;
|
||||
const SODIUM_CRYPTO_STREAM_XCHACHA20_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_STREAM_XCHACHA20_NONCEBYTES = 24;
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
<?php
|
||||
|
||||
require_once dirname(dirname(__FILE__)) . '/autoload.php';
|
||||
|
||||
/**
|
||||
* This file will monkey patch the pure-PHP implementation in place of the
|
||||
* PECL functions and constants, but only if they do not already exist.
|
||||
*
|
||||
* Thus, the functions or constants just proxy to the appropriate
|
||||
* ParagonIE_Sodium_Compat method or class constant, respectively.
|
||||
*/
|
||||
foreach (array(
|
||||
'CRYPTO_AEAD_AESGIS128L_KEYBYTES',
|
||||
'CRYPTO_AEAD_AESGIS128L_NSECBYTES',
|
||||
'CRYPTO_AEAD_AESGIS128L_NPUBBYTES',
|
||||
'CRYPTO_AEAD_AESGIS128L_ABYTES',
|
||||
'CRYPTO_AEAD_AESGIS256_KEYBYTES',
|
||||
'CRYPTO_AEAD_AESGIS256_NSECBYTES',
|
||||
'CRYPTO_AEAD_AESGIS256_NPUBBYTES',
|
||||
'CRYPTO_AEAD_AESGIS256_ABYTES',
|
||||
) as $constant
|
||||
) {
|
||||
if (!defined("SODIUM_$constant") && defined("ParagonIE_Sodium_Compat::$constant")) {
|
||||
define("SODIUM_$constant", constant("ParagonIE_Sodium_Compat::$constant"));
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_aead_aegis128l_decrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aegis128l_decrypt()
|
||||
* @param string $ciphertext
|
||||
* @param string $additional_data
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_aead_aegis128l_decrypt(
|
||||
$ciphertext,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aegis128l_decrypt(
|
||||
$ciphertext,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
$key
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_aead_aegis128l_encrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aegis128l_encrypt()
|
||||
* @param string $message
|
||||
* @param string $additional_data
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_aead_aegis128l_encrypt(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aegis128l_encrypt(
|
||||
$message,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
$key
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_aead_aegis256_decrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aegis256_encrypt()
|
||||
* @param string $ciphertext
|
||||
* @param string $additional_data
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_aead_aegis256_decrypt(
|
||||
$ciphertext,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aegis256_decrypt(
|
||||
$ciphertext,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
$key
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_aead_aegis256_encrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aegis256_encrypt()
|
||||
* @param string $message
|
||||
* @param string $additional_data
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_aead_aegis256_encrypt(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aegis256_encrypt(
|
||||
$message,
|
||||
$additional_data,
|
||||
$nonce,
|
||||
$key
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?php
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS128L_KEYBYTES = 16;
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS128L_NSECBYTES = 0;
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS128L_NPUBBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS128L_ABYTES = 32;
|
||||
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS256_KEYBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS256_NSECBYTES = 0;
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS256_NPUBBYTES = 32;
|
||||
const SODIUM_CRYPTO_AEAD_AEGIS256_ABYTES = 32;
|
||||
+277
@@ -0,0 +1,277 @@
|
||||
<?php
|
||||
|
||||
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES')) {
|
||||
define(
|
||||
'SODIUM_CRYPTO_CORE_RISTRETTO255_BYTES',
|
||||
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_BYTES
|
||||
);
|
||||
define('SODIUM_COMPAT_POLYFILLED_RISTRETTO255', true);
|
||||
}
|
||||
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES')) {
|
||||
define(
|
||||
'SODIUM_CRYPTO_CORE_RISTRETTO255_HASHBYTES',
|
||||
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_HASHBYTES
|
||||
);
|
||||
}
|
||||
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES')) {
|
||||
define(
|
||||
'SODIUM_CRYPTO_CORE_RISTRETTO255_SCALARBYTES',
|
||||
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_SCALARBYTES
|
||||
);
|
||||
}
|
||||
if (!defined('SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES')) {
|
||||
define(
|
||||
'SODIUM_CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES',
|
||||
ParagonIE_Sodium_Compat::CRYPTO_CORE_RISTRETTO255_NONREDUCEDSCALARBYTES
|
||||
);
|
||||
}
|
||||
if (!defined('SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES')) {
|
||||
define(
|
||||
'SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES',
|
||||
ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_RISTRETTO255_SCALARBYTES
|
||||
);
|
||||
}
|
||||
if (!defined('SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES')) {
|
||||
define(
|
||||
'SODIUM_CRYPTO_SCALARMULT_RISTRETTO255_BYTES',
|
||||
ParagonIE_Sodium_Compat::CRYPTO_SCALARMULT_RISTRETTO255_BYTES
|
||||
);
|
||||
}
|
||||
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_add')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_add()
|
||||
*
|
||||
* @param string $p
|
||||
* @param string $q
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_add(
|
||||
#[\SensitiveParameter]
|
||||
$p,
|
||||
#[\SensitiveParameter]
|
||||
$q
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_add($p, $q, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_from_hash')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_from_hash()
|
||||
*
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_from_hash(
|
||||
#[\SensitiveParameter]
|
||||
$s
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_from_hash($s, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_is_valid_point')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_is_valid_point()
|
||||
*
|
||||
* @param string $s
|
||||
* @return bool
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_is_valid_point(
|
||||
#[\SensitiveParameter]
|
||||
$s
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_is_valid_point($s, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_random')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_random()
|
||||
*
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_random()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::ristretto255_random(true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_add')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_add()
|
||||
*
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_add(
|
||||
#[\SensitiveParameter]
|
||||
$x,
|
||||
#[\SensitiveParameter]
|
||||
$y
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_add($x, $y, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_complement')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_complement()
|
||||
*
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_complement(
|
||||
#[\SensitiveParameter]
|
||||
$s
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_complement($s, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_invert')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_invert()
|
||||
*
|
||||
* @param string $p
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_invert(
|
||||
#[\SensitiveParameter]
|
||||
$p
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_invert($p, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_mul')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_mul()
|
||||
*
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_mul(
|
||||
#[\SensitiveParameter]
|
||||
$x,
|
||||
#[\SensitiveParameter]
|
||||
$y
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_mul($x, $y, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_negate')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_negate()
|
||||
*
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_negate(
|
||||
#[\SensitiveParameter]
|
||||
$s
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_negate($s, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_random')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_random()
|
||||
*
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_random()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_random(true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_reduce')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_reduce()
|
||||
*
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_reduce(
|
||||
#[\SensitiveParameter]
|
||||
$s
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_reduce($s, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_scalar_sub')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_scalar_sub()
|
||||
*
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_scalar_sub(
|
||||
#[\SensitiveParameter]
|
||||
$x,
|
||||
#[\SensitiveParameter]
|
||||
$y
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_scalar_sub($x, $y, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_core_ristretto255_sub')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::ristretto255_sub()
|
||||
*
|
||||
* @param string $p
|
||||
* @param string $q
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
function sodium_crypto_core_ristretto255_sub(
|
||||
#[\SensitiveParameter]
|
||||
$p,
|
||||
#[\SensitiveParameter]
|
||||
$q
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::ristretto255_sub($p, $q, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_scalarmult_ristretto255')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_ristretto255()
|
||||
* @param string $n
|
||||
* @param string $p
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_scalarmult_ristretto255(
|
||||
#[\SensitiveParameter]
|
||||
$n,
|
||||
#[\SensitiveParameter]
|
||||
$p
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::scalarmult_ristretto255($n, $p, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_scalarmult_ristretto255_base')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_ristretto255_base()
|
||||
* @param string $n
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_scalarmult_ristretto255_base(
|
||||
#[\SensitiveParameter]
|
||||
$n
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::scalarmult_ristretto255_base($n, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,999 @@
|
||||
<?php
|
||||
namespace Sodium;
|
||||
|
||||
require_once dirname(dirname(__FILE__)) . '/autoload.php';
|
||||
|
||||
use ParagonIE_Sodium_Compat;
|
||||
|
||||
/**
|
||||
* This file will monkey patch the pure-PHP implementation in place of the
|
||||
* PECL functions, but only if they do not already exist.
|
||||
*
|
||||
* Thus, the functions just proxy to the appropriate ParagonIE_Sodium_Compat
|
||||
* method.
|
||||
*/
|
||||
if (!is_callable('\\Sodium\\bin2hex')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::bin2hex()
|
||||
* @param string $string
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function bin2hex(
|
||||
#[\SensitiveParameter]
|
||||
$string
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::bin2hex($string);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\compare')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::compare()
|
||||
* @param string $a
|
||||
* @param string $b
|
||||
* @return int
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function compare(
|
||||
#[\SensitiveParameter]
|
||||
$a,
|
||||
#[\SensitiveParameter]
|
||||
$b
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::compare($a, $b);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_decrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt()
|
||||
* @param string $message
|
||||
* @param string $assocData
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_aead_aes256gcm_decrypt(
|
||||
$message,
|
||||
$assocData,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_decrypt($message, $assocData, $nonce, $key);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_encrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt()
|
||||
* @param string $message
|
||||
* @param string $assocData
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_aead_aes256gcm_encrypt(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$assocData,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_encrypt($message, $assocData, $nonce, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_aes256gcm_is_available')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available()
|
||||
* @return bool
|
||||
*/
|
||||
function crypto_aead_aes256gcm_is_available()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_aes256gcm_is_available();
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_decrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt()
|
||||
* @param string $message
|
||||
* @param string $assocData
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_aead_chacha20poly1305_decrypt(
|
||||
$message,
|
||||
$assocData,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_decrypt($message, $assocData, $nonce, $key);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_encrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt()
|
||||
* @param string $message
|
||||
* @param string $assocData
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_aead_chacha20poly1305_encrypt(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$assocData,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_encrypt($message, $assocData, $nonce, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_ietf_decrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt()
|
||||
* @param string $message
|
||||
* @param string $assocData
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_aead_chacha20poly1305_ietf_decrypt(
|
||||
$message,
|
||||
$assocData,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_decrypt($message, $assocData, $nonce, $key);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_aead_chacha20poly1305_ietf_encrypt')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt()
|
||||
* @param string $message
|
||||
* @param string $assocData
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_aead_chacha20poly1305_ietf_encrypt(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$assocData,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_aead_chacha20poly1305_ietf_encrypt($message, $assocData, $nonce, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_auth')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_auth()
|
||||
* @param string $message
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_auth(
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_auth($message, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_auth_verify')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_auth_verify()
|
||||
* @param string $mac
|
||||
* @param string $message
|
||||
* @param string $key
|
||||
* @return bool
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_auth_verify(
|
||||
$mac,
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_auth_verify($mac, $message, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $kp
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$kp
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_box($message, $nonce, $kp);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_keypair')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_keypair()
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box_keypair()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::crypto_box_keypair();
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_keypair_from_secretkey_and_publickey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey()
|
||||
* @param string $sk
|
||||
* @param string $pk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box_keypair_from_secretkey_and_publickey(
|
||||
#[\SensitiveParameter]
|
||||
$sk,
|
||||
$pk
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_keypair_from_secretkey_and_publickey($sk, $pk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_open')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_open()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $kp
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_box_open(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$kp
|
||||
) {
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_open($message, $nonce, $kp);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_publickey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_publickey()
|
||||
* @param string $keypair
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box_publickey(
|
||||
#[\SensitiveParameter]
|
||||
$keypair
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_publickey($keypair);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_publickey_from_secretkey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey()
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box_publickey_from_secretkey(
|
||||
#[\SensitiveParameter]
|
||||
$sk
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_publickey_from_secretkey($sk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_seal')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
|
||||
* @param string $message
|
||||
* @param string $publicKey
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box_seal(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$publicKey
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_seal($message, $publicKey);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_seal_open')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_seal_open()
|
||||
* @param string $message
|
||||
* @param string $kp
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_box_seal_open(
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$kp
|
||||
) {
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_seal_open($message, $kp);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_box_secretkey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_box_secretkey()
|
||||
* @param string $keypair
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_box_secretkey(
|
||||
#[\SensitiveParameter]
|
||||
$keypair
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_box_secretkey($keypair);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_generichash')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_generichash()
|
||||
* @param string $message
|
||||
* @param string|null $key
|
||||
* @param int $outLen
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_generichash(
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$key = null,
|
||||
$outLen = 32
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_generichash($message, $key, $outLen);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_generichash_final')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_generichash_final()
|
||||
* @param string|null $ctx
|
||||
* @param int $outputLength
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_generichash_final(
|
||||
#[\SensitiveParameter]
|
||||
&$ctx,
|
||||
$outputLength = 32
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_generichash_final($ctx, $outputLength);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_generichash_init')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_generichash_init()
|
||||
* @param string|null $key
|
||||
* @param int $outLen
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_generichash_init(
|
||||
#[\SensitiveParameter]
|
||||
$key = null,
|
||||
$outLen = 32
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_generichash_init($key, $outLen);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_generichash_update')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_generichash_update()
|
||||
* @param string|null $ctx
|
||||
* @param string $message
|
||||
* @return void
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_generichash_update(
|
||||
#[\SensitiveParameter]
|
||||
&$ctx,
|
||||
$message = ''
|
||||
) {
|
||||
ParagonIE_Sodium_Compat::crypto_generichash_update($ctx, $message);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_kx')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_kx()
|
||||
* @param string $my_secret
|
||||
* @param string $their_public
|
||||
* @param string $client_public
|
||||
* @param string $server_public
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_kx(
|
||||
#[\SensitiveParameter]
|
||||
$my_secret,
|
||||
$their_public,
|
||||
$client_public,
|
||||
$server_public
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_kx(
|
||||
$my_secret,
|
||||
$their_public,
|
||||
$client_public,
|
||||
$server_public,
|
||||
true
|
||||
);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_pwhash')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_pwhash()
|
||||
* @param int $outlen
|
||||
* @param string $passwd
|
||||
* @param string $salt
|
||||
* @param int $opslimit
|
||||
* @param int $memlimit
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_pwhash(
|
||||
$outlen,
|
||||
#[\SensitiveParameter]
|
||||
$passwd,
|
||||
$salt,
|
||||
$opslimit,
|
||||
$memlimit
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_pwhash($outlen, $passwd, $salt, $opslimit, $memlimit);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_pwhash_str')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str()
|
||||
* @param string $passwd
|
||||
* @param int $opslimit
|
||||
* @param int $memlimit
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_pwhash_str(
|
||||
#[\SensitiveParameter]
|
||||
$passwd,
|
||||
$opslimit,
|
||||
$memlimit
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_pwhash_str($passwd, $opslimit, $memlimit);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_pwhash_str_verify')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_pwhash_str_verify()
|
||||
* @param string $passwd
|
||||
* @param string $hash
|
||||
* @return bool
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_pwhash_str_verify(
|
||||
#[\SensitiveParameter]
|
||||
$passwd,
|
||||
#[\SensitiveParameter]
|
||||
$hash
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_pwhash_str_verify($passwd, $hash);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256()
|
||||
* @param int $outlen
|
||||
* @param string $passwd
|
||||
* @param string $salt
|
||||
* @param int $opslimit
|
||||
* @param int $memlimit
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_pwhash_scryptsalsa208sha256(
|
||||
$outlen,
|
||||
#[\SensitiveParameter]
|
||||
$passwd,
|
||||
#[\SensitiveParameter]
|
||||
$salt,
|
||||
$opslimit,
|
||||
$memlimit
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256($outlen, $passwd, $salt, $opslimit, $memlimit);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str()
|
||||
* @param string $passwd
|
||||
* @param int $opslimit
|
||||
* @param int $memlimit
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_pwhash_scryptsalsa208sha256_str(
|
||||
#[\SensitiveParameter]
|
||||
$passwd,
|
||||
$opslimit,
|
||||
$memlimit
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str($passwd, $opslimit, $memlimit);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_pwhash_scryptsalsa208sha256_str_verify')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify()
|
||||
* @param string $passwd
|
||||
* @param string $hash
|
||||
* @return bool
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_pwhash_scryptsalsa208sha256_str_verify(
|
||||
#[\SensitiveParameter]
|
||||
$passwd,
|
||||
#[\SensitiveParameter]
|
||||
$hash
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_pwhash_scryptsalsa208sha256_str_verify($passwd, $hash);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_scalarmult')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_scalarmult()
|
||||
* @param string $n
|
||||
* @param string $p
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_scalarmult(
|
||||
#[\SensitiveParameter]
|
||||
$n,
|
||||
$p
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_scalarmult($n, $p);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_scalarmult_base')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_scalarmult_base()
|
||||
* @param string $n
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_scalarmult_base(
|
||||
#[\SensitiveParameter]
|
||||
$n
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_scalarmult_base($n);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_secretbox')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_secretbox()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_secretbox(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_secretbox($message, $nonce, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_secretbox_open')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_secretbox_open()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_secretbox_open(
|
||||
$message,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_secretbox_open($message, $nonce, $key);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_shorthash')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_shorthash()
|
||||
* @param string $message
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_shorthash(
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$key = ''
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_shorthash($message, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign()
|
||||
* @param string $message
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign(
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$sk
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign($message, $sk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_detached')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_detached()
|
||||
* @param string $message
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_detached(
|
||||
$message,
|
||||
#[\SensitiveParameter]
|
||||
$sk
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_detached($message, $sk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_keypair')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_keypair()
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_keypair()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_keypair();
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_open')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_open()
|
||||
* @param string $signedMessage
|
||||
* @param string $pk
|
||||
* @return string|bool
|
||||
*/
|
||||
function crypto_sign_open($signedMessage, $pk)
|
||||
{
|
||||
try {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_open($signedMessage, $pk);
|
||||
} catch (\TypeError $ex) {
|
||||
return false;
|
||||
} catch (\SodiumException $ex) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_publickey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_publickey()
|
||||
* @param string $keypair
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_publickey(
|
||||
#[\SensitiveParameter]
|
||||
$keypair
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_publickey($keypair);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_publickey_from_secretkey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey()
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_publickey_from_secretkey(
|
||||
#[\SensitiveParameter]
|
||||
$sk
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_publickey_from_secretkey($sk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_secretkey')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_secretkey()
|
||||
* @param string $keypair
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_secretkey(
|
||||
#[\SensitiveParameter]
|
||||
$keypair
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_secretkey($keypair);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_seed_keypair')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_seed_keypair()
|
||||
* @param string $seed
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_seed_keypair(
|
||||
#[\SensitiveParameter]
|
||||
$seed
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_seed_keypair($seed);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_verify_detached')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_verify_detached()
|
||||
* @param string $signature
|
||||
* @param string $message
|
||||
* @param string $pk
|
||||
* @return bool
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_verify_detached($signature, $message, $pk)
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_verify_detached($signature, $message, $pk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_ed25519_pk_to_curve25519')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519()
|
||||
* @param string $pk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_ed25519_pk_to_curve25519($pk)
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_ed25519_pk_to_curve25519($pk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_sign_ed25519_sk_to_curve25519')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519()
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_sign_ed25519_sk_to_curve25519(
|
||||
#[\SensitiveParameter]
|
||||
$sk
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_sign_ed25519_sk_to_curve25519($sk);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_stream')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_stream()
|
||||
* @param int $len
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_stream(
|
||||
$len,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_stream($len, $nonce, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\crypto_stream_xor')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_stream_xor()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function crypto_stream_xor(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_stream_xor($message, $nonce, $key);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\hex2bin')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::hex2bin()
|
||||
* @param string $string
|
||||
* @return string
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function hex2bin(
|
||||
#[\SensitiveParameter]
|
||||
$string
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::hex2bin($string);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\memcmp')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::memcmp()
|
||||
* @param string $a
|
||||
* @param string $b
|
||||
* @return int
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function memcmp(
|
||||
#[\SensitiveParameter]
|
||||
$a,
|
||||
#[\SensitiveParameter]
|
||||
$b
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::memcmp($a, $b);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\memzero')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::memzero()
|
||||
* @param string $str
|
||||
* @return void
|
||||
* @throws \SodiumException
|
||||
* @throws \TypeError
|
||||
*
|
||||
* @psalm-suppress MissingParamType
|
||||
* @psalm-suppress MissingReturnType
|
||||
* @psalm-suppress ReferenceConstraintViolation
|
||||
*/
|
||||
function memzero(
|
||||
#[\SensitiveParameter]
|
||||
&$str
|
||||
) {
|
||||
ParagonIE_Sodium_Compat::memzero($str);
|
||||
}
|
||||
}
|
||||
if (!is_callable('\\Sodium\\randombytes_buf')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::randombytes_buf()
|
||||
* @param int $amount
|
||||
* @return string
|
||||
* @throws \TypeError
|
||||
*/
|
||||
function randombytes_buf($amount)
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::randombytes_buf($amount);
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_callable('\\Sodium\\randombytes_uniform')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::randombytes_uniform()
|
||||
* @param int $upperLimit
|
||||
* @return int
|
||||
* @throws \SodiumException
|
||||
* @throws \Error
|
||||
*/
|
||||
function randombytes_uniform($upperLimit)
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::randombytes_uniform($upperLimit);
|
||||
}
|
||||
}
|
||||
|
||||
if (!is_callable('\\Sodium\\randombytes_random16')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::randombytes_random16()
|
||||
* @return int
|
||||
*/
|
||||
function randombytes_random16()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::randombytes_random16();
|
||||
}
|
||||
}
|
||||
|
||||
if (!defined('\\Sodium\\CRYPTO_AUTH_BYTES')) {
|
||||
require_once dirname(__FILE__) . '/constants.php';
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
if (!is_callable('sodium_crypto_stream_xchacha20')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20()
|
||||
* @param int $len
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_stream_xchacha20(
|
||||
$len,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20($len, $nonce, $key, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_stream_xchacha20_keygen')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20_keygen()
|
||||
* @return string
|
||||
* @throws Exception
|
||||
*/
|
||||
function sodium_crypto_stream_xchacha20_keygen()
|
||||
{
|
||||
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20_keygen();
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_stream_xchacha20_xor')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20_xor()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_stream_xchacha20_xor(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$nonce,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20_xor($message, $nonce, $key, true);
|
||||
}
|
||||
}
|
||||
if (!is_callable('sodium_crypto_stream_xchacha20_xor_ic')) {
|
||||
/**
|
||||
* @see ParagonIE_Sodium_Compat::crypto_stream_xchacha20_xor_ic()
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param int $counter
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
function sodium_crypto_stream_xchacha20_xor_ic(
|
||||
#[\SensitiveParameter]
|
||||
$message,
|
||||
$nonce,
|
||||
$counter,
|
||||
#[\SensitiveParameter]
|
||||
$key
|
||||
) {
|
||||
return ParagonIE_Sodium_Compat::crypto_stream_xchacha20_xor_ic($message, $nonce, $counter, $key, true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium;
|
||||
|
||||
class Compat extends \ParagonIE_Sodium_Compat
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class BLAKE2b extends \ParagonIE_Sodium_Core_BLAKE2b
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class ChaCha20 extends \ParagonIE_Sodium_Core_ChaCha20
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\ChaCha20;
|
||||
|
||||
class Ctx extends \ParagonIE_Sodium_Core_ChaCha20_Ctx
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\ChaCha20;
|
||||
|
||||
class IetfCtx extends \ParagonIE_Sodium_Core_ChaCha20_IetfCtx
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class Curve25519 extends \ParagonIE_Sodium_Core_Curve25519
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519;
|
||||
|
||||
class Fe extends \ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519\Ge;
|
||||
|
||||
class Cached extends \ParagonIE_Sodium_Core_Curve25519_Ge_Cached
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519\Ge;
|
||||
|
||||
class P1p1 extends \ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519\Ge;
|
||||
|
||||
class P2 extends \ParagonIE_Sodium_Core_Curve25519_Ge_P2
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519\Ge;
|
||||
|
||||
class P3 extends \ParagonIE_Sodium_Core_Curve25519_Ge_P3
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519\Ge;
|
||||
|
||||
class Precomp extends \ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Curve25519;
|
||||
|
||||
class H extends \ParagonIE_Sodium_Core_Curve25519_H
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class Ed25519 extends \ParagonIE_Sodium_Core_Ed25519
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class HChaCha20 extends \ParagonIE_Sodium_Core_HChaCha20
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class HSalsa20 extends \ParagonIE_Sodium_Core_HSalsa20
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class Poly1305 extends \ParagonIE_Sodium_Core_Poly1305
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core\Poly1305;
|
||||
|
||||
class State extends \ParagonIE_Sodium_Core_Poly1305_State
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class Salsa20 extends \ParagonIE_Sodium_Core_Salsa20
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class SipHash extends \ParagonIE_Sodium_Core_SipHash
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class Util extends \ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class X25519 extends \ParagonIE_Sodium_Core_X25519
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class XChaCha20 extends \ParagonIE_Sodium_Core_XChaCha20
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium\Core;
|
||||
|
||||
class Xsalsa20 extends \ParagonIE_Sodium_Core_XSalsa20
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium;
|
||||
|
||||
class Crypto extends \ParagonIE_Sodium_Crypto
|
||||
{
|
||||
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
namespace ParagonIE\Sodium;
|
||||
|
||||
class File extends \ParagonIE_Sodium_File
|
||||
{
|
||||
|
||||
}
|
||||
+4515
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,284 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_AEGIS_State128L', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C0')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C0', "\x00\x01\x01\x02\x03\x05\x08\x0d\x15\x22\x37\x59\x90\xe9\x79\x62");
|
||||
}
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C1')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C1', "\xdb\x3d\x18\x55\x6d\xc2\x2f\xf1\x20\x11\x31\x42\x73\xb5\x28\xdd");
|
||||
}
|
||||
|
||||
class ParagonIE_Sodium_Core_AEGIS_State128L
|
||||
{
|
||||
/** @var array<int, string> $state */
|
||||
protected $state;
|
||||
public function __construct()
|
||||
{
|
||||
$this->state = array_fill(0, 8, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal Only use this for unit tests!
|
||||
* @return string[]
|
||||
*/
|
||||
public function getState()
|
||||
{
|
||||
return array_values($this->state);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $input
|
||||
* @return self
|
||||
* @throws SodiumException
|
||||
*
|
||||
* @internal Only for unit tests
|
||||
*/
|
||||
public static function initForUnitTests(array $input)
|
||||
{
|
||||
if (count($input) < 8) {
|
||||
throw new SodiumException('invalid input');
|
||||
}
|
||||
$state = new self();
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$state->state[$i] = $input[$i];
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return self
|
||||
*/
|
||||
public static function init($key, $nonce)
|
||||
{
|
||||
$state = new self();
|
||||
|
||||
// S0 = key ^ nonce
|
||||
$state->state[0] = $key ^ $nonce;
|
||||
// S1 = C1
|
||||
$state->state[1] = SODIUM_COMPAT_AEGIS_C1;
|
||||
// S2 = C0
|
||||
$state->state[2] = SODIUM_COMPAT_AEGIS_C0;
|
||||
// S3 = C1
|
||||
$state->state[3] = SODIUM_COMPAT_AEGIS_C1;
|
||||
// S4 = key ^ nonce
|
||||
$state->state[4] = $key ^ $nonce;
|
||||
// S5 = key ^ C0
|
||||
$state->state[5] = $key ^ SODIUM_COMPAT_AEGIS_C0;
|
||||
// S6 = key ^ C1
|
||||
$state->state[6] = $key ^ SODIUM_COMPAT_AEGIS_C1;
|
||||
// S7 = key ^ C0
|
||||
$state->state[7] = $key ^ SODIUM_COMPAT_AEGIS_C0;
|
||||
|
||||
// Repeat(10, Update(nonce, key))
|
||||
for ($i = 0; $i < 10; ++$i) {
|
||||
$state->update($nonce, $key);
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ai
|
||||
* @return self
|
||||
*/
|
||||
public function absorb($ai)
|
||||
{
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($ai) !== 32) {
|
||||
throw new SodiumException('Input must be two AES blocks in size');
|
||||
}
|
||||
$t0 = ParagonIE_Sodium_Core_Util::substr($ai, 0, 16);
|
||||
$t1 = ParagonIE_Sodium_Core_Util::substr($ai, 16, 16);
|
||||
return $this->update($t0, $t1);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $ci
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public function dec($ci)
|
||||
{
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($ci) !== 32) {
|
||||
throw new SodiumException('Input must be two AES blocks in size');
|
||||
}
|
||||
|
||||
// z0 = S6 ^ S1 ^ (S2 & S3)
|
||||
$z0 = $this->state[6]
|
||||
^ $this->state[1]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[2], $this->state[3]);
|
||||
// z1 = S2 ^ S5 ^ (S6 & S7)
|
||||
$z1 = $this->state[2]
|
||||
^ $this->state[5]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[6], $this->state[7]);
|
||||
|
||||
// t0, t1 = Split(xi, 128)
|
||||
$t0 = ParagonIE_Sodium_Core_Util::substr($ci, 0, 16);
|
||||
$t1 = ParagonIE_Sodium_Core_Util::substr($ci, 16, 16);
|
||||
|
||||
// out0 = t0 ^ z0
|
||||
// out1 = t1 ^ z1
|
||||
$out0 = $t0 ^ $z0;
|
||||
$out1 = $t1 ^ $z1;
|
||||
|
||||
// Update(out0, out1)
|
||||
// xi = out0 || out1
|
||||
$this->update($out0, $out1);
|
||||
return $out0 . $out1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $cn
|
||||
* @return string
|
||||
*/
|
||||
public function decPartial($cn)
|
||||
{
|
||||
$len = ParagonIE_Sodium_Core_Util::strlen($cn);
|
||||
|
||||
// z0 = S6 ^ S1 ^ (S2 & S3)
|
||||
$z0 = $this->state[6]
|
||||
^ $this->state[1]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[2], $this->state[3]);
|
||||
// z1 = S2 ^ S5 ^ (S6 & S7)
|
||||
$z1 = $this->state[2]
|
||||
^ $this->state[5]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[6], $this->state[7]);
|
||||
|
||||
// t0, t1 = Split(ZeroPad(cn, 256), 128)
|
||||
$cn = str_pad($cn, 32, "\0", STR_PAD_RIGHT);
|
||||
$t0 = ParagonIE_Sodium_Core_Util::substr($cn, 0, 16);
|
||||
$t1 = ParagonIE_Sodium_Core_Util::substr($cn, 16, 16);
|
||||
// out0 = t0 ^ z0
|
||||
// out1 = t1 ^ z1
|
||||
$out0 = $t0 ^ $z0;
|
||||
$out1 = $t1 ^ $z1;
|
||||
|
||||
// xn = Truncate(out0 || out1, |cn|)
|
||||
$xn = ParagonIE_Sodium_Core_Util::substr($out0 . $out1, 0, $len);
|
||||
|
||||
// v0, v1 = Split(ZeroPad(xn, 256), 128)
|
||||
$padded = str_pad($xn, 32, "\0", STR_PAD_RIGHT);
|
||||
$v0 = ParagonIE_Sodium_Core_Util::substr($padded, 0, 16);
|
||||
$v1 = ParagonIE_Sodium_Core_Util::substr($padded, 16, 16);
|
||||
// Update(v0, v1)
|
||||
$this->update($v0, $v1);
|
||||
|
||||
// return xn
|
||||
return $xn;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $xi
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public function enc($xi)
|
||||
{
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($xi) !== 32) {
|
||||
throw new SodiumException('Input must be two AES blocks in size');
|
||||
}
|
||||
|
||||
// z0 = S6 ^ S1 ^ (S2 & S3)
|
||||
$z0 = $this->state[6]
|
||||
^ $this->state[1]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[2], $this->state[3]);
|
||||
// z1 = S2 ^ S5 ^ (S6 & S7)
|
||||
$z1 = $this->state[2]
|
||||
^ $this->state[5]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[6], $this->state[7]);
|
||||
|
||||
// t0, t1 = Split(xi, 128)
|
||||
$t0 = ParagonIE_Sodium_Core_Util::substr($xi, 0, 16);
|
||||
$t1 = ParagonIE_Sodium_Core_Util::substr($xi, 16, 16);
|
||||
|
||||
// out0 = t0 ^ z0
|
||||
// out1 = t1 ^ z1
|
||||
$out0 = $t0 ^ $z0;
|
||||
$out1 = $t1 ^ $z1;
|
||||
|
||||
// Update(t0, t1)
|
||||
// ci = out0 || out1
|
||||
$this->update($t0, $t1);
|
||||
|
||||
// return ci
|
||||
return $out0 . $out1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $ad_len_bits
|
||||
* @param int $msg_len_bits
|
||||
* @return string
|
||||
*/
|
||||
public function finalize($ad_len_bits, $msg_len_bits)
|
||||
{
|
||||
$encoded = ParagonIE_Sodium_Core_Util::store64_le($ad_len_bits) .
|
||||
ParagonIE_Sodium_Core_Util::store64_le($msg_len_bits);
|
||||
$t = $this->state[2] ^ $encoded;
|
||||
for ($i = 0; $i < 7; ++$i) {
|
||||
$this->update($t, $t);
|
||||
}
|
||||
return ($this->state[0] ^ $this->state[1] ^ $this->state[2] ^ $this->state[3]) .
|
||||
($this->state[4] ^ $this->state[5] ^ $this->state[6] ^ $this->state[7]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $m0
|
||||
* @param string $m1
|
||||
* @return self
|
||||
*/
|
||||
public function update($m0, $m1)
|
||||
{
|
||||
/*
|
||||
S'0 = AESRound(S7, S0 ^ M0)
|
||||
S'1 = AESRound(S0, S1)
|
||||
S'2 = AESRound(S1, S2)
|
||||
S'3 = AESRound(S2, S3)
|
||||
S'4 = AESRound(S3, S4 ^ M1)
|
||||
S'5 = AESRound(S4, S5)
|
||||
S'6 = AESRound(S5, S6)
|
||||
S'7 = AESRound(S6, S7)
|
||||
*/
|
||||
list($s_0, $s_1) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[7], $this->state[0] ^ $m0,
|
||||
$this->state[0], $this->state[1]
|
||||
);
|
||||
|
||||
list($s_2, $s_3) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[1], $this->state[2],
|
||||
$this->state[2], $this->state[3]
|
||||
);
|
||||
|
||||
list($s_4, $s_5) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[3], $this->state[4] ^ $m1,
|
||||
$this->state[4], $this->state[5]
|
||||
);
|
||||
list($s_6, $s_7) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[5], $this->state[6],
|
||||
$this->state[6], $this->state[7]
|
||||
);
|
||||
|
||||
/*
|
||||
S0 = S'0
|
||||
S1 = S'1
|
||||
S2 = S'2
|
||||
S3 = S'3
|
||||
S4 = S'4
|
||||
S5 = S'5
|
||||
S6 = S'6
|
||||
S7 = S'7
|
||||
*/
|
||||
$this->state[0] = $s_0;
|
||||
$this->state[1] = $s_1;
|
||||
$this->state[2] = $s_2;
|
||||
$this->state[3] = $s_3;
|
||||
$this->state[4] = $s_4;
|
||||
$this->state[5] = $s_5;
|
||||
$this->state[6] = $s_6;
|
||||
$this->state[7] = $s_7;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,240 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_AEGIS_State256', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C0')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C0', "\x00\x01\x01\x02\x03\x05\x08\x0d\x15\x22\x37\x59\x90\xe9\x79\x62");
|
||||
}
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C1')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C1', "\xdb\x3d\x18\x55\x6d\xc2\x2f\xf1\x20\x11\x31\x42\x73\xb5\x28\xdd");
|
||||
}
|
||||
|
||||
class ParagonIE_Sodium_Core_AEGIS_State256
|
||||
{
|
||||
/** @var array<int, string> $state */
|
||||
protected $state;
|
||||
public function __construct()
|
||||
{
|
||||
$this->state = array_fill(0, 6, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal Only use this for unit tests!
|
||||
* @return string[]
|
||||
*/
|
||||
public function getState()
|
||||
{
|
||||
return array_values($this->state);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $input
|
||||
* @return self
|
||||
* @throws SodiumException
|
||||
*
|
||||
* @internal Only for unit tests
|
||||
*/
|
||||
public static function initForUnitTests(array $input)
|
||||
{
|
||||
if (count($input) < 6) {
|
||||
throw new SodiumException('invalid input');
|
||||
}
|
||||
$state = new self();
|
||||
for ($i = 0; $i < 6; ++$i) {
|
||||
$state->state[$i] = $input[$i];
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return self
|
||||
*/
|
||||
public static function init($key, $nonce)
|
||||
{
|
||||
$state = new self();
|
||||
$k0 = ParagonIE_Sodium_Core_Util::substr($key, 0, 16);
|
||||
$k1 = ParagonIE_Sodium_Core_Util::substr($key, 16, 16);
|
||||
$n0 = ParagonIE_Sodium_Core_Util::substr($nonce, 0, 16);
|
||||
$n1 = ParagonIE_Sodium_Core_Util::substr($nonce, 16, 16);
|
||||
|
||||
// S0 = k0 ^ n0
|
||||
// S1 = k1 ^ n1
|
||||
// S2 = C1
|
||||
// S3 = C0
|
||||
// S4 = k0 ^ C0
|
||||
// S5 = k1 ^ C1
|
||||
$k0_n0 = $k0 ^ $n0;
|
||||
$k1_n1 = $k1 ^ $n1;
|
||||
$state->state[0] = $k0_n0;
|
||||
$state->state[1] = $k1_n1;
|
||||
$state->state[2] = SODIUM_COMPAT_AEGIS_C1;
|
||||
$state->state[3] = SODIUM_COMPAT_AEGIS_C0;
|
||||
$state->state[4] = $k0 ^ SODIUM_COMPAT_AEGIS_C0;
|
||||
$state->state[5] = $k1 ^ SODIUM_COMPAT_AEGIS_C1;
|
||||
|
||||
// Repeat(4,
|
||||
// Update(k0)
|
||||
// Update(k1)
|
||||
// Update(k0 ^ n0)
|
||||
// Update(k1 ^ n1)
|
||||
// )
|
||||
for ($i = 0; $i < 4; ++$i) {
|
||||
$state->update($k0);
|
||||
$state->update($k1);
|
||||
$state->update($k0 ^ $n0);
|
||||
$state->update($k1 ^ $n1);
|
||||
}
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ai
|
||||
* @return self
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public function absorb($ai)
|
||||
{
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($ai) !== 16) {
|
||||
throw new SodiumException('Input must be an AES block in size');
|
||||
}
|
||||
return $this->update($ai);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ci
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public function dec($ci)
|
||||
{
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($ci) !== 16) {
|
||||
throw new SodiumException('Input must be an AES block in size');
|
||||
}
|
||||
// z = S1 ^ S4 ^ S5 ^ (S2 & S3)
|
||||
$z = $this->state[1]
|
||||
^ $this->state[4]
|
||||
^ $this->state[5]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[2], $this->state[3]);
|
||||
$xi = $ci ^ $z;
|
||||
$this->update($xi);
|
||||
return $xi;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $cn
|
||||
* @return string
|
||||
*/
|
||||
public function decPartial($cn)
|
||||
{
|
||||
$len = ParagonIE_Sodium_Core_Util::strlen($cn);
|
||||
// z = S1 ^ S4 ^ S5 ^ (S2 & S3)
|
||||
$z = $this->state[1]
|
||||
^ $this->state[4]
|
||||
^ $this->state[5]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[2], $this->state[3]);
|
||||
|
||||
// t = ZeroPad(cn, 128)
|
||||
$t = str_pad($cn, 16, "\0", STR_PAD_RIGHT);
|
||||
|
||||
// out = t ^ z
|
||||
$out = $t ^ $z;
|
||||
|
||||
// xn = Truncate(out, |cn|)
|
||||
$xn = ParagonIE_Sodium_Core_Util::substr($out, 0, $len);
|
||||
|
||||
// v = ZeroPad(xn, 128)
|
||||
$v = str_pad($xn, 16, "\0", STR_PAD_RIGHT);
|
||||
// Update(v)
|
||||
$this->update($v);
|
||||
|
||||
// return xn
|
||||
return $xn;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $xi
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public function enc($xi)
|
||||
{
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($xi) !== 16) {
|
||||
throw new SodiumException('Input must be an AES block in size');
|
||||
}
|
||||
// z = S1 ^ S4 ^ S5 ^ (S2 & S3)
|
||||
$z = $this->state[1]
|
||||
^ $this->state[4]
|
||||
^ $this->state[5]
|
||||
^ ParagonIE_Sodium_Core_Util::andStrings($this->state[2], $this->state[3]);
|
||||
$this->update($xi);
|
||||
return $xi ^ $z;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $ad_len_bits
|
||||
* @param int $msg_len_bits
|
||||
* @return string
|
||||
*/
|
||||
public function finalize($ad_len_bits, $msg_len_bits)
|
||||
{
|
||||
$encoded = ParagonIE_Sodium_Core_Util::store64_le($ad_len_bits) .
|
||||
ParagonIE_Sodium_Core_Util::store64_le($msg_len_bits);
|
||||
$t = $this->state[3] ^ $encoded;
|
||||
|
||||
for ($i = 0; $i < 7; ++$i) {
|
||||
$this->update($t);
|
||||
}
|
||||
|
||||
return ($this->state[0] ^ $this->state[1] ^ $this->state[2]) .
|
||||
($this->state[3] ^ $this->state[4] ^ $this->state[5]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $m
|
||||
* @return self
|
||||
*/
|
||||
public function update($m)
|
||||
{
|
||||
/*
|
||||
S'0 = AESRound(S5, S0 ^ M)
|
||||
S'1 = AESRound(S0, S1)
|
||||
S'2 = AESRound(S1, S2)
|
||||
S'3 = AESRound(S2, S3)
|
||||
S'4 = AESRound(S3, S4)
|
||||
S'5 = AESRound(S4, S5)
|
||||
*/
|
||||
list($s_0, $s_1) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[5],$this->state[0] ^ $m,
|
||||
$this->state[0], $this->state[1]
|
||||
);
|
||||
|
||||
list($s_2, $s_3) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[1], $this->state[2],
|
||||
$this->state[2], $this->state[3]
|
||||
);
|
||||
list($s_4, $s_5) = ParagonIE_Sodium_Core_AES::doubleRound(
|
||||
$this->state[3], $this->state[4],
|
||||
$this->state[4], $this->state[5]
|
||||
);
|
||||
|
||||
/*
|
||||
S0 = S'0
|
||||
S1 = S'1
|
||||
S2 = S'2
|
||||
S3 = S'3
|
||||
S4 = S'4
|
||||
S5 = S'5
|
||||
*/
|
||||
$this->state[0] = $s_0;
|
||||
$this->state[1] = $s_1;
|
||||
$this->state[2] = $s_2;
|
||||
$this->state[3] = $s_3;
|
||||
$this->state[4] = $s_4;
|
||||
$this->state[5] = $s_5;
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
<?php
|
||||
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C0')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C0', "\x00\x01\x01\x02\x03\x05\x08\x0d\x15\x22\x37\x59\x90\xe9\x79\x62");
|
||||
}
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C1')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C1', "\xdb\x3d\x18\x55\x6d\xc2\x2f\xf1\x20\x11\x31\x42\x73\xb5\x28\xdd");
|
||||
}
|
||||
|
||||
class ParagonIE_Sodium_Core_AEGIS128L extends ParagonIE_Sodium_Core_AES
|
||||
{
|
||||
/**
|
||||
* @param string $ct
|
||||
* @param string $tag
|
||||
* @param string $ad
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function decrypt($ct, $tag, $ad, $key, $nonce)
|
||||
{
|
||||
$state = self::init($key, $nonce);
|
||||
$ad_blocks = (self::strlen($ad) + 31) >> 5;
|
||||
for ($i = 0; $i < $ad_blocks; ++$i) {
|
||||
$ai = self::substr($ad, $i << 5, 32);
|
||||
if (self::strlen($ai) < 32) {
|
||||
$ai = str_pad($ai, 32, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
$state->absorb($ai);
|
||||
}
|
||||
|
||||
$msg = '';
|
||||
$cn = self::strlen($ct) & 31;
|
||||
$ct_blocks = self::strlen($ct) >> 5;
|
||||
for ($i = 0; $i < $ct_blocks; ++$i) {
|
||||
$msg .= $state->dec(self::substr($ct, $i << 5, 32));
|
||||
}
|
||||
if ($cn) {
|
||||
$start = $ct_blocks << 5;
|
||||
$msg .= $state->decPartial(self::substr($ct, $start, $cn));
|
||||
}
|
||||
$expected_tag = $state->finalize(
|
||||
self::strlen($ad) << 3,
|
||||
self::strlen($msg) << 3
|
||||
);
|
||||
if (!self::hashEquals($expected_tag, $tag)) {
|
||||
try {
|
||||
// The RFC says to erase msg, so we shall try:
|
||||
ParagonIE_Sodium_Compat::memzero($msg);
|
||||
} catch (SodiumException $ex) {
|
||||
// Do nothing if we cannot memzero
|
||||
}
|
||||
throw new SodiumException('verification failed');
|
||||
}
|
||||
return $msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $msg
|
||||
* @param string $ad
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return array
|
||||
*
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function encrypt($msg, $ad, $key, $nonce)
|
||||
{
|
||||
$state = self::init($key, $nonce);
|
||||
// ad_blocks = Split(ZeroPad(ad, 256), 256)
|
||||
// for ai in ad_blocks:
|
||||
// Absorb(ai)
|
||||
$ad_len = self::strlen($ad);
|
||||
$msg_len = self::strlen($msg);
|
||||
$ad_blocks = ($ad_len + 31) >> 5;
|
||||
for ($i = 0; $i < $ad_blocks; ++$i) {
|
||||
$ai = self::substr($ad, $i << 5, 32);
|
||||
if (self::strlen($ai) < 32) {
|
||||
$ai = str_pad($ai, 32, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
$state->absorb($ai);
|
||||
}
|
||||
|
||||
// msg_blocks = Split(ZeroPad(msg, 256), 256)
|
||||
// for xi in msg_blocks:
|
||||
// ct = ct || Enc(xi)
|
||||
$ct = '';
|
||||
$msg_blocks = ($msg_len + 31) >> 5;
|
||||
for ($i = 0; $i < $msg_blocks; ++$i) {
|
||||
$xi = self::substr($msg, $i << 5, 32);
|
||||
if (self::strlen($xi) < 32) {
|
||||
$xi = str_pad($xi, 32, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
$ct .= $state->enc($xi);
|
||||
}
|
||||
// tag = Finalize(|ad|, |msg|)
|
||||
// ct = Truncate(ct, |msg|)
|
||||
$tag = $state->finalize(
|
||||
$ad_len << 3,
|
||||
$msg_len << 3
|
||||
);
|
||||
// return ct and tag
|
||||
return array(
|
||||
self::substr($ct, 0, $msg_len),
|
||||
$tag
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return ParagonIE_Sodium_Core_AEGIS_State128L
|
||||
*/
|
||||
public static function init($key, $nonce)
|
||||
{
|
||||
return ParagonIE_Sodium_Core_AEGIS_State128L::init($key, $nonce);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C0')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C0', "\x00\x01\x01\x02\x03\x05\x08\x0d\x15\x22\x37\x59\x90\xe9\x79\x62");
|
||||
}
|
||||
if (!defined('SODIUM_COMPAT_AEGIS_C1')) {
|
||||
define('SODIUM_COMPAT_AEGIS_C1', "\xdb\x3d\x18\x55\x6d\xc2\x2f\xf1\x20\x11\x31\x42\x73\xb5\x28\xdd");
|
||||
}
|
||||
|
||||
class ParagonIE_Sodium_Core_AEGIS256 extends ParagonIE_Sodium_Core_AES
|
||||
{
|
||||
/**
|
||||
* @param string $ct
|
||||
* @param string $tag
|
||||
* @param string $ad
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function decrypt($ct, $tag, $ad, $key, $nonce)
|
||||
{
|
||||
$state = self::init($key, $nonce);
|
||||
|
||||
// ad_blocks = Split(ZeroPad(ad, 128), 128)
|
||||
$ad_blocks = (self::strlen($ad) + 15) >> 4;
|
||||
// for ai in ad_blocks:
|
||||
// Absorb(ai)
|
||||
for ($i = 0; $i < $ad_blocks; ++$i) {
|
||||
$ai = self::substr($ad, $i << 4, 16);
|
||||
if (self::strlen($ai) < 16) {
|
||||
$ai = str_pad($ai, 16, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
$state->absorb($ai);
|
||||
}
|
||||
|
||||
$msg = '';
|
||||
$cn = self::strlen($ct) & 15;
|
||||
$ct_blocks = self::strlen($ct) >> 4;
|
||||
// ct_blocks = Split(ZeroPad(ct, 128), 128)
|
||||
// cn = Tail(ct, |ct| mod 128)
|
||||
for ($i = 0; $i < $ct_blocks; ++$i) {
|
||||
$msg .= $state->dec(self::substr($ct, $i << 4, 16));
|
||||
}
|
||||
// if cn is not empty:
|
||||
// msg = msg || DecPartial(cn)
|
||||
if ($cn) {
|
||||
$start = $ct_blocks << 4;
|
||||
$msg .= $state->decPartial(self::substr($ct, $start, $cn));
|
||||
}
|
||||
$expected_tag = $state->finalize(
|
||||
self::strlen($ad) << 3,
|
||||
self::strlen($msg) << 3
|
||||
);
|
||||
if (!self::hashEquals($expected_tag, $tag)) {
|
||||
try {
|
||||
// The RFC says to erase msg, so we shall try:
|
||||
ParagonIE_Sodium_Compat::memzero($msg);
|
||||
} catch (SodiumException $ex) {
|
||||
// Do nothing if we cannot memzero
|
||||
}
|
||||
throw new SodiumException('verification failed');
|
||||
}
|
||||
return $msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $msg
|
||||
* @param string $ad
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return array
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function encrypt($msg, $ad, $key, $nonce)
|
||||
{
|
||||
$state = self::init($key, $nonce);
|
||||
$ad_len = self::strlen($ad);
|
||||
$msg_len = self::strlen($msg);
|
||||
$ad_blocks = ($ad_len + 15) >> 4;
|
||||
for ($i = 0; $i < $ad_blocks; ++$i) {
|
||||
$ai = self::substr($ad, $i << 4, 16);
|
||||
if (self::strlen($ai) < 16) {
|
||||
$ai = str_pad($ai, 16, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
$state->absorb($ai);
|
||||
}
|
||||
|
||||
$ct = '';
|
||||
$msg_blocks = ($msg_len + 15) >> 4;
|
||||
for ($i = 0; $i < $msg_blocks; ++$i) {
|
||||
$xi = self::substr($msg, $i << 4, 16);
|
||||
if (self::strlen($xi) < 16) {
|
||||
$xi = str_pad($xi, 16, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
$ct .= $state->enc($xi);
|
||||
}
|
||||
$tag = $state->finalize(
|
||||
$ad_len << 3,
|
||||
$msg_len << 3
|
||||
);
|
||||
return array(
|
||||
self::substr($ct, 0, $msg_len),
|
||||
$tag
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $key
|
||||
* @param string $nonce
|
||||
* @return ParagonIE_Sodium_Core_AEGIS_State256
|
||||
*/
|
||||
public static function init($key, $nonce)
|
||||
{
|
||||
return ParagonIE_Sodium_Core_AEGIS_State256::init($key, $nonce);
|
||||
}
|
||||
}
|
||||
+518
@@ -0,0 +1,518 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_AES', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bitsliced implementation of the AES block cipher.
|
||||
*
|
||||
* Based on the implementation provided by BearSSL.
|
||||
*
|
||||
* @internal This should only be used by sodium_compat
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_AES extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
/**
|
||||
* @var int[] AES round constants
|
||||
*/
|
||||
private static $Rcon = array(
|
||||
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36
|
||||
);
|
||||
|
||||
/**
|
||||
* Mutates the values of $q!
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_AES_Block $q
|
||||
* @return void
|
||||
*/
|
||||
public static function sbox(ParagonIE_Sodium_Core_AES_Block $q)
|
||||
{
|
||||
/**
|
||||
* @var int $x0
|
||||
* @var int $x1
|
||||
* @var int $x2
|
||||
* @var int $x3
|
||||
* @var int $x4
|
||||
* @var int $x5
|
||||
* @var int $x6
|
||||
* @var int $x7
|
||||
*/
|
||||
$x0 = $q[7] & self::U32_MAX;
|
||||
$x1 = $q[6] & self::U32_MAX;
|
||||
$x2 = $q[5] & self::U32_MAX;
|
||||
$x3 = $q[4] & self::U32_MAX;
|
||||
$x4 = $q[3] & self::U32_MAX;
|
||||
$x5 = $q[2] & self::U32_MAX;
|
||||
$x6 = $q[1] & self::U32_MAX;
|
||||
$x7 = $q[0] & self::U32_MAX;
|
||||
|
||||
$y14 = $x3 ^ $x5;
|
||||
$y13 = $x0 ^ $x6;
|
||||
$y9 = $x0 ^ $x3;
|
||||
$y8 = $x0 ^ $x5;
|
||||
$t0 = $x1 ^ $x2;
|
||||
$y1 = $t0 ^ $x7;
|
||||
$y4 = $y1 ^ $x3;
|
||||
$y12 = $y13 ^ $y14;
|
||||
$y2 = $y1 ^ $x0;
|
||||
$y5 = $y1 ^ $x6;
|
||||
$y3 = $y5 ^ $y8;
|
||||
$t1 = $x4 ^ $y12;
|
||||
$y15 = $t1 ^ $x5;
|
||||
$y20 = $t1 ^ $x1;
|
||||
$y6 = $y15 ^ $x7;
|
||||
$y10 = $y15 ^ $t0;
|
||||
$y11 = $y20 ^ $y9;
|
||||
$y7 = $x7 ^ $y11;
|
||||
$y17 = $y10 ^ $y11;
|
||||
$y19 = $y10 ^ $y8;
|
||||
$y16 = $t0 ^ $y11;
|
||||
$y21 = $y13 ^ $y16;
|
||||
$y18 = $x0 ^ $y16;
|
||||
|
||||
/*
|
||||
* Non-linear section.
|
||||
*/
|
||||
$t2 = $y12 & $y15;
|
||||
$t3 = $y3 & $y6;
|
||||
$t4 = $t3 ^ $t2;
|
||||
$t5 = $y4 & $x7;
|
||||
$t6 = $t5 ^ $t2;
|
||||
$t7 = $y13 & $y16;
|
||||
$t8 = $y5 & $y1;
|
||||
$t9 = $t8 ^ $t7;
|
||||
$t10 = $y2 & $y7;
|
||||
$t11 = $t10 ^ $t7;
|
||||
$t12 = $y9 & $y11;
|
||||
$t13 = $y14 & $y17;
|
||||
$t14 = $t13 ^ $t12;
|
||||
$t15 = $y8 & $y10;
|
||||
$t16 = $t15 ^ $t12;
|
||||
$t17 = $t4 ^ $t14;
|
||||
$t18 = $t6 ^ $t16;
|
||||
$t19 = $t9 ^ $t14;
|
||||
$t20 = $t11 ^ $t16;
|
||||
$t21 = $t17 ^ $y20;
|
||||
$t22 = $t18 ^ $y19;
|
||||
$t23 = $t19 ^ $y21;
|
||||
$t24 = $t20 ^ $y18;
|
||||
|
||||
$t25 = $t21 ^ $t22;
|
||||
$t26 = $t21 & $t23;
|
||||
$t27 = $t24 ^ $t26;
|
||||
$t28 = $t25 & $t27;
|
||||
$t29 = $t28 ^ $t22;
|
||||
$t30 = $t23 ^ $t24;
|
||||
$t31 = $t22 ^ $t26;
|
||||
$t32 = $t31 & $t30;
|
||||
$t33 = $t32 ^ $t24;
|
||||
$t34 = $t23 ^ $t33;
|
||||
$t35 = $t27 ^ $t33;
|
||||
$t36 = $t24 & $t35;
|
||||
$t37 = $t36 ^ $t34;
|
||||
$t38 = $t27 ^ $t36;
|
||||
$t39 = $t29 & $t38;
|
||||
$t40 = $t25 ^ $t39;
|
||||
|
||||
$t41 = $t40 ^ $t37;
|
||||
$t42 = $t29 ^ $t33;
|
||||
$t43 = $t29 ^ $t40;
|
||||
$t44 = $t33 ^ $t37;
|
||||
$t45 = $t42 ^ $t41;
|
||||
$z0 = $t44 & $y15;
|
||||
$z1 = $t37 & $y6;
|
||||
$z2 = $t33 & $x7;
|
||||
$z3 = $t43 & $y16;
|
||||
$z4 = $t40 & $y1;
|
||||
$z5 = $t29 & $y7;
|
||||
$z6 = $t42 & $y11;
|
||||
$z7 = $t45 & $y17;
|
||||
$z8 = $t41 & $y10;
|
||||
$z9 = $t44 & $y12;
|
||||
$z10 = $t37 & $y3;
|
||||
$z11 = $t33 & $y4;
|
||||
$z12 = $t43 & $y13;
|
||||
$z13 = $t40 & $y5;
|
||||
$z14 = $t29 & $y2;
|
||||
$z15 = $t42 & $y9;
|
||||
$z16 = $t45 & $y14;
|
||||
$z17 = $t41 & $y8;
|
||||
|
||||
/*
|
||||
* Bottom linear transformation.
|
||||
*/
|
||||
$t46 = $z15 ^ $z16;
|
||||
$t47 = $z10 ^ $z11;
|
||||
$t48 = $z5 ^ $z13;
|
||||
$t49 = $z9 ^ $z10;
|
||||
$t50 = $z2 ^ $z12;
|
||||
$t51 = $z2 ^ $z5;
|
||||
$t52 = $z7 ^ $z8;
|
||||
$t53 = $z0 ^ $z3;
|
||||
$t54 = $z6 ^ $z7;
|
||||
$t55 = $z16 ^ $z17;
|
||||
$t56 = $z12 ^ $t48;
|
||||
$t57 = $t50 ^ $t53;
|
||||
$t58 = $z4 ^ $t46;
|
||||
$t59 = $z3 ^ $t54;
|
||||
$t60 = $t46 ^ $t57;
|
||||
$t61 = $z14 ^ $t57;
|
||||
$t62 = $t52 ^ $t58;
|
||||
$t63 = $t49 ^ $t58;
|
||||
$t64 = $z4 ^ $t59;
|
||||
$t65 = $t61 ^ $t62;
|
||||
$t66 = $z1 ^ $t63;
|
||||
$s0 = $t59 ^ $t63;
|
||||
$s6 = $t56 ^ ~$t62;
|
||||
$s7 = $t48 ^ ~$t60;
|
||||
$t67 = $t64 ^ $t65;
|
||||
$s3 = $t53 ^ $t66;
|
||||
$s4 = $t51 ^ $t66;
|
||||
$s5 = $t47 ^ $t65;
|
||||
$s1 = $t64 ^ ~$s3;
|
||||
$s2 = $t55 ^ ~$t67;
|
||||
|
||||
$q[7] = $s0 & self::U32_MAX;
|
||||
$q[6] = $s1 & self::U32_MAX;
|
||||
$q[5] = $s2 & self::U32_MAX;
|
||||
$q[4] = $s3 & self::U32_MAX;
|
||||
$q[3] = $s4 & self::U32_MAX;
|
||||
$q[2] = $s5 & self::U32_MAX;
|
||||
$q[1] = $s6 & self::U32_MAX;
|
||||
$q[0] = $s7 & self::U32_MAX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutates the values of $q!
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_AES_Block $q
|
||||
* @return void
|
||||
*/
|
||||
public static function invSbox(ParagonIE_Sodium_Core_AES_Block $q)
|
||||
{
|
||||
self::processInversion($q);
|
||||
self::sbox($q);
|
||||
self::processInversion($q);
|
||||
}
|
||||
|
||||
/**
|
||||
* This is some boilerplate code needed to invert an S-box. Rather than repeat the code
|
||||
* twice, I moved it to a protected method.
|
||||
*
|
||||
* Mutates $q
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_AES_Block $q
|
||||
* @return void
|
||||
*/
|
||||
protected static function processInversion(ParagonIE_Sodium_Core_AES_Block $q)
|
||||
{
|
||||
$q0 = (~$q[0]) & self::U32_MAX;
|
||||
$q1 = (~$q[1]) & self::U32_MAX;
|
||||
$q2 = $q[2] & self::U32_MAX;
|
||||
$q3 = $q[3] & self::U32_MAX;
|
||||
$q4 = $q[4] & self::U32_MAX;
|
||||
$q5 = (~$q[5]) & self::U32_MAX;
|
||||
$q6 = (~$q[6]) & self::U32_MAX;
|
||||
$q7 = $q[7] & self::U32_MAX;
|
||||
$q[7] = ($q1 ^ $q4 ^ $q6) & self::U32_MAX;
|
||||
$q[6] = ($q0 ^ $q3 ^ $q5) & self::U32_MAX;
|
||||
$q[5] = ($q7 ^ $q2 ^ $q4) & self::U32_MAX;
|
||||
$q[4] = ($q6 ^ $q1 ^ $q3) & self::U32_MAX;
|
||||
$q[3] = ($q5 ^ $q0 ^ $q2) & self::U32_MAX;
|
||||
$q[2] = ($q4 ^ $q7 ^ $q1) & self::U32_MAX;
|
||||
$q[1] = ($q3 ^ $q6 ^ $q0) & self::U32_MAX;
|
||||
$q[0] = ($q2 ^ $q5 ^ $q7) & self::U32_MAX;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $x
|
||||
* @return int
|
||||
*/
|
||||
public static function subWord($x)
|
||||
{
|
||||
$q = ParagonIE_Sodium_Core_AES_Block::fromArray(
|
||||
array($x, $x, $x, $x, $x, $x, $x, $x)
|
||||
);
|
||||
$q->orthogonalize();
|
||||
self::sbox($q);
|
||||
$q->orthogonalize();
|
||||
return $q[0] & self::U32_MAX;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate the key schedule from a given random key
|
||||
*
|
||||
* @param string $key
|
||||
* @return ParagonIE_Sodium_Core_AES_KeySchedule
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function keySchedule($key)
|
||||
{
|
||||
$key_len = self::strlen($key);
|
||||
switch ($key_len) {
|
||||
case 16:
|
||||
$num_rounds = 10;
|
||||
break;
|
||||
case 24:
|
||||
$num_rounds = 12;
|
||||
break;
|
||||
case 32:
|
||||
$num_rounds = 14;
|
||||
break;
|
||||
default:
|
||||
throw new SodiumException('Invalid key length: ' . $key_len);
|
||||
}
|
||||
$skey = array();
|
||||
$comp_skey = array();
|
||||
$nk = $key_len >> 2;
|
||||
$nkf = ($num_rounds + 1) << 2;
|
||||
$tmp = 0;
|
||||
|
||||
for ($i = 0; $i < $nk; ++$i) {
|
||||
$tmp = self::load_4(self::substr($key, $i << 2, 4));
|
||||
$skey[($i << 1)] = $tmp;
|
||||
$skey[($i << 1) + 1] = $tmp;
|
||||
}
|
||||
|
||||
for ($i = $nk, $j = 0, $k = 0; $i < $nkf; ++$i) {
|
||||
if ($j === 0) {
|
||||
$tmp = (($tmp & 0xff) << 24) | ($tmp >> 8);
|
||||
$tmp = (self::subWord($tmp) ^ self::$Rcon[$k]) & self::U32_MAX;
|
||||
} elseif ($nk > 6 && $j === 4) {
|
||||
$tmp = self::subWord($tmp);
|
||||
}
|
||||
$tmp ^= $skey[($i - $nk) << 1];
|
||||
$skey[($i << 1)] = $tmp & self::U32_MAX;
|
||||
$skey[($i << 1) + 1] = $tmp & self::U32_MAX;
|
||||
if (++$j === $nk) {
|
||||
/** @psalm-suppress LoopInvalidation */
|
||||
$j = 0;
|
||||
++$k;
|
||||
}
|
||||
}
|
||||
for ($i = 0; $i < $nkf; $i += 4) {
|
||||
$q = ParagonIE_Sodium_Core_AES_Block::fromArray(
|
||||
array_slice($skey, $i << 1, 8)
|
||||
);
|
||||
$q->orthogonalize();
|
||||
// We have to overwrite $skey since we're not using C pointers like BearSSL did
|
||||
for ($j = 0; $j < 8; ++$j) {
|
||||
$skey[($i << 1) + $j] = $q[$j];
|
||||
}
|
||||
}
|
||||
for ($i = 0, $j = 0; $i < $nkf; ++$i, $j += 2) {
|
||||
$comp_skey[$i] = ($skey[$j] & 0x55555555)
|
||||
| ($skey[$j + 1] & 0xAAAAAAAA);
|
||||
}
|
||||
return new ParagonIE_Sodium_Core_AES_KeySchedule($comp_skey, $num_rounds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutates $q
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_AES_KeySchedule $skey
|
||||
* @param ParagonIE_Sodium_Core_AES_Block $q
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*/
|
||||
public static function addRoundKey(
|
||||
ParagonIE_Sodium_Core_AES_Block $q,
|
||||
ParagonIE_Sodium_Core_AES_KeySchedule $skey,
|
||||
$offset = 0
|
||||
) {
|
||||
$block = $skey->getRoundKey($offset);
|
||||
for ($j = 0; $j < 8; ++$j) {
|
||||
$q[$j] = ($q[$j] ^ $block[$j]) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This mainly exists for testing, as we need the round key features for AEGIS.
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function decryptBlockECB($message, $key)
|
||||
{
|
||||
if (self::strlen($message) !== 16) {
|
||||
throw new SodiumException('decryptBlockECB() expects a 16 byte message');
|
||||
}
|
||||
$skey = self::keySchedule($key)->expand();
|
||||
$q = ParagonIE_Sodium_Core_AES_Block::init();
|
||||
$q[0] = self::load_4(self::substr($message, 0, 4));
|
||||
$q[2] = self::load_4(self::substr($message, 4, 4));
|
||||
$q[4] = self::load_4(self::substr($message, 8, 4));
|
||||
$q[6] = self::load_4(self::substr($message, 12, 4));
|
||||
|
||||
$q->orthogonalize();
|
||||
self::bitsliceDecryptBlock($skey, $q);
|
||||
$q->orthogonalize();
|
||||
|
||||
return self::store32_le($q[0]) .
|
||||
self::store32_le($q[2]) .
|
||||
self::store32_le($q[4]) .
|
||||
self::store32_le($q[6]);
|
||||
}
|
||||
|
||||
/**
|
||||
* This mainly exists for testing, as we need the round key features for AEGIS.
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function encryptBlockECB($message, $key)
|
||||
{
|
||||
if (self::strlen($message) !== 16) {
|
||||
throw new SodiumException('encryptBlockECB() expects a 16 byte message');
|
||||
}
|
||||
$comp_skey = self::keySchedule($key);
|
||||
$skey = $comp_skey->expand();
|
||||
$q = ParagonIE_Sodium_Core_AES_Block::init();
|
||||
$q[0] = self::load_4(self::substr($message, 0, 4));
|
||||
$q[2] = self::load_4(self::substr($message, 4, 4));
|
||||
$q[4] = self::load_4(self::substr($message, 8, 4));
|
||||
$q[6] = self::load_4(self::substr($message, 12, 4));
|
||||
|
||||
$q->orthogonalize();
|
||||
self::bitsliceEncryptBlock($skey, $q);
|
||||
$q->orthogonalize();
|
||||
|
||||
return self::store32_le($q[0]) .
|
||||
self::store32_le($q[2]) .
|
||||
self::store32_le($q[4]) .
|
||||
self::store32_le($q[6]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mutates $q
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_AES_Expanded $skey
|
||||
* @param ParagonIE_Sodium_Core_AES_Block $q
|
||||
* @return void
|
||||
*/
|
||||
public static function bitsliceEncryptBlock(
|
||||
ParagonIE_Sodium_Core_AES_Expanded $skey,
|
||||
ParagonIE_Sodium_Core_AES_Block $q
|
||||
) {
|
||||
self::addRoundKey($q, $skey);
|
||||
for ($u = 1; $u < $skey->getNumRounds(); ++$u) {
|
||||
self::sbox($q);
|
||||
$q->shiftRows();
|
||||
$q->mixColumns();
|
||||
self::addRoundKey($q, $skey, ($u << 3));
|
||||
}
|
||||
self::sbox($q);
|
||||
$q->shiftRows();
|
||||
self::addRoundKey($q, $skey, ($skey->getNumRounds() << 3));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
*/
|
||||
public static function aesRound($x, $y)
|
||||
{
|
||||
$q = ParagonIE_Sodium_Core_AES_Block::init();
|
||||
$q[0] = self::load_4(self::substr($x, 0, 4));
|
||||
$q[2] = self::load_4(self::substr($x, 4, 4));
|
||||
$q[4] = self::load_4(self::substr($x, 8, 4));
|
||||
$q[6] = self::load_4(self::substr($x, 12, 4));
|
||||
|
||||
$rk = ParagonIE_Sodium_Core_AES_Block::init();
|
||||
$rk[0] = $rk[1] = self::load_4(self::substr($y, 0, 4));
|
||||
$rk[2] = $rk[3] = self::load_4(self::substr($y, 4, 4));
|
||||
$rk[4] = $rk[5] = self::load_4(self::substr($y, 8, 4));
|
||||
$rk[6] = $rk[7] = self::load_4(self::substr($y, 12, 4));
|
||||
|
||||
$q->orthogonalize();
|
||||
self::sbox($q);
|
||||
$q->shiftRows();
|
||||
$q->mixColumns();
|
||||
$q->orthogonalize();
|
||||
// add round key without key schedule:
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$q[$i] ^= $rk[$i];
|
||||
}
|
||||
return self::store32_le($q[0]) .
|
||||
self::store32_le($q[2]) .
|
||||
self::store32_le($q[4]) .
|
||||
self::store32_le($q[6]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Process two AES blocks in one shot.
|
||||
*
|
||||
* @param string $b0 First AES block
|
||||
* @param string $rk0 First round key
|
||||
* @param string $b1 Second AES block
|
||||
* @param string $rk1 Second round key
|
||||
* @return string[]
|
||||
*/
|
||||
public static function doubleRound($b0, $rk0, $b1, $rk1)
|
||||
{
|
||||
$q = ParagonIE_Sodium_Core_AES_Block::init();
|
||||
// First block
|
||||
$q[0] = self::load_4(self::substr($b0, 0, 4));
|
||||
$q[2] = self::load_4(self::substr($b0, 4, 4));
|
||||
$q[4] = self::load_4(self::substr($b0, 8, 4));
|
||||
$q[6] = self::load_4(self::substr($b0, 12, 4));
|
||||
// Second block
|
||||
$q[1] = self::load_4(self::substr($b1, 0, 4));
|
||||
$q[3] = self::load_4(self::substr($b1, 4, 4));
|
||||
$q[5] = self::load_4(self::substr($b1, 8, 4));
|
||||
$q[7] = self::load_4(self::substr($b1, 12, 4));;
|
||||
|
||||
$rk = ParagonIE_Sodium_Core_AES_Block::init();
|
||||
// First round key
|
||||
$rk[0] = self::load_4(self::substr($rk0, 0, 4));
|
||||
$rk[2] = self::load_4(self::substr($rk0, 4, 4));
|
||||
$rk[4] = self::load_4(self::substr($rk0, 8, 4));
|
||||
$rk[6] = self::load_4(self::substr($rk0, 12, 4));
|
||||
// Second round key
|
||||
$rk[1] = self::load_4(self::substr($rk1, 0, 4));
|
||||
$rk[3] = self::load_4(self::substr($rk1, 4, 4));
|
||||
$rk[5] = self::load_4(self::substr($rk1, 8, 4));
|
||||
$rk[7] = self::load_4(self::substr($rk1, 12, 4));
|
||||
|
||||
$q->orthogonalize();
|
||||
self::sbox($q);
|
||||
$q->shiftRows();
|
||||
$q->mixColumns();
|
||||
$q->orthogonalize();
|
||||
// add round key without key schedule:
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$q[$i] ^= $rk[$i];
|
||||
}
|
||||
return array(
|
||||
self::store32_le($q[0]) . self::store32_le($q[2]) . self::store32_le($q[4]) . self::store32_le($q[6]),
|
||||
self::store32_le($q[1]) . self::store32_le($q[3]) . self::store32_le($q[5]) . self::store32_le($q[7]),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ParagonIE_Sodium_Core_AES_Expanded $skey
|
||||
* @param ParagonIE_Sodium_Core_AES_Block $q
|
||||
* @return void
|
||||
*/
|
||||
public static function bitsliceDecryptBlock(
|
||||
ParagonIE_Sodium_Core_AES_Expanded $skey,
|
||||
ParagonIE_Sodium_Core_AES_Block $q
|
||||
) {
|
||||
self::addRoundKey($q, $skey, ($skey->getNumRounds() << 3));
|
||||
for ($u = $skey->getNumRounds() - 1; $u > 0; --$u) {
|
||||
$q->inverseShiftRows();
|
||||
self::invSbox($q);
|
||||
self::addRoundKey($q, $skey, ($u << 3));
|
||||
$q->inverseMixColumns();
|
||||
}
|
||||
$q->inverseShiftRows();
|
||||
self::invSbox($q);
|
||||
self::addRoundKey($q, $skey, ($u << 3));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_AES_Block', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal This should only be used by sodium_compat
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_AES_Block extends SplFixedArray
|
||||
{
|
||||
/**
|
||||
* @var array<int, int>
|
||||
*/
|
||||
protected $values = array();
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $size;
|
||||
|
||||
/**
|
||||
* @param int $size
|
||||
*/
|
||||
public function __construct($size = 8)
|
||||
{
|
||||
parent::__construct($size);
|
||||
$this->size = $size;
|
||||
$this->values = array_fill(0, $size, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public static function init()
|
||||
{
|
||||
return new self(8);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param array<int, int> $array
|
||||
* @param bool $save_indexes
|
||||
* @return self
|
||||
*
|
||||
* @psalm-suppress MethodSignatureMismatch
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public static function fromArray($array, $save_indexes = null)
|
||||
{
|
||||
$count = count($array);
|
||||
if ($save_indexes) {
|
||||
$keys = array_keys($array);
|
||||
} else {
|
||||
$keys = range(0, $count - 1);
|
||||
}
|
||||
$array = array_values($array);
|
||||
/** @var array<int, int> $keys */
|
||||
|
||||
$obj = new ParagonIE_Sodium_Core_AES_Block();
|
||||
if ($save_indexes) {
|
||||
for ($i = 0; $i < $count; ++$i) {
|
||||
$obj->offsetSet($keys[$i], $array[$i]);
|
||||
}
|
||||
} else {
|
||||
for ($i = 0; $i < $count; ++$i) {
|
||||
$obj->offsetSet($i, $array[$i]);
|
||||
}
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int|null $offset
|
||||
* @param int $value
|
||||
* @return void
|
||||
*
|
||||
* @psalm-suppress MethodSignatureMismatch
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
if (!is_int($value)) {
|
||||
throw new InvalidArgumentException('Expected an integer');
|
||||
}
|
||||
if (is_null($offset)) {
|
||||
$this->values[] = $value;
|
||||
} else {
|
||||
$this->values[$offset] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return bool
|
||||
*
|
||||
* @psalm-suppress MethodSignatureMismatch
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return isset($this->values[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return void
|
||||
*
|
||||
* @psalm-suppress MethodSignatureMismatch
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
unset($this->values[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return int
|
||||
*
|
||||
* @psalm-suppress MethodSignatureMismatch
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
if (!isset($this->values[$offset])) {
|
||||
$this->values[$offset] = 0;
|
||||
}
|
||||
return (int) ($this->values[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __debugInfo()
|
||||
{
|
||||
$out = array();
|
||||
foreach ($this->values as $v) {
|
||||
$out[] = str_pad(dechex($v), 8, '0', STR_PAD_LEFT);
|
||||
}
|
||||
return array(implode(', ', $out));
|
||||
/*
|
||||
return array(implode(', ', $this->values));
|
||||
*/
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $cl low bit mask
|
||||
* @param int $ch high bit mask
|
||||
* @param int $s shift
|
||||
* @param int $x index 1
|
||||
* @param int $y index 2
|
||||
* @return self
|
||||
*/
|
||||
public function swapN($cl, $ch, $s, $x, $y)
|
||||
{
|
||||
static $u32mask = ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$a = $this->values[$x] & $u32mask;
|
||||
$b = $this->values[$y] & $u32mask;
|
||||
// (x) = (a & cl) | ((b & cl) << (s));
|
||||
$this->values[$x] = ($a & $cl) | ((($b & $cl) << $s) & $u32mask);
|
||||
// (y) = ((a & ch) >> (s)) | (b & ch);
|
||||
$this->values[$y] = ((($a & $ch) & $u32mask) >> $s) | ($b & $ch);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $x index 1
|
||||
* @param int $y index 2
|
||||
* @return self
|
||||
*/
|
||||
public function swap2($x, $y)
|
||||
{
|
||||
return $this->swapN(0x55555555, 0xAAAAAAAA, 1, $x, $y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $x index 1
|
||||
* @param int $y index 2
|
||||
* @return self
|
||||
*/
|
||||
public function swap4($x, $y)
|
||||
{
|
||||
return $this->swapN(0x33333333, 0xCCCCCCCC, 2, $x, $y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $x index 1
|
||||
* @param int $y index 2
|
||||
* @return self
|
||||
*/
|
||||
public function swap8($x, $y)
|
||||
{
|
||||
return $this->swapN(0x0F0F0F0F, 0xF0F0F0F0, 4, $x, $y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function orthogonalize()
|
||||
{
|
||||
return $this
|
||||
->swap2(0, 1)
|
||||
->swap2(2, 3)
|
||||
->swap2(4, 5)
|
||||
->swap2(6, 7)
|
||||
|
||||
->swap4(0, 2)
|
||||
->swap4(1, 3)
|
||||
->swap4(4, 6)
|
||||
->swap4(5, 7)
|
||||
|
||||
->swap8(0, 4)
|
||||
->swap8(1, 5)
|
||||
->swap8(2, 6)
|
||||
->swap8(3, 7);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function shiftRows()
|
||||
{
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$x = $this->values[$i] & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$this->values[$i] = (
|
||||
($x & 0x000000FF)
|
||||
| (($x & 0x0000FC00) >> 2) | (($x & 0x00000300) << 6)
|
||||
| (($x & 0x00F00000) >> 4) | (($x & 0x000F0000) << 4)
|
||||
| (($x & 0xC0000000) >> 6) | (($x & 0x3F000000) << 2)
|
||||
) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $x
|
||||
* @return int
|
||||
*/
|
||||
public static function rotr16($x)
|
||||
{
|
||||
return (($x << 16) & ParagonIE_Sodium_Core_Util::U32_MAX) | ($x >> 16);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function mixColumns()
|
||||
{
|
||||
$q0 = $this->values[0];
|
||||
$q1 = $this->values[1];
|
||||
$q2 = $this->values[2];
|
||||
$q3 = $this->values[3];
|
||||
$q4 = $this->values[4];
|
||||
$q5 = $this->values[5];
|
||||
$q6 = $this->values[6];
|
||||
$q7 = $this->values[7];
|
||||
$r0 = (($q0 >> 8) | ($q0 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r1 = (($q1 >> 8) | ($q1 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r2 = (($q2 >> 8) | ($q2 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r3 = (($q3 >> 8) | ($q3 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r4 = (($q4 >> 8) | ($q4 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r5 = (($q5 >> 8) | ($q5 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r6 = (($q6 >> 8) | ($q6 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r7 = (($q7 >> 8) | ($q7 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
|
||||
$this->values[0] = $q7 ^ $r7 ^ $r0 ^ self::rotr16($q0 ^ $r0);
|
||||
$this->values[1] = $q0 ^ $r0 ^ $q7 ^ $r7 ^ $r1 ^ self::rotr16($q1 ^ $r1);
|
||||
$this->values[2] = $q1 ^ $r1 ^ $r2 ^ self::rotr16($q2 ^ $r2);
|
||||
$this->values[3] = $q2 ^ $r2 ^ $q7 ^ $r7 ^ $r3 ^ self::rotr16($q3 ^ $r3);
|
||||
$this->values[4] = $q3 ^ $r3 ^ $q7 ^ $r7 ^ $r4 ^ self::rotr16($q4 ^ $r4);
|
||||
$this->values[5] = $q4 ^ $r4 ^ $r5 ^ self::rotr16($q5 ^ $r5);
|
||||
$this->values[6] = $q5 ^ $r5 ^ $r6 ^ self::rotr16($q6 ^ $r6);
|
||||
$this->values[7] = $q6 ^ $r6 ^ $r7 ^ self::rotr16($q7 ^ $r7);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function inverseMixColumns()
|
||||
{
|
||||
$q0 = $this->values[0];
|
||||
$q1 = $this->values[1];
|
||||
$q2 = $this->values[2];
|
||||
$q3 = $this->values[3];
|
||||
$q4 = $this->values[4];
|
||||
$q5 = $this->values[5];
|
||||
$q6 = $this->values[6];
|
||||
$q7 = $this->values[7];
|
||||
$r0 = (($q0 >> 8) | ($q0 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r1 = (($q1 >> 8) | ($q1 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r2 = (($q2 >> 8) | ($q2 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r3 = (($q3 >> 8) | ($q3 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r4 = (($q4 >> 8) | ($q4 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r5 = (($q5 >> 8) | ($q5 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r6 = (($q6 >> 8) | ($q6 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$r7 = (($q7 >> 8) | ($q7 << 24)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
|
||||
$this->values[0] = $q5 ^ $q6 ^ $q7 ^ $r0 ^ $r5 ^ $r7 ^ self::rotr16($q0 ^ $q5 ^ $q6 ^ $r0 ^ $r5);
|
||||
$this->values[1] = $q0 ^ $q5 ^ $r0 ^ $r1 ^ $r5 ^ $r6 ^ $r7 ^ self::rotr16($q1 ^ $q5 ^ $q7 ^ $r1 ^ $r5 ^ $r6);
|
||||
$this->values[2] = $q0 ^ $q1 ^ $q6 ^ $r1 ^ $r2 ^ $r6 ^ $r7 ^ self::rotr16($q0 ^ $q2 ^ $q6 ^ $r2 ^ $r6 ^ $r7);
|
||||
$this->values[3] = $q0 ^ $q1 ^ $q2 ^ $q5 ^ $q6 ^ $r0 ^ $r2 ^ $r3 ^ $r5 ^ self::rotr16($q0 ^ $q1 ^ $q3 ^ $q5 ^ $q6 ^ $q7 ^ $r0 ^ $r3 ^ $r5 ^ $r7);
|
||||
$this->values[4] = $q1 ^ $q2 ^ $q3 ^ $q5 ^ $r1 ^ $r3 ^ $r4 ^ $r5 ^ $r6 ^ $r7 ^ self::rotr16($q1 ^ $q2 ^ $q4 ^ $q5 ^ $q7 ^ $r1 ^ $r4 ^ $r5 ^ $r6);
|
||||
$this->values[5] = $q2 ^ $q3 ^ $q4 ^ $q6 ^ $r2 ^ $r4 ^ $r5 ^ $r6 ^ $r7 ^ self::rotr16($q2 ^ $q3 ^ $q5 ^ $q6 ^ $r2 ^ $r5 ^ $r6 ^ $r7);
|
||||
$this->values[6] = $q3 ^ $q4 ^ $q5 ^ $q7 ^ $r3 ^ $r5 ^ $r6 ^ $r7 ^ self::rotr16($q3 ^ $q4 ^ $q6 ^ $q7 ^ $r3 ^ $r6 ^ $r7);
|
||||
$this->values[7] = $q4 ^ $q5 ^ $q6 ^ $r4 ^ $r6 ^ $r7 ^ self::rotr16($q4 ^ $q5 ^ $q7 ^ $r4 ^ $r7);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function inverseShiftRows()
|
||||
{
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$x = $this->values[$i];
|
||||
$this->values[$i] = ParagonIE_Sodium_Core_Util::U32_MAX & (
|
||||
($x & 0x000000FF)
|
||||
| (($x & 0x00003F00) << 2) | (($x & 0x0000C000) >> 6)
|
||||
| (($x & 0x000F0000) << 4) | (($x & 0x00F00000) >> 4)
|
||||
| (($x & 0x03000000) << 6) | (($x & 0xFC000000) >> 2)
|
||||
);
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_AES_Expanded', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal This should only be used by sodium_compat
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_AES_Expanded extends ParagonIE_Sodium_Core_AES_KeySchedule
|
||||
{
|
||||
/** @var bool $expanded */
|
||||
protected $expanded = true;
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_AES_KeySchedule', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal This should only be used by sodium_compat
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_AES_KeySchedule
|
||||
{
|
||||
/** @var array<int, int> $skey -- has size 120 */
|
||||
protected $skey;
|
||||
|
||||
/** @var bool $expanded */
|
||||
protected $expanded = false;
|
||||
|
||||
/** @var int $numRounds */
|
||||
private $numRounds;
|
||||
|
||||
/**
|
||||
* @param array $skey
|
||||
* @param int $numRounds
|
||||
*/
|
||||
public function __construct(array $skey, $numRounds = 10)
|
||||
{
|
||||
$this->skey = $skey;
|
||||
$this->numRounds = $numRounds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a value at an arbitrary index. Mostly used for unit testing.
|
||||
*
|
||||
* @param int $i
|
||||
* @return int
|
||||
*/
|
||||
public function get($i)
|
||||
{
|
||||
return $this->skey[$i];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int
|
||||
*/
|
||||
public function getNumRounds()
|
||||
{
|
||||
return $this->numRounds;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $offset
|
||||
* @return ParagonIE_Sodium_Core_AES_Block
|
||||
*/
|
||||
public function getRoundKey($offset)
|
||||
{
|
||||
return ParagonIE_Sodium_Core_AES_Block::fromArray(
|
||||
array_slice($this->skey, $offset, 8)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an expanded key schedule
|
||||
*
|
||||
* @return ParagonIE_Sodium_Core_AES_Expanded
|
||||
*/
|
||||
public function expand()
|
||||
{
|
||||
$exp = new ParagonIE_Sodium_Core_AES_Expanded(
|
||||
array_fill(0, 120, 0),
|
||||
$this->numRounds
|
||||
);
|
||||
$n = ($exp->numRounds + 1) << 2;
|
||||
for ($u = 0, $v = 0; $u < $n; ++$u, $v += 2) {
|
||||
$x = $y = $this->skey[$u];
|
||||
$x &= 0x55555555;
|
||||
$exp->skey[$v] = ($x | ($x << 1)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
$y &= 0xAAAAAAAA;
|
||||
$exp->skey[$v + 1] = ($y | ($y >> 1)) & ParagonIE_Sodium_Core_Util::U32_MAX;
|
||||
}
|
||||
return $exp;
|
||||
}
|
||||
}
|
||||
+797
@@ -0,0 +1,797 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_BLAKE2b', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_BLAKE2b
|
||||
*
|
||||
* Based on the work of Devi Mandiri in devi/salt.
|
||||
*/
|
||||
abstract class ParagonIE_Sodium_Core_BLAKE2b extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
/**
|
||||
* @var SplFixedArray
|
||||
*/
|
||||
protected static $iv;
|
||||
|
||||
/**
|
||||
* @var array<int, array<int, int>>
|
||||
*/
|
||||
protected static $sigma = array(
|
||||
array( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
|
||||
array( 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3),
|
||||
array( 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4),
|
||||
array( 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8),
|
||||
array( 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13),
|
||||
array( 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9),
|
||||
array( 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11),
|
||||
array( 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10),
|
||||
array( 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5),
|
||||
array( 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13 , 0),
|
||||
array( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15),
|
||||
array( 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3)
|
||||
);
|
||||
|
||||
const BLOCKBYTES = 128;
|
||||
const OUTBYTES = 64;
|
||||
const KEYBYTES = 64;
|
||||
|
||||
/**
|
||||
* Turn two 32-bit integers into a fixed array representing a 64-bit integer.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $high
|
||||
* @param int $low
|
||||
* @return SplFixedArray
|
||||
* @psalm-suppress MixedAssignment
|
||||
*/
|
||||
public static function new64($high, $low)
|
||||
{
|
||||
if (PHP_INT_SIZE === 4) {
|
||||
throw new SodiumException("Error, use 32-bit");
|
||||
}
|
||||
$i64 = new SplFixedArray(2);
|
||||
$i64[0] = $high & 0xffffffff;
|
||||
$i64[1] = $low & 0xffffffff;
|
||||
return $i64;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an arbitrary number into an SplFixedArray of two 32-bit integers
|
||||
* that represents a 64-bit integer.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $num
|
||||
* @return SplFixedArray
|
||||
*/
|
||||
protected static function to64($num)
|
||||
{
|
||||
list($hi, $lo) = self::numericTo64BitInteger($num);
|
||||
return self::new64($hi, $lo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds two 64-bit integers together, returning their sum as a SplFixedArray
|
||||
* containing two 32-bit integers (representing a 64-bit integer).
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @param SplFixedArray $y
|
||||
* @return SplFixedArray
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedOperand
|
||||
*/
|
||||
protected static function add64($x, $y)
|
||||
{
|
||||
if (PHP_INT_SIZE === 4) {
|
||||
throw new SodiumException("Error, use 32-bit");
|
||||
}
|
||||
$l = ($x[1] + $y[1]) & 0xffffffff;
|
||||
return self::new64(
|
||||
(int) ($x[0] + $y[0] + (
|
||||
($l < $x[1]) ? 1 : 0
|
||||
)),
|
||||
(int) $l
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @param SplFixedArray $y
|
||||
* @param SplFixedArray $z
|
||||
* @return SplFixedArray
|
||||
*/
|
||||
protected static function add364($x, $y, $z)
|
||||
{
|
||||
return self::add64($x, self::add64($y, $z));
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @param SplFixedArray $y
|
||||
* @return SplFixedArray
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
protected static function xor64(SplFixedArray $x, SplFixedArray $y)
|
||||
{
|
||||
if (PHP_INT_SIZE === 4) {
|
||||
throw new SodiumException("Error, use 32-bit");
|
||||
}
|
||||
if (!is_numeric($x[0])) {
|
||||
throw new SodiumException('x[0] is not an integer');
|
||||
}
|
||||
if (!is_numeric($x[1])) {
|
||||
throw new SodiumException('x[1] is not an integer');
|
||||
}
|
||||
if (!is_numeric($y[0])) {
|
||||
throw new SodiumException('y[0] is not an integer');
|
||||
}
|
||||
if (!is_numeric($y[1])) {
|
||||
throw new SodiumException('y[1] is not an integer');
|
||||
}
|
||||
return self::new64(
|
||||
(int) (($x[0] ^ $y[0]) & 0xffffffff),
|
||||
(int) (($x[1] ^ $y[1]) & 0xffffffff)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @param int $c
|
||||
* @return SplFixedArray
|
||||
* @psalm-suppress MixedAssignment
|
||||
*/
|
||||
public static function rotr64($x, $c)
|
||||
{
|
||||
if (PHP_INT_SIZE === 4) {
|
||||
throw new SodiumException("Error, use 32-bit");
|
||||
}
|
||||
if ($c >= 64) {
|
||||
$c %= 64;
|
||||
}
|
||||
if ($c >= 32) {
|
||||
/** @var int $tmp */
|
||||
$tmp = $x[0];
|
||||
$x[0] = $x[1];
|
||||
$x[1] = $tmp;
|
||||
$c -= 32;
|
||||
}
|
||||
if ($c === 0) {
|
||||
return $x;
|
||||
}
|
||||
|
||||
$l0 = 0;
|
||||
$c = 64 - $c;
|
||||
|
||||
/** @var int $c */
|
||||
if ($c < 32) {
|
||||
$h0 = ((int) ($x[0]) << $c) | (
|
||||
(
|
||||
(int) ($x[1]) & ((1 << $c) - 1)
|
||||
<<
|
||||
(32 - $c)
|
||||
) >> (32 - $c)
|
||||
);
|
||||
$l0 = (int) ($x[1]) << $c;
|
||||
} else {
|
||||
$h0 = (int) ($x[1]) << ($c - 32);
|
||||
}
|
||||
|
||||
$h1 = 0;
|
||||
$c1 = 64 - $c;
|
||||
|
||||
if ($c1 < 32) {
|
||||
$h1 = (int) ($x[0]) >> $c1;
|
||||
$l1 = ((int) ($x[1]) >> $c1) | ((int) ($x[0]) & ((1 << $c1) - 1)) << (32 - $c1);
|
||||
} else {
|
||||
$l1 = (int) ($x[0]) >> ($c1 - 32);
|
||||
}
|
||||
|
||||
return self::new64($h0 | $h1, $l0 | $l1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @return int
|
||||
* @psalm-suppress MixedOperand
|
||||
*/
|
||||
protected static function flatten64($x)
|
||||
{
|
||||
return (int) ($x[0] * 4294967296 + $x[1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @param int $i
|
||||
* @return SplFixedArray
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
protected static function load64(SplFixedArray $x, $i)
|
||||
{
|
||||
/** @var int $l */
|
||||
$l = (int) ($x[$i])
|
||||
| ((int) ($x[$i+1]) << 8)
|
||||
| ((int) ($x[$i+2]) << 16)
|
||||
| ((int) ($x[$i+3]) << 24);
|
||||
/** @var int $h */
|
||||
$h = (int) ($x[$i+4])
|
||||
| ((int) ($x[$i+5]) << 8)
|
||||
| ((int) ($x[$i+6]) << 16)
|
||||
| ((int) ($x[$i+7]) << 24);
|
||||
return self::new64($h, $l);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $x
|
||||
* @param int $i
|
||||
* @param SplFixedArray $u
|
||||
* @return void
|
||||
* @psalm-suppress MixedAssignment
|
||||
*/
|
||||
protected static function store64(SplFixedArray $x, $i, SplFixedArray $u)
|
||||
{
|
||||
$maxLength = $x->getSize() - 1;
|
||||
for ($j = 0; $j < 8; ++$j) {
|
||||
/*
|
||||
[0, 1, 2, 3, 4, 5, 6, 7]
|
||||
... becomes ...
|
||||
[0, 0, 0, 0, 1, 1, 1, 1]
|
||||
*/
|
||||
/** @var int $uIdx */
|
||||
$uIdx = ((7 - $j) & 4) >> 2;
|
||||
$x[$i] = ((int) ($u[$uIdx]) & 0xff);
|
||||
if (++$i > $maxLength) {
|
||||
return;
|
||||
}
|
||||
/** @psalm-suppress MixedOperand */
|
||||
$u[$uIdx] >>= 8;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* This just sets the $iv static variable.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public static function pseudoConstructor()
|
||||
{
|
||||
static $called = false;
|
||||
if ($called) {
|
||||
return;
|
||||
}
|
||||
self::$iv = new SplFixedArray(8);
|
||||
self::$iv[0] = self::new64(0x6a09e667, 0xf3bcc908);
|
||||
self::$iv[1] = self::new64(0xbb67ae85, 0x84caa73b);
|
||||
self::$iv[2] = self::new64(0x3c6ef372, 0xfe94f82b);
|
||||
self::$iv[3] = self::new64(0xa54ff53a, 0x5f1d36f1);
|
||||
self::$iv[4] = self::new64(0x510e527f, 0xade682d1);
|
||||
self::$iv[5] = self::new64(0x9b05688c, 0x2b3e6c1f);
|
||||
self::$iv[6] = self::new64(0x1f83d9ab, 0xfb41bd6b);
|
||||
self::$iv[7] = self::new64(0x5be0cd19, 0x137e2179);
|
||||
|
||||
$called = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a fresh BLAKE2 context.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @return SplFixedArray
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
*/
|
||||
protected static function context()
|
||||
{
|
||||
$ctx = new SplFixedArray(6);
|
||||
$ctx[0] = new SplFixedArray(8); // h
|
||||
$ctx[1] = new SplFixedArray(2); // t
|
||||
$ctx[2] = new SplFixedArray(2); // f
|
||||
$ctx[3] = new SplFixedArray(256); // buf
|
||||
$ctx[4] = 0; // buflen
|
||||
$ctx[5] = 0; // last_node (uint8_t)
|
||||
|
||||
for ($i = 8; $i--;) {
|
||||
$ctx[0][$i] = self::$iv[$i];
|
||||
}
|
||||
for ($i = 256; $i--;) {
|
||||
$ctx[3][$i] = 0;
|
||||
}
|
||||
|
||||
$zero = self::new64(0, 0);
|
||||
$ctx[1][0] = $zero;
|
||||
$ctx[1][1] = $zero;
|
||||
$ctx[2][0] = $zero;
|
||||
$ctx[2][1] = $zero;
|
||||
|
||||
return $ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $ctx
|
||||
* @param SplFixedArray $buf
|
||||
* @return void
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
protected static function compress(SplFixedArray $ctx, SplFixedArray $buf)
|
||||
{
|
||||
$m = new SplFixedArray(16);
|
||||
$v = new SplFixedArray(16);
|
||||
|
||||
for ($i = 16; $i--;) {
|
||||
$m[$i] = self::load64($buf, $i << 3);
|
||||
}
|
||||
|
||||
for ($i = 8; $i--;) {
|
||||
$v[$i] = $ctx[0][$i];
|
||||
}
|
||||
|
||||
$v[ 8] = self::$iv[0];
|
||||
$v[ 9] = self::$iv[1];
|
||||
$v[10] = self::$iv[2];
|
||||
$v[11] = self::$iv[3];
|
||||
|
||||
$v[12] = self::xor64($ctx[1][0], self::$iv[4]);
|
||||
$v[13] = self::xor64($ctx[1][1], self::$iv[5]);
|
||||
$v[14] = self::xor64($ctx[2][0], self::$iv[6]);
|
||||
$v[15] = self::xor64($ctx[2][1], self::$iv[7]);
|
||||
|
||||
for ($r = 0; $r < 12; ++$r) {
|
||||
$v = self::G($r, 0, 0, 4, 8, 12, $v, $m);
|
||||
$v = self::G($r, 1, 1, 5, 9, 13, $v, $m);
|
||||
$v = self::G($r, 2, 2, 6, 10, 14, $v, $m);
|
||||
$v = self::G($r, 3, 3, 7, 11, 15, $v, $m);
|
||||
$v = self::G($r, 4, 0, 5, 10, 15, $v, $m);
|
||||
$v = self::G($r, 5, 1, 6, 11, 12, $v, $m);
|
||||
$v = self::G($r, 6, 2, 7, 8, 13, $v, $m);
|
||||
$v = self::G($r, 7, 3, 4, 9, 14, $v, $m);
|
||||
}
|
||||
|
||||
for ($i = 8; $i--;) {
|
||||
$ctx[0][$i] = self::xor64(
|
||||
$ctx[0][$i], self::xor64($v[$i], $v[$i+8])
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $r
|
||||
* @param int $i
|
||||
* @param int $a
|
||||
* @param int $b
|
||||
* @param int $c
|
||||
* @param int $d
|
||||
* @param SplFixedArray $v
|
||||
* @param SplFixedArray $m
|
||||
* @return SplFixedArray
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
public static function G($r, $i, $a, $b, $c, $d, SplFixedArray $v, SplFixedArray $m)
|
||||
{
|
||||
$v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][$i << 1]]);
|
||||
$v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 32);
|
||||
$v[$c] = self::add64($v[$c], $v[$d]);
|
||||
$v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 24);
|
||||
$v[$a] = self::add364($v[$a], $v[$b], $m[self::$sigma[$r][($i << 1) + 1]]);
|
||||
$v[$d] = self::rotr64(self::xor64($v[$d], $v[$a]), 16);
|
||||
$v[$c] = self::add64($v[$c], $v[$d]);
|
||||
$v[$b] = self::rotr64(self::xor64($v[$b], $v[$c]), 63);
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $ctx
|
||||
* @param int $inc
|
||||
* @return void
|
||||
* @throws SodiumException
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
*/
|
||||
public static function increment_counter($ctx, $inc)
|
||||
{
|
||||
if ($inc < 0) {
|
||||
throw new SodiumException('Increasing by a negative number makes no sense.');
|
||||
}
|
||||
$t = self::to64($inc);
|
||||
# S->t is $ctx[1] in our implementation
|
||||
|
||||
# S->t[0] = ( uint64_t )( t >> 0 );
|
||||
$ctx[1][0] = self::add64($ctx[1][0], $t);
|
||||
|
||||
# S->t[1] += ( S->t[0] < inc );
|
||||
if (self::flatten64($ctx[1][0]) < $inc) {
|
||||
$ctx[1][1] = self::add64($ctx[1][1], self::to64(1));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $ctx
|
||||
* @param SplFixedArray $p
|
||||
* @param int $plen
|
||||
* @return void
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
* @psalm-suppress MixedOperand
|
||||
*/
|
||||
public static function update(SplFixedArray $ctx, SplFixedArray $p, $plen)
|
||||
{
|
||||
self::pseudoConstructor();
|
||||
|
||||
$offset = 0;
|
||||
while ($plen > 0) {
|
||||
$left = $ctx[4];
|
||||
$fill = 256 - $left;
|
||||
|
||||
if ($plen > $fill) {
|
||||
# memcpy( S->buf + left, in, fill ); /* Fill buffer */
|
||||
for ($i = $fill; $i--;) {
|
||||
$ctx[3][$i + $left] = $p[$i + $offset];
|
||||
}
|
||||
|
||||
# S->buflen += fill;
|
||||
$ctx[4] += $fill;
|
||||
|
||||
# blake2b_increment_counter( S, BLAKE2B_BLOCKBYTES );
|
||||
self::increment_counter($ctx, 128);
|
||||
|
||||
# blake2b_compress( S, S->buf ); /* Compress */
|
||||
self::compress($ctx, $ctx[3]);
|
||||
|
||||
# memcpy( S->buf, S->buf + BLAKE2B_BLOCKBYTES, BLAKE2B_BLOCKBYTES ); /* Shift buffer left */
|
||||
for ($i = 128; $i--;) {
|
||||
$ctx[3][$i] = $ctx[3][$i + 128];
|
||||
}
|
||||
|
||||
# S->buflen -= BLAKE2B_BLOCKBYTES;
|
||||
$ctx[4] -= 128;
|
||||
|
||||
# in += fill;
|
||||
$offset += $fill;
|
||||
|
||||
# inlen -= fill;
|
||||
$plen -= $fill;
|
||||
} else {
|
||||
for ($i = $plen; $i--;) {
|
||||
$ctx[3][$i + $left] = $p[$i + $offset];
|
||||
}
|
||||
$ctx[4] += $plen;
|
||||
$offset += $plen;
|
||||
$plen -= $plen;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $ctx
|
||||
* @param SplFixedArray $out
|
||||
* @return SplFixedArray
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
* @psalm-suppress MixedOperand
|
||||
*/
|
||||
public static function finish(SplFixedArray $ctx, SplFixedArray $out)
|
||||
{
|
||||
self::pseudoConstructor();
|
||||
if ($ctx[4] > 128) {
|
||||
self::increment_counter($ctx, 128);
|
||||
self::compress($ctx, $ctx[3]);
|
||||
$ctx[4] -= 128;
|
||||
if ($ctx[4] > 128) {
|
||||
throw new SodiumException('Failed to assert that buflen <= 128 bytes');
|
||||
}
|
||||
for ($i = $ctx[4]; $i--;) {
|
||||
$ctx[3][$i] = $ctx[3][$i + 128];
|
||||
}
|
||||
}
|
||||
|
||||
self::increment_counter($ctx, $ctx[4]);
|
||||
$ctx[2][0] = self::new64(0xffffffff, 0xffffffff);
|
||||
|
||||
for ($i = 256 - $ctx[4]; $i--;) {
|
||||
$ctx[3][$i+$ctx[4]] = 0;
|
||||
}
|
||||
|
||||
self::compress($ctx, $ctx[3]);
|
||||
|
||||
$i = (int) (($out->getSize() - 1) / 8);
|
||||
for (; $i >= 0; --$i) {
|
||||
self::store64($out, $i << 3, $ctx[0][$i]);
|
||||
}
|
||||
return $out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray|null $key
|
||||
* @param int $outlen
|
||||
* @param SplFixedArray|null $salt
|
||||
* @param SplFixedArray|null $personal
|
||||
* @return SplFixedArray
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
public static function init(
|
||||
$key = null,
|
||||
$outlen = 64,
|
||||
$salt = null,
|
||||
$personal = null
|
||||
) {
|
||||
self::pseudoConstructor();
|
||||
$klen = 0;
|
||||
|
||||
if ($key !== null) {
|
||||
if (count($key) > 64) {
|
||||
throw new SodiumException('Invalid key size');
|
||||
}
|
||||
$klen = count($key);
|
||||
}
|
||||
|
||||
if ($outlen > 64) {
|
||||
throw new SodiumException('Invalid output size');
|
||||
}
|
||||
|
||||
$ctx = self::context();
|
||||
|
||||
$p = new SplFixedArray(64);
|
||||
// Zero our param buffer...
|
||||
for ($i = 64; --$i;) {
|
||||
$p[$i] = 0;
|
||||
}
|
||||
|
||||
$p[0] = $outlen; // digest_length
|
||||
$p[1] = $klen; // key_length
|
||||
$p[2] = 1; // fanout
|
||||
$p[3] = 1; // depth
|
||||
|
||||
if ($salt instanceof SplFixedArray) {
|
||||
// salt: [32] through [47]
|
||||
for ($i = 0; $i < 16; ++$i) {
|
||||
$p[32 + $i] = (int) $salt[$i];
|
||||
}
|
||||
}
|
||||
if ($personal instanceof SplFixedArray) {
|
||||
// personal: [48] through [63]
|
||||
for ($i = 0; $i < 16; ++$i) {
|
||||
$p[48 + $i] = (int) $personal[$i];
|
||||
}
|
||||
}
|
||||
|
||||
$ctx[0][0] = self::xor64(
|
||||
$ctx[0][0],
|
||||
self::load64($p, 0)
|
||||
);
|
||||
if ($salt instanceof SplFixedArray || $personal instanceof SplFixedArray) {
|
||||
// We need to do what blake2b_init_param() does:
|
||||
for ($i = 1; $i < 8; ++$i) {
|
||||
$ctx[0][$i] = self::xor64(
|
||||
$ctx[0][$i],
|
||||
self::load64($p, $i << 3)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if ($klen > 0 && $key instanceof SplFixedArray) {
|
||||
$block = new SplFixedArray(128);
|
||||
for ($i = 128; $i--;) {
|
||||
$block[$i] = 0;
|
||||
}
|
||||
for ($i = $klen; $i--;) {
|
||||
$block[$i] = $key[$i];
|
||||
}
|
||||
self::update($ctx, $block, 128);
|
||||
$ctx[4] = 128;
|
||||
}
|
||||
|
||||
return $ctx;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a string into an SplFixedArray of integers
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $str
|
||||
* @return SplFixedArray
|
||||
* @psalm-suppress MixedArgumentTypeCoercion
|
||||
*/
|
||||
public static function stringToSplFixedArray($str = '')
|
||||
{
|
||||
$values = unpack('C*', $str);
|
||||
return SplFixedArray::fromArray(array_values($values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an SplFixedArray of integers into a string
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $a
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function SplFixedArrayToString(SplFixedArray $a)
|
||||
{
|
||||
/**
|
||||
* @var array<int, int|string> $arr
|
||||
*/
|
||||
$arr = $a->toArray();
|
||||
$c = $a->count();
|
||||
array_unshift($arr, str_repeat('C', $c));
|
||||
return (string) (call_user_func_array('pack', $arr));
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param SplFixedArray $ctx
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArgument
|
||||
* @psalm-suppress MixedAssignment
|
||||
* @psalm-suppress MixedArrayAccess
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
* @psalm-suppress MixedMethodCall
|
||||
*/
|
||||
public static function contextToString(SplFixedArray $ctx)
|
||||
{
|
||||
$str = '';
|
||||
/** @var array<int, array<int, int>> $ctxA */
|
||||
$ctxA = $ctx[0]->toArray();
|
||||
|
||||
# uint64_t h[8];
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$str .= self::store32_le($ctxA[$i][1]);
|
||||
$str .= self::store32_le($ctxA[$i][0]);
|
||||
}
|
||||
|
||||
# uint64_t t[2];
|
||||
# uint64_t f[2];
|
||||
for ($i = 1; $i < 3; ++$i) {
|
||||
$ctxA = $ctx[$i]->toArray();
|
||||
$str .= self::store32_le($ctxA[0][1]);
|
||||
$str .= self::store32_le($ctxA[0][0]);
|
||||
$str .= self::store32_le($ctxA[1][1]);
|
||||
$str .= self::store32_le($ctxA[1][0]);
|
||||
}
|
||||
|
||||
# uint8_t buf[2 * 128];
|
||||
$str .= self::SplFixedArrayToString($ctx[3]);
|
||||
|
||||
/** @var int $ctx4 */
|
||||
$ctx4 = (int) $ctx[4];
|
||||
|
||||
# size_t buflen;
|
||||
$str .= implode('', array(
|
||||
self::intToChr($ctx4 & 0xff),
|
||||
self::intToChr(($ctx4 >> 8) & 0xff),
|
||||
self::intToChr(($ctx4 >> 16) & 0xff),
|
||||
self::intToChr(($ctx4 >> 24) & 0xff),
|
||||
self::intToChr(($ctx4 >> 32) & 0xff),
|
||||
self::intToChr(($ctx4 >> 40) & 0xff),
|
||||
self::intToChr(($ctx4 >> 48) & 0xff),
|
||||
self::intToChr(($ctx4 >> 56) & 0xff)
|
||||
));
|
||||
# uint8_t last_node;
|
||||
return $str . self::intToChr($ctx[5]) . str_repeat("\x00", 23);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an SplFixedArray containing other SplFixedArray elements, from
|
||||
* a string (compatible with \Sodium\crypto_generichash_{init, update, final})
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $string
|
||||
* @return SplFixedArray
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress MixedArrayAssignment
|
||||
*/
|
||||
public static function stringToContext($string)
|
||||
{
|
||||
$ctx = self::context();
|
||||
|
||||
# uint64_t h[8];
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$ctx[0][$i] = SplFixedArray::fromArray(
|
||||
array(
|
||||
self::load_4(
|
||||
self::substr($string, (($i << 3) + 4), 4)
|
||||
),
|
||||
self::load_4(
|
||||
self::substr($string, (($i << 3) + 0), 4)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
# uint64_t t[2];
|
||||
# uint64_t f[2];
|
||||
for ($i = 1; $i < 3; ++$i) {
|
||||
$ctx[$i][1] = SplFixedArray::fromArray(
|
||||
array(
|
||||
self::load_4(self::substr($string, 76 + (($i - 1) << 4), 4)),
|
||||
self::load_4(self::substr($string, 72 + (($i - 1) << 4), 4))
|
||||
)
|
||||
);
|
||||
$ctx[$i][0] = SplFixedArray::fromArray(
|
||||
array(
|
||||
self::load_4(self::substr($string, 68 + (($i - 1) << 4), 4)),
|
||||
self::load_4(self::substr($string, 64 + (($i - 1) << 4), 4))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
# uint8_t buf[2 * 128];
|
||||
$ctx[3] = self::stringToSplFixedArray(self::substr($string, 96, 256));
|
||||
|
||||
# uint8_t buf[2 * 128];
|
||||
$int = 0;
|
||||
for ($i = 0; $i < 8; ++$i) {
|
||||
$int |= self::chrToInt($string[352 + $i]) << ($i << 3);
|
||||
}
|
||||
$ctx[4] = $int;
|
||||
|
||||
return $ctx;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Base64
|
||||
*
|
||||
* Copyright (c) 2016 - 2018 Paragon Initiative Enterprises.
|
||||
* Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Base64_Original
|
||||
{
|
||||
// COPY ParagonIE_Sodium_Core_Base64_Common STARTING HERE
|
||||
/**
|
||||
* Encode into Base64
|
||||
*
|
||||
* Base64 character set "[A-Z][a-z][0-9]+/"
|
||||
*
|
||||
* @param string $src
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function encode($src)
|
||||
{
|
||||
return self::doEncode($src, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode into Base64, no = padding
|
||||
*
|
||||
* Base64 character set "[A-Z][a-z][0-9]+/"
|
||||
*
|
||||
* @param string $src
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function encodeUnpadded($src)
|
||||
{
|
||||
return self::doEncode($src, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $src
|
||||
* @param bool $pad Include = padding?
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
protected static function doEncode($src, $pad = true)
|
||||
{
|
||||
$dest = '';
|
||||
$srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
|
||||
// Main loop (no padding):
|
||||
for ($i = 0; $i + 3 <= $srcLen; $i += 3) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, 3));
|
||||
$b0 = $chunk[1];
|
||||
$b1 = $chunk[2];
|
||||
$b2 = $chunk[3];
|
||||
|
||||
$dest .=
|
||||
self::encode6Bits( $b0 >> 2 ) .
|
||||
self::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
|
||||
self::encode6Bits((($b1 << 2) | ($b2 >> 6)) & 63) .
|
||||
self::encode6Bits( $b2 & 63);
|
||||
}
|
||||
// The last chunk, which may have padding:
|
||||
if ($i < $srcLen) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, $srcLen - $i));
|
||||
$b0 = $chunk[1];
|
||||
if ($i + 1 < $srcLen) {
|
||||
$b1 = $chunk[2];
|
||||
$dest .=
|
||||
self::encode6Bits($b0 >> 2) .
|
||||
self::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
|
||||
self::encode6Bits(($b1 << 2) & 63);
|
||||
if ($pad) {
|
||||
$dest .= '=';
|
||||
}
|
||||
} else {
|
||||
$dest .=
|
||||
self::encode6Bits( $b0 >> 2) .
|
||||
self::encode6Bits(($b0 << 4) & 63);
|
||||
if ($pad) {
|
||||
$dest .= '==';
|
||||
}
|
||||
}
|
||||
}
|
||||
return $dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* decode from base64 into binary
|
||||
*
|
||||
* Base64 character set "./[A-Z][a-z][0-9]"
|
||||
*
|
||||
* @param string $src
|
||||
* @param bool $strictPadding
|
||||
* @return string
|
||||
* @throws RangeException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress RedundantCondition
|
||||
*/
|
||||
public static function decode($src, $strictPadding = false)
|
||||
{
|
||||
// Remove padding
|
||||
$srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
|
||||
if ($srcLen === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($strictPadding) {
|
||||
if (($srcLen & 3) === 0) {
|
||||
if ($src[$srcLen - 1] === '=') {
|
||||
$srcLen--;
|
||||
if ($src[$srcLen - 1] === '=') {
|
||||
$srcLen--;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (($srcLen & 3) === 1) {
|
||||
throw new RangeException(
|
||||
'Incorrect padding'
|
||||
);
|
||||
}
|
||||
if ($src[$srcLen - 1] === '=') {
|
||||
throw new RangeException(
|
||||
'Incorrect padding'
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$src = rtrim($src, '=');
|
||||
$srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
|
||||
}
|
||||
|
||||
$err = 0;
|
||||
$dest = '';
|
||||
// Main loop (no padding):
|
||||
for ($i = 0; $i + 4 <= $srcLen; $i += 4) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, 4));
|
||||
$c0 = self::decode6Bits($chunk[1]);
|
||||
$c1 = self::decode6Bits($chunk[2]);
|
||||
$c2 = self::decode6Bits($chunk[3]);
|
||||
$c3 = self::decode6Bits($chunk[4]);
|
||||
|
||||
$dest .= pack(
|
||||
'CCC',
|
||||
((($c0 << 2) | ($c1 >> 4)) & 0xff),
|
||||
((($c1 << 4) | ($c2 >> 2)) & 0xff),
|
||||
((($c2 << 6) | $c3) & 0xff)
|
||||
);
|
||||
$err |= ($c0 | $c1 | $c2 | $c3) >> 8;
|
||||
}
|
||||
// The last chunk, which may have padding:
|
||||
if ($i < $srcLen) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, $srcLen - $i));
|
||||
$c0 = self::decode6Bits($chunk[1]);
|
||||
|
||||
if ($i + 2 < $srcLen) {
|
||||
$c1 = self::decode6Bits($chunk[2]);
|
||||
$c2 = self::decode6Bits($chunk[3]);
|
||||
$dest .= pack(
|
||||
'CC',
|
||||
((($c0 << 2) | ($c1 >> 4)) & 0xff),
|
||||
((($c1 << 4) | ($c2 >> 2)) & 0xff)
|
||||
);
|
||||
$err |= ($c0 | $c1 | $c2) >> 8;
|
||||
} elseif ($i + 1 < $srcLen) {
|
||||
$c1 = self::decode6Bits($chunk[2]);
|
||||
$dest .= pack(
|
||||
'C',
|
||||
((($c0 << 2) | ($c1 >> 4)) & 0xff)
|
||||
);
|
||||
$err |= ($c0 | $c1) >> 8;
|
||||
} elseif ($i < $srcLen && $strictPadding) {
|
||||
$err |= 1;
|
||||
}
|
||||
}
|
||||
/** @var bool $check */
|
||||
$check = ($err === 0);
|
||||
if (!$check) {
|
||||
throw new RangeException(
|
||||
'Base64::decode() only expects characters in the correct base64 alphabet'
|
||||
);
|
||||
}
|
||||
return $dest;
|
||||
}
|
||||
// COPY ParagonIE_Sodium_Core_Base64_Common ENDING HERE
|
||||
|
||||
/**
|
||||
* Uses bitwise operators instead of table-lookups to turn 6-bit integers
|
||||
* into 8-bit integers.
|
||||
*
|
||||
* Base64 character set:
|
||||
* [A-Z] [a-z] [0-9] + /
|
||||
* 0x41-0x5a, 0x61-0x7a, 0x30-0x39, 0x2b, 0x2f
|
||||
*
|
||||
* @param int $src
|
||||
* @return int
|
||||
*/
|
||||
protected static function decode6Bits($src)
|
||||
{
|
||||
$ret = -1;
|
||||
|
||||
// if ($src > 0x40 && $src < 0x5b) $ret += $src - 0x41 + 1; // -64
|
||||
$ret += (((0x40 - $src) & ($src - 0x5b)) >> 8) & ($src - 64);
|
||||
|
||||
// if ($src > 0x60 && $src < 0x7b) $ret += $src - 0x61 + 26 + 1; // -70
|
||||
$ret += (((0x60 - $src) & ($src - 0x7b)) >> 8) & ($src - 70);
|
||||
|
||||
// if ($src > 0x2f && $src < 0x3a) $ret += $src - 0x30 + 52 + 1; // 5
|
||||
$ret += (((0x2f - $src) & ($src - 0x3a)) >> 8) & ($src + 5);
|
||||
|
||||
// if ($src == 0x2b) $ret += 62 + 1;
|
||||
$ret += (((0x2a - $src) & ($src - 0x2c)) >> 8) & 63;
|
||||
|
||||
// if ($src == 0x2f) ret += 63 + 1;
|
||||
$ret += (((0x2e - $src) & ($src - 0x30)) >> 8) & 64;
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses bitwise operators instead of table-lookups to turn 8-bit integers
|
||||
* into 6-bit integers.
|
||||
*
|
||||
* @param int $src
|
||||
* @return string
|
||||
*/
|
||||
protected static function encode6Bits($src)
|
||||
{
|
||||
$diff = 0x41;
|
||||
|
||||
// if ($src > 25) $diff += 0x61 - 0x41 - 26; // 6
|
||||
$diff += ((25 - $src) >> 8) & 6;
|
||||
|
||||
// if ($src > 51) $diff += 0x30 - 0x61 - 26; // -75
|
||||
$diff -= ((51 - $src) >> 8) & 75;
|
||||
|
||||
// if ($src > 61) $diff += 0x2b - 0x30 - 10; // -15
|
||||
$diff -= ((61 - $src) >> 8) & 15;
|
||||
|
||||
// if ($src > 62) $diff += 0x2f - 0x2b - 1; // 3
|
||||
$diff += ((62 - $src) >> 8) & 3;
|
||||
|
||||
return pack('C', $src + $diff);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Base64UrlSafe
|
||||
*
|
||||
* Copyright (c) 2016 - 2018 Paragon Initiative Enterprises.
|
||||
* Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Base64_UrlSafe
|
||||
{
|
||||
// COPY ParagonIE_Sodium_Core_Base64_Common STARTING HERE
|
||||
/**
|
||||
* Encode into Base64
|
||||
*
|
||||
* Base64 character set "[A-Z][a-z][0-9]+/"
|
||||
*
|
||||
* @param string $src
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function encode($src)
|
||||
{
|
||||
return self::doEncode($src, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode into Base64, no = padding
|
||||
*
|
||||
* Base64 character set "[A-Z][a-z][0-9]+/"
|
||||
*
|
||||
* @param string $src
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function encodeUnpadded($src)
|
||||
{
|
||||
return self::doEncode($src, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $src
|
||||
* @param bool $pad Include = padding?
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
protected static function doEncode($src, $pad = true)
|
||||
{
|
||||
$dest = '';
|
||||
$srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
|
||||
// Main loop (no padding):
|
||||
for ($i = 0; $i + 3 <= $srcLen; $i += 3) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, 3));
|
||||
$b0 = $chunk[1];
|
||||
$b1 = $chunk[2];
|
||||
$b2 = $chunk[3];
|
||||
|
||||
$dest .=
|
||||
self::encode6Bits( $b0 >> 2 ) .
|
||||
self::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
|
||||
self::encode6Bits((($b1 << 2) | ($b2 >> 6)) & 63) .
|
||||
self::encode6Bits( $b2 & 63);
|
||||
}
|
||||
// The last chunk, which may have padding:
|
||||
if ($i < $srcLen) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, $srcLen - $i));
|
||||
$b0 = $chunk[1];
|
||||
if ($i + 1 < $srcLen) {
|
||||
$b1 = $chunk[2];
|
||||
$dest .=
|
||||
self::encode6Bits($b0 >> 2) .
|
||||
self::encode6Bits((($b0 << 4) | ($b1 >> 4)) & 63) .
|
||||
self::encode6Bits(($b1 << 2) & 63);
|
||||
if ($pad) {
|
||||
$dest .= '=';
|
||||
}
|
||||
} else {
|
||||
$dest .=
|
||||
self::encode6Bits( $b0 >> 2) .
|
||||
self::encode6Bits(($b0 << 4) & 63);
|
||||
if ($pad) {
|
||||
$dest .= '==';
|
||||
}
|
||||
}
|
||||
}
|
||||
return $dest;
|
||||
}
|
||||
|
||||
/**
|
||||
* decode from base64 into binary
|
||||
*
|
||||
* Base64 character set "./[A-Z][a-z][0-9]"
|
||||
*
|
||||
* @param string $src
|
||||
* @param bool $strictPadding
|
||||
* @return string
|
||||
* @throws RangeException
|
||||
* @throws TypeError
|
||||
* @psalm-suppress RedundantCondition
|
||||
*/
|
||||
public static function decode($src, $strictPadding = false)
|
||||
{
|
||||
// Remove padding
|
||||
$srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
|
||||
if ($srcLen === 0) {
|
||||
return '';
|
||||
}
|
||||
|
||||
if ($strictPadding) {
|
||||
if (($srcLen & 3) === 0) {
|
||||
if ($src[$srcLen - 1] === '=') {
|
||||
$srcLen--;
|
||||
if ($src[$srcLen - 1] === '=') {
|
||||
$srcLen--;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (($srcLen & 3) === 1) {
|
||||
throw new RangeException(
|
||||
'Incorrect padding'
|
||||
);
|
||||
}
|
||||
if ($src[$srcLen - 1] === '=') {
|
||||
throw new RangeException(
|
||||
'Incorrect padding'
|
||||
);
|
||||
}
|
||||
} else {
|
||||
$src = rtrim($src, '=');
|
||||
$srcLen = ParagonIE_Sodium_Core_Util::strlen($src);
|
||||
}
|
||||
|
||||
$err = 0;
|
||||
$dest = '';
|
||||
// Main loop (no padding):
|
||||
for ($i = 0; $i + 4 <= $srcLen; $i += 4) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, 4));
|
||||
$c0 = self::decode6Bits($chunk[1]);
|
||||
$c1 = self::decode6Bits($chunk[2]);
|
||||
$c2 = self::decode6Bits($chunk[3]);
|
||||
$c3 = self::decode6Bits($chunk[4]);
|
||||
|
||||
$dest .= pack(
|
||||
'CCC',
|
||||
((($c0 << 2) | ($c1 >> 4)) & 0xff),
|
||||
((($c1 << 4) | ($c2 >> 2)) & 0xff),
|
||||
((($c2 << 6) | $c3) & 0xff)
|
||||
);
|
||||
$err |= ($c0 | $c1 | $c2 | $c3) >> 8;
|
||||
}
|
||||
// The last chunk, which may have padding:
|
||||
if ($i < $srcLen) {
|
||||
/** @var array<int, int> $chunk */
|
||||
$chunk = unpack('C*', ParagonIE_Sodium_Core_Util::substr($src, $i, $srcLen - $i));
|
||||
$c0 = self::decode6Bits($chunk[1]);
|
||||
|
||||
if ($i + 2 < $srcLen) {
|
||||
$c1 = self::decode6Bits($chunk[2]);
|
||||
$c2 = self::decode6Bits($chunk[3]);
|
||||
$dest .= pack(
|
||||
'CC',
|
||||
((($c0 << 2) | ($c1 >> 4)) & 0xff),
|
||||
((($c1 << 4) | ($c2 >> 2)) & 0xff)
|
||||
);
|
||||
$err |= ($c0 | $c1 | $c2) >> 8;
|
||||
} elseif ($i + 1 < $srcLen) {
|
||||
$c1 = self::decode6Bits($chunk[2]);
|
||||
$dest .= pack(
|
||||
'C',
|
||||
((($c0 << 2) | ($c1 >> 4)) & 0xff)
|
||||
);
|
||||
$err |= ($c0 | $c1) >> 8;
|
||||
} elseif ($i < $srcLen && $strictPadding) {
|
||||
$err |= 1;
|
||||
}
|
||||
}
|
||||
/** @var bool $check */
|
||||
$check = ($err === 0);
|
||||
if (!$check) {
|
||||
throw new RangeException(
|
||||
'Base64::decode() only expects characters in the correct base64 alphabet'
|
||||
);
|
||||
}
|
||||
return $dest;
|
||||
}
|
||||
// COPY ParagonIE_Sodium_Core_Base64_Common ENDING HERE
|
||||
/**
|
||||
* Uses bitwise operators instead of table-lookups to turn 6-bit integers
|
||||
* into 8-bit integers.
|
||||
*
|
||||
* Base64 character set:
|
||||
* [A-Z] [a-z] [0-9] + /
|
||||
* 0x41-0x5a, 0x61-0x7a, 0x30-0x39, 0x2b, 0x2f
|
||||
*
|
||||
* @param int $src
|
||||
* @return int
|
||||
*/
|
||||
protected static function decode6Bits($src)
|
||||
{
|
||||
$ret = -1;
|
||||
|
||||
// if ($src > 0x40 && $src < 0x5b) $ret += $src - 0x41 + 1; // -64
|
||||
$ret += (((0x40 - $src) & ($src - 0x5b)) >> 8) & ($src - 64);
|
||||
|
||||
// if ($src > 0x60 && $src < 0x7b) $ret += $src - 0x61 + 26 + 1; // -70
|
||||
$ret += (((0x60 - $src) & ($src - 0x7b)) >> 8) & ($src - 70);
|
||||
|
||||
// if ($src > 0x2f && $src < 0x3a) $ret += $src - 0x30 + 52 + 1; // 5
|
||||
$ret += (((0x2f - $src) & ($src - 0x3a)) >> 8) & ($src + 5);
|
||||
|
||||
// if ($src == 0x2c) $ret += 62 + 1;
|
||||
$ret += (((0x2c - $src) & ($src - 0x2e)) >> 8) & 63;
|
||||
|
||||
// if ($src == 0x5f) ret += 63 + 1;
|
||||
$ret += (((0x5e - $src) & ($src - 0x60)) >> 8) & 64;
|
||||
|
||||
return $ret;
|
||||
}
|
||||
|
||||
/**
|
||||
* Uses bitwise operators instead of table-lookups to turn 8-bit integers
|
||||
* into 6-bit integers.
|
||||
*
|
||||
* @param int $src
|
||||
* @return string
|
||||
*/
|
||||
protected static function encode6Bits($src)
|
||||
{
|
||||
$diff = 0x41;
|
||||
|
||||
// if ($src > 25) $diff += 0x61 - 0x41 - 26; // 6
|
||||
$diff += ((25 - $src) >> 8) & 6;
|
||||
|
||||
// if ($src > 51) $diff += 0x30 - 0x61 - 26; // -75
|
||||
$diff -= ((51 - $src) >> 8) & 75;
|
||||
|
||||
// if ($src > 61) $diff += 0x2d - 0x30 - 10; // -13
|
||||
$diff -= ((61 - $src) >> 8) & 13;
|
||||
|
||||
// if ($src > 62) $diff += 0x5f - 0x2b - 1; // 3
|
||||
$diff += ((62 - $src) >> 8) & 49;
|
||||
|
||||
return pack('C', $src + $diff);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_ChaCha20', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_ChaCha20
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_ChaCha20 extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
/**
|
||||
* Bitwise left rotation
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $v
|
||||
* @param int $n
|
||||
* @return int
|
||||
*/
|
||||
public static function rotate($v, $n)
|
||||
{
|
||||
$v &= 0xffffffff;
|
||||
$n &= 31;
|
||||
return (int) (
|
||||
0xffffffff & (
|
||||
($v << $n)
|
||||
|
|
||||
($v >> (32 - $n))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ChaCha20 quarter round function. Works on four 32-bit integers.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $a
|
||||
* @param int $b
|
||||
* @param int $c
|
||||
* @param int $d
|
||||
* @return array<int, int>
|
||||
*/
|
||||
protected static function quarterRound($a, $b, $c, $d)
|
||||
{
|
||||
# a = PLUS(a,b); d = ROTATE(XOR(d,a),16);
|
||||
/** @var int $a */
|
||||
$a = ($a + $b) & 0xffffffff;
|
||||
$d = self::rotate($d ^ $a, 16);
|
||||
|
||||
# c = PLUS(c,d); b = ROTATE(XOR(b,c),12);
|
||||
/** @var int $c */
|
||||
$c = ($c + $d) & 0xffffffff;
|
||||
$b = self::rotate($b ^ $c, 12);
|
||||
|
||||
# a = PLUS(a,b); d = ROTATE(XOR(d,a), 8);
|
||||
/** @var int $a */
|
||||
$a = ($a + $b) & 0xffffffff;
|
||||
$d = self::rotate($d ^ $a, 8);
|
||||
|
||||
# c = PLUS(c,d); b = ROTATE(XOR(b,c), 7);
|
||||
/** @var int $c */
|
||||
$c = ($c + $d) & 0xffffffff;
|
||||
$b = self::rotate($b ^ $c, 7);
|
||||
return array((int) $a, (int) $b, (int) $c, (int) $d);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_ChaCha20_Ctx $ctx
|
||||
* @param string $message
|
||||
*
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function encryptBytes(
|
||||
ParagonIE_Sodium_Core_ChaCha20_Ctx $ctx,
|
||||
$message = ''
|
||||
) {
|
||||
$bytes = self::strlen($message);
|
||||
|
||||
/*
|
||||
j0 = ctx->input[0];
|
||||
j1 = ctx->input[1];
|
||||
j2 = ctx->input[2];
|
||||
j3 = ctx->input[3];
|
||||
j4 = ctx->input[4];
|
||||
j5 = ctx->input[5];
|
||||
j6 = ctx->input[6];
|
||||
j7 = ctx->input[7];
|
||||
j8 = ctx->input[8];
|
||||
j9 = ctx->input[9];
|
||||
j10 = ctx->input[10];
|
||||
j11 = ctx->input[11];
|
||||
j12 = ctx->input[12];
|
||||
j13 = ctx->input[13];
|
||||
j14 = ctx->input[14];
|
||||
j15 = ctx->input[15];
|
||||
*/
|
||||
$j0 = (int) $ctx[0];
|
||||
$j1 = (int) $ctx[1];
|
||||
$j2 = (int) $ctx[2];
|
||||
$j3 = (int) $ctx[3];
|
||||
$j4 = (int) $ctx[4];
|
||||
$j5 = (int) $ctx[5];
|
||||
$j6 = (int) $ctx[6];
|
||||
$j7 = (int) $ctx[7];
|
||||
$j8 = (int) $ctx[8];
|
||||
$j9 = (int) $ctx[9];
|
||||
$j10 = (int) $ctx[10];
|
||||
$j11 = (int) $ctx[11];
|
||||
$j12 = (int) $ctx[12];
|
||||
$j13 = (int) $ctx[13];
|
||||
$j14 = (int) $ctx[14];
|
||||
$j15 = (int) $ctx[15];
|
||||
|
||||
$c = '';
|
||||
for (;;) {
|
||||
if ($bytes < 64) {
|
||||
$message .= str_repeat("\x00", 64 - $bytes);
|
||||
}
|
||||
|
||||
$x0 = (int) $j0;
|
||||
$x1 = (int) $j1;
|
||||
$x2 = (int) $j2;
|
||||
$x3 = (int) $j3;
|
||||
$x4 = (int) $j4;
|
||||
$x5 = (int) $j5;
|
||||
$x6 = (int) $j6;
|
||||
$x7 = (int) $j7;
|
||||
$x8 = (int) $j8;
|
||||
$x9 = (int) $j9;
|
||||
$x10 = (int) $j10;
|
||||
$x11 = (int) $j11;
|
||||
$x12 = (int) $j12;
|
||||
$x13 = (int) $j13;
|
||||
$x14 = (int) $j14;
|
||||
$x15 = (int) $j15;
|
||||
|
||||
# for (i = 20; i > 0; i -= 2) {
|
||||
for ($i = 20; $i > 0; $i -= 2) {
|
||||
# QUARTERROUND( x0, x4, x8, x12)
|
||||
list($x0, $x4, $x8, $x12) = self::quarterRound($x0, $x4, $x8, $x12);
|
||||
|
||||
# QUARTERROUND( x1, x5, x9, x13)
|
||||
list($x1, $x5, $x9, $x13) = self::quarterRound($x1, $x5, $x9, $x13);
|
||||
|
||||
# QUARTERROUND( x2, x6, x10, x14)
|
||||
list($x2, $x6, $x10, $x14) = self::quarterRound($x2, $x6, $x10, $x14);
|
||||
|
||||
# QUARTERROUND( x3, x7, x11, x15)
|
||||
list($x3, $x7, $x11, $x15) = self::quarterRound($x3, $x7, $x11, $x15);
|
||||
|
||||
# QUARTERROUND( x0, x5, x10, x15)
|
||||
list($x0, $x5, $x10, $x15) = self::quarterRound($x0, $x5, $x10, $x15);
|
||||
|
||||
# QUARTERROUND( x1, x6, x11, x12)
|
||||
list($x1, $x6, $x11, $x12) = self::quarterRound($x1, $x6, $x11, $x12);
|
||||
|
||||
# QUARTERROUND( x2, x7, x8, x13)
|
||||
list($x2, $x7, $x8, $x13) = self::quarterRound($x2, $x7, $x8, $x13);
|
||||
|
||||
# QUARTERROUND( x3, x4, x9, x14)
|
||||
list($x3, $x4, $x9, $x14) = self::quarterRound($x3, $x4, $x9, $x14);
|
||||
}
|
||||
/*
|
||||
x0 = PLUS(x0, j0);
|
||||
x1 = PLUS(x1, j1);
|
||||
x2 = PLUS(x2, j2);
|
||||
x3 = PLUS(x3, j3);
|
||||
x4 = PLUS(x4, j4);
|
||||
x5 = PLUS(x5, j5);
|
||||
x6 = PLUS(x6, j6);
|
||||
x7 = PLUS(x7, j7);
|
||||
x8 = PLUS(x8, j8);
|
||||
x9 = PLUS(x9, j9);
|
||||
x10 = PLUS(x10, j10);
|
||||
x11 = PLUS(x11, j11);
|
||||
x12 = PLUS(x12, j12);
|
||||
x13 = PLUS(x13, j13);
|
||||
x14 = PLUS(x14, j14);
|
||||
x15 = PLUS(x15, j15);
|
||||
*/
|
||||
/** @var int $x0 */
|
||||
$x0 = ($x0 & 0xffffffff) + $j0;
|
||||
/** @var int $x1 */
|
||||
$x1 = ($x1 & 0xffffffff) + $j1;
|
||||
/** @var int $x2 */
|
||||
$x2 = ($x2 & 0xffffffff) + $j2;
|
||||
/** @var int $x3 */
|
||||
$x3 = ($x3 & 0xffffffff) + $j3;
|
||||
/** @var int $x4 */
|
||||
$x4 = ($x4 & 0xffffffff) + $j4;
|
||||
/** @var int $x5 */
|
||||
$x5 = ($x5 & 0xffffffff) + $j5;
|
||||
/** @var int $x6 */
|
||||
$x6 = ($x6 & 0xffffffff) + $j6;
|
||||
/** @var int $x7 */
|
||||
$x7 = ($x7 & 0xffffffff) + $j7;
|
||||
/** @var int $x8 */
|
||||
$x8 = ($x8 & 0xffffffff) + $j8;
|
||||
/** @var int $x9 */
|
||||
$x9 = ($x9 & 0xffffffff) + $j9;
|
||||
/** @var int $x10 */
|
||||
$x10 = ($x10 & 0xffffffff) + $j10;
|
||||
/** @var int $x11 */
|
||||
$x11 = ($x11 & 0xffffffff) + $j11;
|
||||
/** @var int $x12 */
|
||||
$x12 = ($x12 & 0xffffffff) + $j12;
|
||||
/** @var int $x13 */
|
||||
$x13 = ($x13 & 0xffffffff) + $j13;
|
||||
/** @var int $x14 */
|
||||
$x14 = ($x14 & 0xffffffff) + $j14;
|
||||
/** @var int $x15 */
|
||||
$x15 = ($x15 & 0xffffffff) + $j15;
|
||||
|
||||
/*
|
||||
x0 = XOR(x0, LOAD32_LE(m + 0));
|
||||
x1 = XOR(x1, LOAD32_LE(m + 4));
|
||||
x2 = XOR(x2, LOAD32_LE(m + 8));
|
||||
x3 = XOR(x3, LOAD32_LE(m + 12));
|
||||
x4 = XOR(x4, LOAD32_LE(m + 16));
|
||||
x5 = XOR(x5, LOAD32_LE(m + 20));
|
||||
x6 = XOR(x6, LOAD32_LE(m + 24));
|
||||
x7 = XOR(x7, LOAD32_LE(m + 28));
|
||||
x8 = XOR(x8, LOAD32_LE(m + 32));
|
||||
x9 = XOR(x9, LOAD32_LE(m + 36));
|
||||
x10 = XOR(x10, LOAD32_LE(m + 40));
|
||||
x11 = XOR(x11, LOAD32_LE(m + 44));
|
||||
x12 = XOR(x12, LOAD32_LE(m + 48));
|
||||
x13 = XOR(x13, LOAD32_LE(m + 52));
|
||||
x14 = XOR(x14, LOAD32_LE(m + 56));
|
||||
x15 = XOR(x15, LOAD32_LE(m + 60));
|
||||
*/
|
||||
$x0 ^= self::load_4(self::substr($message, 0, 4));
|
||||
$x1 ^= self::load_4(self::substr($message, 4, 4));
|
||||
$x2 ^= self::load_4(self::substr($message, 8, 4));
|
||||
$x3 ^= self::load_4(self::substr($message, 12, 4));
|
||||
$x4 ^= self::load_4(self::substr($message, 16, 4));
|
||||
$x5 ^= self::load_4(self::substr($message, 20, 4));
|
||||
$x6 ^= self::load_4(self::substr($message, 24, 4));
|
||||
$x7 ^= self::load_4(self::substr($message, 28, 4));
|
||||
$x8 ^= self::load_4(self::substr($message, 32, 4));
|
||||
$x9 ^= self::load_4(self::substr($message, 36, 4));
|
||||
$x10 ^= self::load_4(self::substr($message, 40, 4));
|
||||
$x11 ^= self::load_4(self::substr($message, 44, 4));
|
||||
$x12 ^= self::load_4(self::substr($message, 48, 4));
|
||||
$x13 ^= self::load_4(self::substr($message, 52, 4));
|
||||
$x14 ^= self::load_4(self::substr($message, 56, 4));
|
||||
$x15 ^= self::load_4(self::substr($message, 60, 4));
|
||||
|
||||
/*
|
||||
j12 = PLUSONE(j12);
|
||||
if (!j12) {
|
||||
j13 = PLUSONE(j13);
|
||||
}
|
||||
*/
|
||||
++$j12;
|
||||
if ($j12 & 0xf0000000) {
|
||||
throw new SodiumException('Overflow');
|
||||
}
|
||||
|
||||
/*
|
||||
STORE32_LE(c + 0, x0);
|
||||
STORE32_LE(c + 4, x1);
|
||||
STORE32_LE(c + 8, x2);
|
||||
STORE32_LE(c + 12, x3);
|
||||
STORE32_LE(c + 16, x4);
|
||||
STORE32_LE(c + 20, x5);
|
||||
STORE32_LE(c + 24, x6);
|
||||
STORE32_LE(c + 28, x7);
|
||||
STORE32_LE(c + 32, x8);
|
||||
STORE32_LE(c + 36, x9);
|
||||
STORE32_LE(c + 40, x10);
|
||||
STORE32_LE(c + 44, x11);
|
||||
STORE32_LE(c + 48, x12);
|
||||
STORE32_LE(c + 52, x13);
|
||||
STORE32_LE(c + 56, x14);
|
||||
STORE32_LE(c + 60, x15);
|
||||
*/
|
||||
$block = self::store32_le((int) ($x0 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x1 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x2 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x3 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x4 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x5 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x6 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x7 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x8 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x9 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x10 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x11 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x12 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x13 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x14 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x15 & 0xffffffff));
|
||||
|
||||
/* Partial block */
|
||||
if ($bytes < 64) {
|
||||
$c .= self::substr($block, 0, $bytes);
|
||||
break;
|
||||
}
|
||||
|
||||
/* Full block */
|
||||
$c .= $block;
|
||||
$bytes -= 64;
|
||||
if ($bytes <= 0) {
|
||||
break;
|
||||
}
|
||||
$message = self::substr($message, 64);
|
||||
}
|
||||
/* end for(;;) loop */
|
||||
|
||||
$ctx[12] = $j12;
|
||||
$ctx[13] = $j13;
|
||||
return $c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $len
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function stream($len = 64, $nonce = '', $key = '')
|
||||
{
|
||||
return self::encryptBytes(
|
||||
new ParagonIE_Sodium_Core_ChaCha20_Ctx($key, $nonce),
|
||||
str_repeat("\x00", $len)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $len
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function ietfStream($len, $nonce = '', $key = '')
|
||||
{
|
||||
return self::encryptBytes(
|
||||
new ParagonIE_Sodium_Core_ChaCha20_IetfCtx($key, $nonce),
|
||||
str_repeat("\x00", $len)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @param string $ic
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function ietfStreamXorIc($message, $nonce = '', $key = '', $ic = '')
|
||||
{
|
||||
return self::encryptBytes(
|
||||
new ParagonIE_Sodium_Core_ChaCha20_IetfCtx($key, $nonce, $ic),
|
||||
$message
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @param string $ic
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function streamXorIc($message, $nonce = '', $key = '', $ic = '')
|
||||
{
|
||||
return self::encryptBytes(
|
||||
new ParagonIE_Sodium_Core_ChaCha20_Ctx($key, $nonce, $ic),
|
||||
$message
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_ChaCha20_Ctx', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_ChaCha20_Ctx
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_ChaCha20_Ctx extends ParagonIE_Sodium_Core_Util implements ArrayAccess
|
||||
{
|
||||
/**
|
||||
* @var SplFixedArray internally, <int, int>
|
||||
*/
|
||||
protected $container;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_ChaCha20_Ctx constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $key ChaCha20 key.
|
||||
* @param string $iv Initialization Vector (a.k.a. nonce).
|
||||
* @param string $counter The initial counter value.
|
||||
* Defaults to 8 0x00 bytes.
|
||||
* @throws InvalidArgumentException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public function __construct($key = '', $iv = '', $counter = '')
|
||||
{
|
||||
if (self::strlen($key) !== 32) {
|
||||
throw new InvalidArgumentException('ChaCha20 expects a 256-bit key.');
|
||||
}
|
||||
if (self::strlen($iv) !== 8) {
|
||||
throw new InvalidArgumentException('ChaCha20 expects a 64-bit nonce.');
|
||||
}
|
||||
$this->container = new SplFixedArray(16);
|
||||
|
||||
/* "expand 32-byte k" as per ChaCha20 spec */
|
||||
$this->container[0] = 0x61707865;
|
||||
$this->container[1] = 0x3320646e;
|
||||
$this->container[2] = 0x79622d32;
|
||||
$this->container[3] = 0x6b206574;
|
||||
$this->container[4] = self::load_4(self::substr($key, 0, 4));
|
||||
$this->container[5] = self::load_4(self::substr($key, 4, 4));
|
||||
$this->container[6] = self::load_4(self::substr($key, 8, 4));
|
||||
$this->container[7] = self::load_4(self::substr($key, 12, 4));
|
||||
$this->container[8] = self::load_4(self::substr($key, 16, 4));
|
||||
$this->container[9] = self::load_4(self::substr($key, 20, 4));
|
||||
$this->container[10] = self::load_4(self::substr($key, 24, 4));
|
||||
$this->container[11] = self::load_4(self::substr($key, 28, 4));
|
||||
|
||||
if (empty($counter)) {
|
||||
$this->container[12] = 0;
|
||||
$this->container[13] = 0;
|
||||
} else {
|
||||
$this->container[12] = self::load_4(self::substr($counter, 0, 4));
|
||||
$this->container[13] = self::load_4(self::substr($counter, 4, 4));
|
||||
}
|
||||
$this->container[14] = self::load_4(self::substr($iv, 0, 4));
|
||||
$this->container[15] = self::load_4(self::substr($iv, 4, 4));
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @param int $value
|
||||
* @return void
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
if (!is_int($offset)) {
|
||||
throw new InvalidArgumentException('Expected an integer');
|
||||
}
|
||||
if (!is_int($value)) {
|
||||
throw new InvalidArgumentException('Expected an integer');
|
||||
}
|
||||
$this->container[$offset] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return bool
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return isset($this->container[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return void
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
unset($this->container[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return mixed|null
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
return isset($this->container[$offset])
|
||||
? $this->container[$offset]
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_ChaCha20_IetfCtx', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_ChaCha20_IetfCtx
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_ChaCha20_IetfCtx extends ParagonIE_Sodium_Core_ChaCha20_Ctx
|
||||
{
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_ChaCha20_IetfCtx constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $key ChaCha20 key.
|
||||
* @param string $iv Initialization Vector (a.k.a. nonce).
|
||||
* @param string $counter The initial counter value.
|
||||
* Defaults to 4 0x00 bytes.
|
||||
* @throws InvalidArgumentException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public function __construct($key = '', $iv = '', $counter = '')
|
||||
{
|
||||
if (self::strlen($iv) !== 12) {
|
||||
throw new InvalidArgumentException('ChaCha20 expects a 96-bit nonce in IETF mode.');
|
||||
}
|
||||
parent::__construct($key, self::substr($iv, 0, 8), $counter);
|
||||
|
||||
if (!empty($counter)) {
|
||||
$this->container[12] = self::load_4(self::substr($counter, 0, 4));
|
||||
}
|
||||
$this->container[13] = self::load_4(self::substr($iv, 0, 4));
|
||||
$this->container[14] = self::load_4(self::substr($iv, 4, 4));
|
||||
$this->container[15] = self::load_4(self::substr($iv, 8, 4));
|
||||
}
|
||||
}
|
||||
+3836
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,127 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Curve25519_Fe', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*
|
||||
* This represents a Field Element
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Curve25519_Fe implements ArrayAccess
|
||||
{
|
||||
/**
|
||||
* @var array<int, int>
|
||||
*/
|
||||
protected $container = array();
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $size = 10;
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param array<int, int> $array
|
||||
* @param bool $save_indexes
|
||||
* @return self
|
||||
*/
|
||||
public static function fromArray($array, $save_indexes = null)
|
||||
{
|
||||
$count = count($array);
|
||||
if ($save_indexes) {
|
||||
$keys = array_keys($array);
|
||||
} else {
|
||||
$keys = range(0, $count - 1);
|
||||
}
|
||||
$array = array_values($array);
|
||||
/** @var array<int, int> $keys */
|
||||
|
||||
$obj = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
if ($save_indexes) {
|
||||
for ($i = 0; $i < $count; ++$i) {
|
||||
$obj->offsetSet($keys[$i], $array[$i]);
|
||||
}
|
||||
} else {
|
||||
for ($i = 0; $i < $count; ++$i) {
|
||||
$obj->offsetSet($i, $array[$i]);
|
||||
}
|
||||
}
|
||||
return $obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int|null $offset
|
||||
* @param int $value
|
||||
* @return void
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetSet($offset, $value)
|
||||
{
|
||||
if (!is_int($value)) {
|
||||
throw new InvalidArgumentException('Expected an integer');
|
||||
}
|
||||
if (is_null($offset)) {
|
||||
$this->container[] = $value;
|
||||
} else {
|
||||
$this->container[$offset] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return bool
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetExists($offset)
|
||||
{
|
||||
return isset($this->container[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return void
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetUnset($offset)
|
||||
{
|
||||
unset($this->container[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $offset
|
||||
* @return int
|
||||
* @psalm-suppress MixedArrayOffset
|
||||
*/
|
||||
#[ReturnTypeWillChange]
|
||||
public function offsetGet($offset)
|
||||
{
|
||||
if (!isset($this->container[$offset])) {
|
||||
$this->container[$offset] = 0;
|
||||
}
|
||||
return (int) ($this->container[$offset]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function __debugInfo()
|
||||
{
|
||||
return array(implode(', ', $this->container));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_Cached', false)) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Curve25519_Ge_Cached
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Curve25519_Ge_Cached
|
||||
{
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $YplusX;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $YminusX;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Z;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $T2d;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_Curve25519_Ge_Cached constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $YplusX
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $YminusX
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $Z
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $T2d
|
||||
*/
|
||||
public function __construct(
|
||||
$YplusX = null,
|
||||
$YminusX = null,
|
||||
$Z = null,
|
||||
$T2d = null
|
||||
) {
|
||||
if ($YplusX === null) {
|
||||
$YplusX = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($YplusX instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 1 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->YplusX = $YplusX;
|
||||
if ($YminusX === null) {
|
||||
$YminusX = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($YminusX instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 2 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->YminusX = $YminusX;
|
||||
if ($Z === null) {
|
||||
$Z = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($Z instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 3 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Z = $Z;
|
||||
if ($T2d === null) {
|
||||
$T2d = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($T2d instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 4 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->T2d = $T2d;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_P1p1', false)) {
|
||||
return;
|
||||
}
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Curve25519_Ge_P1p1
|
||||
{
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $X;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Y;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Z;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $T;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_Curve25519_Ge_P1p1 constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $x
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $y
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $z
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $t
|
||||
*/
|
||||
public function __construct(
|
||||
$x = null,
|
||||
$y = null,
|
||||
$z = null,
|
||||
$t = null
|
||||
) {
|
||||
if ($x === null) {
|
||||
$x = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($x instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 1 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->X = $x;
|
||||
if ($y === null) {
|
||||
$y = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($y instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 2 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Y = $y;
|
||||
if ($z === null) {
|
||||
$z = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($z instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 3 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Z = $z;
|
||||
if ($t === null) {
|
||||
$t = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($t instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 4 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->T = $t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_P2', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Curve25519_Ge_P2
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Curve25519_Ge_P2
|
||||
{
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $X;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Y;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Z;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_Curve25519_Ge_P2 constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $x
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $y
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $z
|
||||
*/
|
||||
public function __construct(
|
||||
$x = null,
|
||||
$y = null,
|
||||
$z = null
|
||||
) {
|
||||
if ($x === null) {
|
||||
$x = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($x instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 1 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->X = $x;
|
||||
if ($y === null) {
|
||||
$y = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($y instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 2 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Y = $y;
|
||||
if ($z === null) {
|
||||
$z = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($z instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 3 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Z = $z;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_P3', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Curve25519_Ge_P3
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Curve25519_Ge_P3
|
||||
{
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $X;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Y;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $Z;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $T;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_Curve25519_Ge_P3 constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $x
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $y
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $z
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe|null $t
|
||||
*/
|
||||
public function __construct(
|
||||
$x = null,
|
||||
$y = null,
|
||||
$z = null,
|
||||
$t = null
|
||||
) {
|
||||
if ($x === null) {
|
||||
$x = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($x instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 1 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->X = $x;
|
||||
if ($y === null) {
|
||||
$y = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($y instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 2 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Y = $y;
|
||||
if ($z === null) {
|
||||
$z = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($z instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 3 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->Z = $z;
|
||||
if ($t === null) {
|
||||
$t = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($t instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 4 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->T = $t;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Curve25519_Ge_Precomp', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Curve25519_Ge_Precomp
|
||||
{
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $yplusx;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $yminusx;
|
||||
|
||||
/**
|
||||
* @var ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public $xy2d;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_Curve25519_Ge_Precomp constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $yplusx
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $yminusx
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $xy2d
|
||||
*/
|
||||
public function __construct(
|
||||
$yplusx = null,
|
||||
$yminusx = null,
|
||||
$xy2d = null
|
||||
) {
|
||||
if ($yplusx === null) {
|
||||
$yplusx = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($yplusx instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 1 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->yplusx = $yplusx;
|
||||
if ($yminusx === null) {
|
||||
$yminusx = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($yminusx instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 2 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->yminusx = $yminusx;
|
||||
if ($xy2d === null) {
|
||||
$xy2d = new ParagonIE_Sodium_Core_Curve25519_Fe();
|
||||
}
|
||||
if (!($xy2d instanceof ParagonIE_Sodium_Core_Curve25519_Fe)) {
|
||||
throw new TypeError('Argument 3 must be an instance of ParagonIE_Sodium_Core_Curve25519_Fe');
|
||||
}
|
||||
$this->xy2d = $xy2d;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,3 @@
|
||||
# Curve25519 Data Structures
|
||||
|
||||
These are PHP implementation of the [structs used in the ref10 curve25519 code](https://github.com/jedisct1/libsodium/blob/master/src/libsodium/include/sodium/private/curve25519_ref10.h).
|
||||
+554
@@ -0,0 +1,554 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Ed25519', false)) {
|
||||
return;
|
||||
}
|
||||
if (!class_exists('ParagonIE_Sodium_Core_Curve25519', false)) {
|
||||
require_once dirname(__FILE__) . '/Curve25519.php';
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Ed25519
|
||||
*/
|
||||
abstract class ParagonIE_Sodium_Core_Ed25519 extends ParagonIE_Sodium_Core_Curve25519
|
||||
{
|
||||
const KEYPAIR_BYTES = 96;
|
||||
const SEED_BYTES = 32;
|
||||
const SCALAR_BYTES = 32;
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @return string (96 bytes)
|
||||
* @throws Exception
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function keypair()
|
||||
{
|
||||
$seed = random_bytes(self::SEED_BYTES);
|
||||
$pk = '';
|
||||
$sk = '';
|
||||
self::seed_keypair($pk, $sk, $seed);
|
||||
return $sk . $pk;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $pk
|
||||
* @param string $sk
|
||||
* @param string $seed
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function seed_keypair(&$pk, &$sk, $seed)
|
||||
{
|
||||
if (self::strlen($seed) !== self::SEED_BYTES) {
|
||||
throw new RangeException('crypto_sign keypair seed must be 32 bytes long');
|
||||
}
|
||||
|
||||
/** @var string $pk */
|
||||
$pk = self::publickey_from_secretkey($seed);
|
||||
$sk = $seed . $pk;
|
||||
return $sk;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $keypair
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function secretkey($keypair)
|
||||
{
|
||||
if (self::strlen($keypair) !== self::KEYPAIR_BYTES) {
|
||||
throw new RangeException('crypto_sign keypair must be 96 bytes long');
|
||||
}
|
||||
return self::substr($keypair, 0, 64);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $keypair
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function publickey($keypair)
|
||||
{
|
||||
if (self::strlen($keypair) !== self::KEYPAIR_BYTES) {
|
||||
throw new RangeException('crypto_sign keypair must be 96 bytes long');
|
||||
}
|
||||
return self::substr($keypair, 64, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function publickey_from_secretkey($sk)
|
||||
{
|
||||
/** @var string $sk */
|
||||
$sk = hash('sha512', self::substr($sk, 0, 32), true);
|
||||
$sk[0] = self::intToChr(
|
||||
self::chrToInt($sk[0]) & 248
|
||||
);
|
||||
$sk[31] = self::intToChr(
|
||||
(self::chrToInt($sk[31]) & 63) | 64
|
||||
);
|
||||
return self::sk_to_pk($sk);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $pk
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function pk_to_curve25519($pk)
|
||||
{
|
||||
if (self::small_order($pk)) {
|
||||
throw new SodiumException('Public key is on a small order');
|
||||
}
|
||||
$A = self::ge_frombytes_negate_vartime(self::substr($pk, 0, 32));
|
||||
$p1 = self::ge_mul_l($A);
|
||||
if (!self::fe_isnonzero($p1->X)) {
|
||||
throw new SodiumException('Unexpected zero result');
|
||||
}
|
||||
|
||||
# fe_1(one_minus_y);
|
||||
# fe_sub(one_minus_y, one_minus_y, A.Y);
|
||||
# fe_invert(one_minus_y, one_minus_y);
|
||||
$one_minux_y = self::fe_invert(
|
||||
self::fe_sub(
|
||||
self::fe_1(),
|
||||
$A->Y
|
||||
)
|
||||
);
|
||||
|
||||
# fe_1(x);
|
||||
# fe_add(x, x, A.Y);
|
||||
# fe_mul(x, x, one_minus_y);
|
||||
$x = self::fe_mul(
|
||||
self::fe_add(self::fe_1(), $A->Y),
|
||||
$one_minux_y
|
||||
);
|
||||
|
||||
# fe_tobytes(curve25519_pk, x);
|
||||
return self::fe_tobytes($x);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function sk_to_pk($sk)
|
||||
{
|
||||
return self::ge_p3_tobytes(
|
||||
self::ge_scalarmult_base(
|
||||
self::substr($sk, 0, 32)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function sign($message, $sk)
|
||||
{
|
||||
/** @var string $signature */
|
||||
$signature = self::sign_detached($message, $sk);
|
||||
return $signature . $message;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message A signed message
|
||||
* @param string $pk Public key
|
||||
* @return string Message (without signature)
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function sign_open($message, $pk)
|
||||
{
|
||||
/** @var string $signature */
|
||||
$signature = self::substr($message, 0, 64);
|
||||
|
||||
/** @var string $message */
|
||||
$message = self::substr($message, 64);
|
||||
|
||||
if (self::verify_detached($signature, $message, $pk)) {
|
||||
return $message;
|
||||
}
|
||||
throw new SodiumException('Invalid signature');
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $sk
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function sign_detached($message, $sk)
|
||||
{
|
||||
# crypto_hash_sha512(az, sk, 32);
|
||||
$az = hash('sha512', self::substr($sk, 0, 32), true);
|
||||
|
||||
# az[0] &= 248;
|
||||
# az[31] &= 63;
|
||||
# az[31] |= 64;
|
||||
$az[0] = self::intToChr(self::chrToInt($az[0]) & 248);
|
||||
$az[31] = self::intToChr((self::chrToInt($az[31]) & 63) | 64);
|
||||
|
||||
# crypto_hash_sha512_init(&hs);
|
||||
# crypto_hash_sha512_update(&hs, az + 32, 32);
|
||||
# crypto_hash_sha512_update(&hs, m, mlen);
|
||||
# crypto_hash_sha512_final(&hs, nonce);
|
||||
$hs = hash_init('sha512');
|
||||
hash_update($hs, self::substr($az, 32, 32));
|
||||
hash_update($hs, $message);
|
||||
$nonceHash = hash_final($hs, true);
|
||||
|
||||
# memmove(sig + 32, sk + 32, 32);
|
||||
$pk = self::substr($sk, 32, 32);
|
||||
|
||||
# sc_reduce(nonce);
|
||||
# ge_scalarmult_base(&R, nonce);
|
||||
# ge_p3_tobytes(sig, &R);
|
||||
$nonce = self::sc_reduce($nonceHash) . self::substr($nonceHash, 32);
|
||||
$sig = self::ge_p3_tobytes(
|
||||
self::ge_scalarmult_base($nonce)
|
||||
);
|
||||
|
||||
# crypto_hash_sha512_init(&hs);
|
||||
# crypto_hash_sha512_update(&hs, sig, 64);
|
||||
# crypto_hash_sha512_update(&hs, m, mlen);
|
||||
# crypto_hash_sha512_final(&hs, hram);
|
||||
$hs = hash_init('sha512');
|
||||
hash_update($hs, self::substr($sig, 0, 32));
|
||||
hash_update($hs, self::substr($pk, 0, 32));
|
||||
hash_update($hs, $message);
|
||||
$hramHash = hash_final($hs, true);
|
||||
|
||||
# sc_reduce(hram);
|
||||
# sc_muladd(sig + 32, hram, az, nonce);
|
||||
$hram = self::sc_reduce($hramHash);
|
||||
$sigAfter = self::sc_muladd($hram, $az, $nonce);
|
||||
$sig = self::substr($sig, 0, 32) . self::substr($sigAfter, 0, 32);
|
||||
|
||||
try {
|
||||
ParagonIE_Sodium_Compat::memzero($az);
|
||||
} catch (SodiumException $ex) {
|
||||
$az = null;
|
||||
}
|
||||
return $sig;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $sig
|
||||
* @param string $message
|
||||
* @param string $pk
|
||||
* @return bool
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function verify_detached($sig, $message, $pk)
|
||||
{
|
||||
if (self::strlen($sig) < 64) {
|
||||
throw new SodiumException('Signature is too short');
|
||||
}
|
||||
if ((self::chrToInt($sig[63]) & 240) && self::check_S_lt_L(self::substr($sig, 32, 32))) {
|
||||
throw new SodiumException('S < L - Invalid signature');
|
||||
}
|
||||
if (self::small_order($sig)) {
|
||||
throw new SodiumException('Signature is on too small of an order');
|
||||
}
|
||||
if ((self::chrToInt($sig[63]) & 224) !== 0) {
|
||||
throw new SodiumException('Invalid signature');
|
||||
}
|
||||
$d = 0;
|
||||
for ($i = 0; $i < 32; ++$i) {
|
||||
$d |= self::chrToInt($pk[$i]);
|
||||
}
|
||||
if ($d === 0) {
|
||||
throw new SodiumException('All zero public key');
|
||||
}
|
||||
|
||||
/** @var bool The original value of ParagonIE_Sodium_Compat::$fastMult */
|
||||
$orig = ParagonIE_Sodium_Compat::$fastMult;
|
||||
|
||||
// Set ParagonIE_Sodium_Compat::$fastMult to true to speed up verification.
|
||||
ParagonIE_Sodium_Compat::$fastMult = true;
|
||||
|
||||
/** @var ParagonIE_Sodium_Core_Curve25519_Ge_P3 $A */
|
||||
$A = self::ge_frombytes_negate_vartime($pk);
|
||||
|
||||
/** @var string $hDigest */
|
||||
$hDigest = hash(
|
||||
'sha512',
|
||||
self::substr($sig, 0, 32) .
|
||||
self::substr($pk, 0, 32) .
|
||||
$message,
|
||||
true
|
||||
);
|
||||
|
||||
/** @var string $h */
|
||||
$h = self::sc_reduce($hDigest) . self::substr($hDigest, 32);
|
||||
|
||||
/** @var ParagonIE_Sodium_Core_Curve25519_Ge_P2 $R */
|
||||
$R = self::ge_double_scalarmult_vartime(
|
||||
$h,
|
||||
$A,
|
||||
self::substr($sig, 32)
|
||||
);
|
||||
|
||||
/** @var string $rcheck */
|
||||
$rcheck = self::ge_tobytes($R);
|
||||
|
||||
// Reset ParagonIE_Sodium_Compat::$fastMult to what it was before.
|
||||
ParagonIE_Sodium_Compat::$fastMult = $orig;
|
||||
|
||||
return self::verify_32($rcheck, self::substr($sig, 0, 32));
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $S
|
||||
* @return bool
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function check_S_lt_L($S)
|
||||
{
|
||||
if (self::strlen($S) < 32) {
|
||||
throw new SodiumException('Signature must be 32 bytes');
|
||||
}
|
||||
$L = array(
|
||||
0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58,
|
||||
0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10
|
||||
);
|
||||
$c = 0;
|
||||
$n = 1;
|
||||
$i = 32;
|
||||
|
||||
/** @var array<int, int> $L */
|
||||
do {
|
||||
--$i;
|
||||
$x = self::chrToInt($S[$i]);
|
||||
$c |= (
|
||||
(($x - $L[$i]) >> 8) & $n
|
||||
);
|
||||
$n &= (
|
||||
(($x ^ $L[$i]) - 1) >> 8
|
||||
);
|
||||
} while ($i !== 0);
|
||||
|
||||
return $c === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $R
|
||||
* @return bool
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function small_order($R)
|
||||
{
|
||||
/** @var array<int, array<int, int>> $blocklist */
|
||||
$blocklist = array(
|
||||
/* 0 (order 4) */
|
||||
array(
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
),
|
||||
/* 1 (order 1) */
|
||||
array(
|
||||
0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
),
|
||||
/* 2707385501144840649318225287225658788936804267575313519463743609750303402022 (order 8) */
|
||||
array(
|
||||
0x26, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
|
||||
0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
|
||||
0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
|
||||
0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x05
|
||||
),
|
||||
/* 55188659117513257062467267217118295137698188065244968500265048394206261417927 (order 8) */
|
||||
array(
|
||||
0xc7, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
|
||||
0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
|
||||
0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
|
||||
0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0x7a
|
||||
),
|
||||
/* p-1 (order 2) */
|
||||
array(
|
||||
0x13, 0xe8, 0x95, 0x8f, 0xc2, 0xb2, 0x27, 0xb0,
|
||||
0x45, 0xc3, 0xf4, 0x89, 0xf2, 0xef, 0x98, 0xf0,
|
||||
0xd5, 0xdf, 0xac, 0x05, 0xd3, 0xc6, 0x33, 0x39,
|
||||
0xb1, 0x38, 0x02, 0x88, 0x6d, 0x53, 0xfc, 0x85
|
||||
),
|
||||
/* p (order 4) */
|
||||
array(
|
||||
0xb4, 0x17, 0x6a, 0x70, 0x3d, 0x4d, 0xd8, 0x4f,
|
||||
0xba, 0x3c, 0x0b, 0x76, 0x0d, 0x10, 0x67, 0x0f,
|
||||
0x2a, 0x20, 0x53, 0xfa, 0x2c, 0x39, 0xcc, 0xc6,
|
||||
0x4e, 0xc7, 0xfd, 0x77, 0x92, 0xac, 0x03, 0xfa
|
||||
),
|
||||
/* p+1 (order 1) */
|
||||
array(
|
||||
0xec, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
|
||||
),
|
||||
/* p+2707385501144840649318225287225658788936804267575313519463743609750303402022 (order 8) */
|
||||
array(
|
||||
0xed, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
|
||||
),
|
||||
/* p+55188659117513257062467267217118295137698188065244968500265048394206261417927 (order 8) */
|
||||
array(
|
||||
0xee, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f
|
||||
),
|
||||
/* 2p-1 (order 2) */
|
||||
array(
|
||||
0xd9, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
|
||||
),
|
||||
/* 2p (order 4) */
|
||||
array(
|
||||
0xda, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
|
||||
),
|
||||
/* 2p+1 (order 1) */
|
||||
array(
|
||||
0xdb, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
|
||||
)
|
||||
);
|
||||
/** @var int $countBlocklist */
|
||||
$countBlocklist = count($blocklist);
|
||||
|
||||
for ($i = 0; $i < $countBlocklist; ++$i) {
|
||||
$c = 0;
|
||||
for ($j = 0; $j < 32; ++$j) {
|
||||
$c |= self::chrToInt($R[$j]) ^ (int) $blocklist[$i][$j];
|
||||
}
|
||||
if ($c === 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalar_complement($s)
|
||||
{
|
||||
$t_ = self::L . str_repeat("\x00", 32);
|
||||
sodium_increment($t_);
|
||||
$s_ = $s . str_repeat("\x00", 32);
|
||||
ParagonIE_Sodium_Compat::sub($t_, $s_);
|
||||
return self::sc_reduce($t_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalar_random()
|
||||
{
|
||||
do {
|
||||
$r = ParagonIE_Sodium_Compat::randombytes_buf(self::SCALAR_BYTES);
|
||||
$r[self::SCALAR_BYTES - 1] = self::intToChr(
|
||||
self::chrToInt($r[self::SCALAR_BYTES - 1]) & 0x1f
|
||||
);
|
||||
} while (
|
||||
!self::check_S_lt_L($r) || ParagonIE_Sodium_Compat::is_zero($r)
|
||||
);
|
||||
return $r;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalar_negate($s)
|
||||
{
|
||||
$t_ = self::L . str_repeat("\x00", 32) ;
|
||||
$s_ = $s . str_repeat("\x00", 32) ;
|
||||
ParagonIE_Sodium_Compat::sub($t_, $s_);
|
||||
return self::sc_reduce($t_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $a
|
||||
* @param string $b
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalar_add($a, $b)
|
||||
{
|
||||
$a_ = $a . str_repeat("\x00", 32);
|
||||
$b_ = $b . str_repeat("\x00", 32);
|
||||
ParagonIE_Sodium_Compat::add($a_, $b_);
|
||||
return self::sc_reduce($a_);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalar_sub($x, $y)
|
||||
{
|
||||
$yn = self::scalar_negate($y);
|
||||
return self::scalar_add($x, $yn);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_HChaCha20', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_HChaCha20
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_HChaCha20 extends ParagonIE_Sodium_Core_ChaCha20
|
||||
{
|
||||
/**
|
||||
* @param string $in
|
||||
* @param string $key
|
||||
* @param string|null $c
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function hChaCha20($in = '', $key = '', $c = null)
|
||||
{
|
||||
$ctx = array();
|
||||
|
||||
if ($c === null) {
|
||||
$ctx[0] = 0x61707865;
|
||||
$ctx[1] = 0x3320646e;
|
||||
$ctx[2] = 0x79622d32;
|
||||
$ctx[3] = 0x6b206574;
|
||||
} else {
|
||||
$ctx[0] = self::load_4(self::substr($c, 0, 4));
|
||||
$ctx[1] = self::load_4(self::substr($c, 4, 4));
|
||||
$ctx[2] = self::load_4(self::substr($c, 8, 4));
|
||||
$ctx[3] = self::load_4(self::substr($c, 12, 4));
|
||||
}
|
||||
$ctx[4] = self::load_4(self::substr($key, 0, 4));
|
||||
$ctx[5] = self::load_4(self::substr($key, 4, 4));
|
||||
$ctx[6] = self::load_4(self::substr($key, 8, 4));
|
||||
$ctx[7] = self::load_4(self::substr($key, 12, 4));
|
||||
$ctx[8] = self::load_4(self::substr($key, 16, 4));
|
||||
$ctx[9] = self::load_4(self::substr($key, 20, 4));
|
||||
$ctx[10] = self::load_4(self::substr($key, 24, 4));
|
||||
$ctx[11] = self::load_4(self::substr($key, 28, 4));
|
||||
$ctx[12] = self::load_4(self::substr($in, 0, 4));
|
||||
$ctx[13] = self::load_4(self::substr($in, 4, 4));
|
||||
$ctx[14] = self::load_4(self::substr($in, 8, 4));
|
||||
$ctx[15] = self::load_4(self::substr($in, 12, 4));
|
||||
return self::hChaCha20Bytes($ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $ctx
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
protected static function hChaCha20Bytes(array $ctx)
|
||||
{
|
||||
$x0 = (int) $ctx[0];
|
||||
$x1 = (int) $ctx[1];
|
||||
$x2 = (int) $ctx[2];
|
||||
$x3 = (int) $ctx[3];
|
||||
$x4 = (int) $ctx[4];
|
||||
$x5 = (int) $ctx[5];
|
||||
$x6 = (int) $ctx[6];
|
||||
$x7 = (int) $ctx[7];
|
||||
$x8 = (int) $ctx[8];
|
||||
$x9 = (int) $ctx[9];
|
||||
$x10 = (int) $ctx[10];
|
||||
$x11 = (int) $ctx[11];
|
||||
$x12 = (int) $ctx[12];
|
||||
$x13 = (int) $ctx[13];
|
||||
$x14 = (int) $ctx[14];
|
||||
$x15 = (int) $ctx[15];
|
||||
|
||||
for ($i = 0; $i < 10; ++$i) {
|
||||
# QUARTERROUND( x0, x4, x8, x12)
|
||||
list($x0, $x4, $x8, $x12) = self::quarterRound($x0, $x4, $x8, $x12);
|
||||
|
||||
# QUARTERROUND( x1, x5, x9, x13)
|
||||
list($x1, $x5, $x9, $x13) = self::quarterRound($x1, $x5, $x9, $x13);
|
||||
|
||||
# QUARTERROUND( x2, x6, x10, x14)
|
||||
list($x2, $x6, $x10, $x14) = self::quarterRound($x2, $x6, $x10, $x14);
|
||||
|
||||
# QUARTERROUND( x3, x7, x11, x15)
|
||||
list($x3, $x7, $x11, $x15) = self::quarterRound($x3, $x7, $x11, $x15);
|
||||
|
||||
# QUARTERROUND( x0, x5, x10, x15)
|
||||
list($x0, $x5, $x10, $x15) = self::quarterRound($x0, $x5, $x10, $x15);
|
||||
|
||||
# QUARTERROUND( x1, x6, x11, x12)
|
||||
list($x1, $x6, $x11, $x12) = self::quarterRound($x1, $x6, $x11, $x12);
|
||||
|
||||
# QUARTERROUND( x2, x7, x8, x13)
|
||||
list($x2, $x7, $x8, $x13) = self::quarterRound($x2, $x7, $x8, $x13);
|
||||
|
||||
# QUARTERROUND( x3, x4, x9, x14)
|
||||
list($x3, $x4, $x9, $x14) = self::quarterRound($x3, $x4, $x9, $x14);
|
||||
}
|
||||
|
||||
return self::store32_le((int) ($x0 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x1 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x2 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x3 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x12 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x13 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x14 & 0xffffffff)) .
|
||||
self::store32_le((int) ($x15 & 0xffffffff));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_HSalsa20', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_HSalsa20
|
||||
*/
|
||||
abstract class ParagonIE_Sodium_Core_HSalsa20 extends ParagonIE_Sodium_Core_Salsa20
|
||||
{
|
||||
/**
|
||||
* Calculate an hsalsa20 hash of a single block
|
||||
*
|
||||
* HSalsa20 doesn't have a counter and will never be used for more than
|
||||
* one block (used to derive a subkey for xsalsa20).
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $in
|
||||
* @param string $k
|
||||
* @param string|null $c
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function hsalsa20($in, $k, $c = null)
|
||||
{
|
||||
if ($c === null) {
|
||||
$x0 = 0x61707865;
|
||||
$x5 = 0x3320646e;
|
||||
$x10 = 0x79622d32;
|
||||
$x15 = 0x6b206574;
|
||||
} else {
|
||||
$x0 = self::load_4(self::substr($c, 0, 4));
|
||||
$x5 = self::load_4(self::substr($c, 4, 4));
|
||||
$x10 = self::load_4(self::substr($c, 8, 4));
|
||||
$x15 = self::load_4(self::substr($c, 12, 4));
|
||||
}
|
||||
$x1 = self::load_4(self::substr($k, 0, 4));
|
||||
$x2 = self::load_4(self::substr($k, 4, 4));
|
||||
$x3 = self::load_4(self::substr($k, 8, 4));
|
||||
$x4 = self::load_4(self::substr($k, 12, 4));
|
||||
$x11 = self::load_4(self::substr($k, 16, 4));
|
||||
$x12 = self::load_4(self::substr($k, 20, 4));
|
||||
$x13 = self::load_4(self::substr($k, 24, 4));
|
||||
$x14 = self::load_4(self::substr($k, 28, 4));
|
||||
$x6 = self::load_4(self::substr($in, 0, 4));
|
||||
$x7 = self::load_4(self::substr($in, 4, 4));
|
||||
$x8 = self::load_4(self::substr($in, 8, 4));
|
||||
$x9 = self::load_4(self::substr($in, 12, 4));
|
||||
|
||||
for ($i = self::ROUNDS; $i > 0; $i -= 2) {
|
||||
$x4 ^= self::rotate($x0 + $x12, 7);
|
||||
$x8 ^= self::rotate($x4 + $x0, 9);
|
||||
$x12 ^= self::rotate($x8 + $x4, 13);
|
||||
$x0 ^= self::rotate($x12 + $x8, 18);
|
||||
$x9 ^= self::rotate($x5 + $x1, 7);
|
||||
$x13 ^= self::rotate($x9 + $x5, 9);
|
||||
$x1 ^= self::rotate($x13 + $x9, 13);
|
||||
$x5 ^= self::rotate($x1 + $x13, 18);
|
||||
$x14 ^= self::rotate($x10 + $x6, 7);
|
||||
$x2 ^= self::rotate($x14 + $x10, 9);
|
||||
$x6 ^= self::rotate($x2 + $x14, 13);
|
||||
$x10 ^= self::rotate($x6 + $x2, 18);
|
||||
$x3 ^= self::rotate($x15 + $x11, 7);
|
||||
$x7 ^= self::rotate($x3 + $x15, 9);
|
||||
$x11 ^= self::rotate($x7 + $x3, 13);
|
||||
$x15 ^= self::rotate($x11 + $x7, 18);
|
||||
$x1 ^= self::rotate($x0 + $x3, 7);
|
||||
$x2 ^= self::rotate($x1 + $x0, 9);
|
||||
$x3 ^= self::rotate($x2 + $x1, 13);
|
||||
$x0 ^= self::rotate($x3 + $x2, 18);
|
||||
$x6 ^= self::rotate($x5 + $x4, 7);
|
||||
$x7 ^= self::rotate($x6 + $x5, 9);
|
||||
$x4 ^= self::rotate($x7 + $x6, 13);
|
||||
$x5 ^= self::rotate($x4 + $x7, 18);
|
||||
$x11 ^= self::rotate($x10 + $x9, 7);
|
||||
$x8 ^= self::rotate($x11 + $x10, 9);
|
||||
$x9 ^= self::rotate($x8 + $x11, 13);
|
||||
$x10 ^= self::rotate($x9 + $x8, 18);
|
||||
$x12 ^= self::rotate($x15 + $x14, 7);
|
||||
$x13 ^= self::rotate($x12 + $x15, 9);
|
||||
$x14 ^= self::rotate($x13 + $x12, 13);
|
||||
$x15 ^= self::rotate($x14 + $x13, 18);
|
||||
}
|
||||
|
||||
return self::store32_le($x0) .
|
||||
self::store32_le($x5) .
|
||||
self::store32_le($x10) .
|
||||
self::store32_le($x15) .
|
||||
self::store32_le($x6) .
|
||||
self::store32_le($x7) .
|
||||
self::store32_le($x8) .
|
||||
self::store32_le($x9);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Poly1305', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Poly1305
|
||||
*/
|
||||
abstract class ParagonIE_Sodium_Core_Poly1305 extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
const BLOCK_SIZE = 16;
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $m
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function onetimeauth($m, $key)
|
||||
{
|
||||
if (self::strlen($key) < 32) {
|
||||
throw new InvalidArgumentException(
|
||||
'Key must be 32 bytes long.'
|
||||
);
|
||||
}
|
||||
$state = new ParagonIE_Sodium_Core_Poly1305_State(
|
||||
self::substr($key, 0, 32)
|
||||
);
|
||||
return $state
|
||||
->update($m)
|
||||
->finish();
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $mac
|
||||
* @param string $m
|
||||
* @param string $key
|
||||
* @return bool
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function onetimeauth_verify($mac, $m, $key)
|
||||
{
|
||||
if (self::strlen($key) < 32) {
|
||||
throw new InvalidArgumentException(
|
||||
'Key must be 32 bytes long.'
|
||||
);
|
||||
}
|
||||
$state = new ParagonIE_Sodium_Core_Poly1305_State(
|
||||
self::substr($key, 0, 32)
|
||||
);
|
||||
$calc = $state
|
||||
->update($m)
|
||||
->finish();
|
||||
return self::verify_16($calc, $mac);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Poly1305_State', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Poly1305_State
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Poly1305_State extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
/**
|
||||
* @var array<int, int>
|
||||
*/
|
||||
protected $buffer = array();
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
protected $final = false;
|
||||
|
||||
/**
|
||||
* @var array<int, int>
|
||||
*/
|
||||
public $h;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
protected $leftover = 0;
|
||||
|
||||
/**
|
||||
* @var int[]
|
||||
*/
|
||||
public $r;
|
||||
|
||||
/**
|
||||
* @var int[]
|
||||
*/
|
||||
public $pad;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_Poly1305_State constructor.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $key
|
||||
* @throws InvalidArgumentException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public function __construct($key = '')
|
||||
{
|
||||
if (self::strlen($key) < 32) {
|
||||
throw new InvalidArgumentException(
|
||||
'Poly1305 requires a 32-byte key'
|
||||
);
|
||||
}
|
||||
/* r &= 0xffffffc0ffffffc0ffffffc0fffffff */
|
||||
$this->r = array(
|
||||
(int) ((self::load_4(self::substr($key, 0, 4))) & 0x3ffffff),
|
||||
(int) ((self::load_4(self::substr($key, 3, 4)) >> 2) & 0x3ffff03),
|
||||
(int) ((self::load_4(self::substr($key, 6, 4)) >> 4) & 0x3ffc0ff),
|
||||
(int) ((self::load_4(self::substr($key, 9, 4)) >> 6) & 0x3f03fff),
|
||||
(int) ((self::load_4(self::substr($key, 12, 4)) >> 8) & 0x00fffff)
|
||||
);
|
||||
|
||||
/* h = 0 */
|
||||
$this->h = array(0, 0, 0, 0, 0);
|
||||
|
||||
/* save pad for later */
|
||||
$this->pad = array(
|
||||
self::load_4(self::substr($key, 16, 4)),
|
||||
self::load_4(self::substr($key, 20, 4)),
|
||||
self::load_4(self::substr($key, 24, 4)),
|
||||
self::load_4(self::substr($key, 28, 4)),
|
||||
);
|
||||
|
||||
$this->leftover = 0;
|
||||
$this->final = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Zero internal buffer upon destruction
|
||||
*/
|
||||
public function __destruct()
|
||||
{
|
||||
$this->r[0] ^= $this->r[0];
|
||||
$this->r[1] ^= $this->r[1];
|
||||
$this->r[2] ^= $this->r[2];
|
||||
$this->r[3] ^= $this->r[3];
|
||||
$this->r[4] ^= $this->r[4];
|
||||
$this->h[0] ^= $this->h[0];
|
||||
$this->h[1] ^= $this->h[1];
|
||||
$this->h[2] ^= $this->h[2];
|
||||
$this->h[3] ^= $this->h[3];
|
||||
$this->h[4] ^= $this->h[4];
|
||||
$this->pad[0] ^= $this->pad[0];
|
||||
$this->pad[1] ^= $this->pad[1];
|
||||
$this->pad[2] ^= $this->pad[2];
|
||||
$this->pad[3] ^= $this->pad[3];
|
||||
$this->leftover = 0;
|
||||
$this->final = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @return self
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public function update($message = '')
|
||||
{
|
||||
$bytes = self::strlen($message);
|
||||
if ($bytes < 1) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
/* handle leftover */
|
||||
if ($this->leftover) {
|
||||
$want = ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE - $this->leftover;
|
||||
if ($want > $bytes) {
|
||||
$want = $bytes;
|
||||
}
|
||||
for ($i = 0; $i < $want; ++$i) {
|
||||
$mi = self::chrToInt($message[$i]);
|
||||
$this->buffer[$this->leftover + $i] = $mi;
|
||||
}
|
||||
// We snip off the leftmost bytes.
|
||||
$message = self::substr($message, $want);
|
||||
$bytes = self::strlen($message);
|
||||
$this->leftover += $want;
|
||||
if ($this->leftover < ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
|
||||
// We still don't have enough to run $this->blocks()
|
||||
return $this;
|
||||
}
|
||||
|
||||
$this->blocks(
|
||||
self::intArrayToString($this->buffer),
|
||||
ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
|
||||
);
|
||||
$this->leftover = 0;
|
||||
}
|
||||
|
||||
/* process full blocks */
|
||||
if ($bytes >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
|
||||
/** @var int $want */
|
||||
$want = $bytes & ~(ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE - 1);
|
||||
if ($want >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
|
||||
$block = self::substr($message, 0, $want);
|
||||
if (self::strlen($block) >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
|
||||
$this->blocks($block, $want);
|
||||
$message = self::substr($message, $want);
|
||||
$bytes = self::strlen($message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* store leftover */
|
||||
if ($bytes) {
|
||||
for ($i = 0; $i < $bytes; ++$i) {
|
||||
$mi = self::chrToInt($message[$i]);
|
||||
$this->buffer[$this->leftover + $i] = $mi;
|
||||
}
|
||||
$this->leftover = (int) $this->leftover + $bytes;
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @param int $bytes
|
||||
* @return self
|
||||
* @throws TypeError
|
||||
*/
|
||||
public function blocks($message, $bytes)
|
||||
{
|
||||
if (self::strlen($message) < 16) {
|
||||
$message = str_pad($message, 16, "\x00", STR_PAD_RIGHT);
|
||||
}
|
||||
/** @var int $hibit */
|
||||
$hibit = $this->final ? 0 : 1 << 24; /* 1 << 128 */
|
||||
$r0 = (int) $this->r[0];
|
||||
$r1 = (int) $this->r[1];
|
||||
$r2 = (int) $this->r[2];
|
||||
$r3 = (int) $this->r[3];
|
||||
$r4 = (int) $this->r[4];
|
||||
|
||||
$s1 = self::mul($r1, 5, 3);
|
||||
$s2 = self::mul($r2, 5, 3);
|
||||
$s3 = self::mul($r3, 5, 3);
|
||||
$s4 = self::mul($r4, 5, 3);
|
||||
|
||||
$h0 = $this->h[0];
|
||||
$h1 = $this->h[1];
|
||||
$h2 = $this->h[2];
|
||||
$h3 = $this->h[3];
|
||||
$h4 = $this->h[4];
|
||||
|
||||
while ($bytes >= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE) {
|
||||
/* h += m[i] */
|
||||
$h0 += self::load_4(self::substr($message, 0, 4)) & 0x3ffffff;
|
||||
$h1 += (self::load_4(self::substr($message, 3, 4)) >> 2) & 0x3ffffff;
|
||||
$h2 += (self::load_4(self::substr($message, 6, 4)) >> 4) & 0x3ffffff;
|
||||
$h3 += (self::load_4(self::substr($message, 9, 4)) >> 6) & 0x3ffffff;
|
||||
$h4 += (self::load_4(self::substr($message, 12, 4)) >> 8) | $hibit;
|
||||
|
||||
/* h *= r */
|
||||
$d0 = (
|
||||
self::mul($h0, $r0, 27) +
|
||||
self::mul($s4, $h1, 27) +
|
||||
self::mul($s3, $h2, 27) +
|
||||
self::mul($s2, $h3, 27) +
|
||||
self::mul($s1, $h4, 27)
|
||||
);
|
||||
|
||||
$d1 = (
|
||||
self::mul($h0, $r1, 27) +
|
||||
self::mul($h1, $r0, 27) +
|
||||
self::mul($s4, $h2, 27) +
|
||||
self::mul($s3, $h3, 27) +
|
||||
self::mul($s2, $h4, 27)
|
||||
);
|
||||
|
||||
$d2 = (
|
||||
self::mul($h0, $r2, 27) +
|
||||
self::mul($h1, $r1, 27) +
|
||||
self::mul($h2, $r0, 27) +
|
||||
self::mul($s4, $h3, 27) +
|
||||
self::mul($s3, $h4, 27)
|
||||
);
|
||||
|
||||
$d3 = (
|
||||
self::mul($h0, $r3, 27) +
|
||||
self::mul($h1, $r2, 27) +
|
||||
self::mul($h2, $r1, 27) +
|
||||
self::mul($h3, $r0, 27) +
|
||||
self::mul($s4, $h4, 27)
|
||||
);
|
||||
|
||||
$d4 = (
|
||||
self::mul($h0, $r4, 27) +
|
||||
self::mul($h1, $r3, 27) +
|
||||
self::mul($h2, $r2, 27) +
|
||||
self::mul($h3, $r1, 27) +
|
||||
self::mul($h4, $r0, 27)
|
||||
);
|
||||
|
||||
/* (partial) h %= p */
|
||||
/** @var int $c */
|
||||
$c = $d0 >> 26;
|
||||
/** @var int $h0 */
|
||||
$h0 = $d0 & 0x3ffffff;
|
||||
$d1 += $c;
|
||||
|
||||
/** @var int $c */
|
||||
$c = $d1 >> 26;
|
||||
/** @var int $h1 */
|
||||
$h1 = $d1 & 0x3ffffff;
|
||||
$d2 += $c;
|
||||
|
||||
/** @var int $c */
|
||||
$c = $d2 >> 26;
|
||||
/** @var int $h2 */
|
||||
$h2 = $d2 & 0x3ffffff;
|
||||
$d3 += $c;
|
||||
|
||||
/** @var int $c */
|
||||
$c = $d3 >> 26;
|
||||
/** @var int $h3 */
|
||||
$h3 = $d3 & 0x3ffffff;
|
||||
$d4 += $c;
|
||||
|
||||
/** @var int $c */
|
||||
$c = $d4 >> 26;
|
||||
/** @var int $h4 */
|
||||
$h4 = $d4 & 0x3ffffff;
|
||||
$h0 += (int) self::mul($c, 5, 3);
|
||||
|
||||
/** @var int $c */
|
||||
$c = $h0 >> 26;
|
||||
/** @var int $h0 */
|
||||
$h0 &= 0x3ffffff;
|
||||
$h1 += $c;
|
||||
|
||||
// Chop off the left 32 bytes.
|
||||
$message = self::substr(
|
||||
$message,
|
||||
ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
|
||||
);
|
||||
$bytes -= ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE;
|
||||
}
|
||||
|
||||
$this->h = array(
|
||||
(int) ($h0 & 0xffffffff),
|
||||
(int) ($h1 & 0xffffffff),
|
||||
(int) ($h2 & 0xffffffff),
|
||||
(int) ($h3 & 0xffffffff),
|
||||
(int) ($h4 & 0xffffffff)
|
||||
);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public function finish()
|
||||
{
|
||||
/* process the remaining block */
|
||||
if ($this->leftover) {
|
||||
$i = $this->leftover;
|
||||
$this->buffer[$i++] = 1;
|
||||
for (; $i < ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE; ++$i) {
|
||||
$this->buffer[$i] = 0;
|
||||
}
|
||||
$this->final = true;
|
||||
$this->blocks(
|
||||
self::substr(
|
||||
self::intArrayToString($this->buffer),
|
||||
0,
|
||||
ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
|
||||
),
|
||||
ParagonIE_Sodium_Core_Poly1305::BLOCK_SIZE
|
||||
);
|
||||
}
|
||||
|
||||
$h0 = (int) $this->h[0];
|
||||
$h1 = (int) $this->h[1];
|
||||
$h2 = (int) $this->h[2];
|
||||
$h3 = (int) $this->h[3];
|
||||
$h4 = (int) $this->h[4];
|
||||
|
||||
/** @var int $c */
|
||||
$c = $h1 >> 26;
|
||||
/** @var int $h1 */
|
||||
$h1 &= 0x3ffffff;
|
||||
/** @var int $h2 */
|
||||
$h2 += $c;
|
||||
/** @var int $c */
|
||||
$c = $h2 >> 26;
|
||||
/** @var int $h2 */
|
||||
$h2 &= 0x3ffffff;
|
||||
$h3 += $c;
|
||||
/** @var int $c */
|
||||
$c = $h3 >> 26;
|
||||
$h3 &= 0x3ffffff;
|
||||
$h4 += $c;
|
||||
/** @var int $c */
|
||||
$c = $h4 >> 26;
|
||||
$h4 &= 0x3ffffff;
|
||||
/** @var int $h0 */
|
||||
$h0 += self::mul($c, 5, 3);
|
||||
/** @var int $c */
|
||||
$c = $h0 >> 26;
|
||||
/** @var int $h0 */
|
||||
$h0 &= 0x3ffffff;
|
||||
/** @var int $h1 */
|
||||
$h1 += $c;
|
||||
|
||||
/* compute h + -p */
|
||||
/** @var int $g0 */
|
||||
$g0 = $h0 + 5;
|
||||
/** @var int $c */
|
||||
$c = $g0 >> 26;
|
||||
/** @var int $g0 */
|
||||
$g0 &= 0x3ffffff;
|
||||
|
||||
/** @var int $g1 */
|
||||
$g1 = $h1 + $c;
|
||||
/** @var int $c */
|
||||
$c = $g1 >> 26;
|
||||
$g1 &= 0x3ffffff;
|
||||
|
||||
/** @var int $g2 */
|
||||
$g2 = $h2 + $c;
|
||||
/** @var int $c */
|
||||
$c = $g2 >> 26;
|
||||
/** @var int $g2 */
|
||||
$g2 &= 0x3ffffff;
|
||||
|
||||
/** @var int $g3 */
|
||||
$g3 = $h3 + $c;
|
||||
/** @var int $c */
|
||||
$c = $g3 >> 26;
|
||||
/** @var int $g3 */
|
||||
$g3 &= 0x3ffffff;
|
||||
|
||||
/** @var int $g4 */
|
||||
$g4 = ($h4 + $c - (1 << 26)) & 0xffffffff;
|
||||
|
||||
/* select h if h < p, or h + -p if h >= p */
|
||||
/** @var int $mask */
|
||||
$mask = ($g4 >> 31) - 1;
|
||||
|
||||
$g0 &= $mask;
|
||||
$g1 &= $mask;
|
||||
$g2 &= $mask;
|
||||
$g3 &= $mask;
|
||||
$g4 &= $mask;
|
||||
|
||||
/** @var int $mask */
|
||||
$mask = ~$mask & 0xffffffff;
|
||||
/** @var int $h0 */
|
||||
$h0 = ($h0 & $mask) | $g0;
|
||||
/** @var int $h1 */
|
||||
$h1 = ($h1 & $mask) | $g1;
|
||||
/** @var int $h2 */
|
||||
$h2 = ($h2 & $mask) | $g2;
|
||||
/** @var int $h3 */
|
||||
$h3 = ($h3 & $mask) | $g3;
|
||||
/** @var int $h4 */
|
||||
$h4 = ($h4 & $mask) | $g4;
|
||||
|
||||
/* h = h % (2^128) */
|
||||
/** @var int $h0 */
|
||||
$h0 = (($h0) | ($h1 << 26)) & 0xffffffff;
|
||||
/** @var int $h1 */
|
||||
$h1 = (($h1 >> 6) | ($h2 << 20)) & 0xffffffff;
|
||||
/** @var int $h2 */
|
||||
$h2 = (($h2 >> 12) | ($h3 << 14)) & 0xffffffff;
|
||||
/** @var int $h3 */
|
||||
$h3 = (($h3 >> 18) | ($h4 << 8)) & 0xffffffff;
|
||||
|
||||
/* mac = (h + pad) % (2^128) */
|
||||
$f = (int) ($h0 + $this->pad[0]);
|
||||
$h0 = (int) $f;
|
||||
$f = (int) ($h1 + $this->pad[1] + ($f >> 32));
|
||||
$h1 = (int) $f;
|
||||
$f = (int) ($h2 + $this->pad[2] + ($f >> 32));
|
||||
$h2 = (int) $f;
|
||||
$f = (int) ($h3 + $this->pad[3] + ($f >> 32));
|
||||
$h3 = (int) $f;
|
||||
|
||||
return self::store32_le($h0 & 0xffffffff) .
|
||||
self::store32_le($h1 & 0xffffffff) .
|
||||
self::store32_le($h2 & 0xffffffff) .
|
||||
self::store32_le($h3 & 0xffffffff);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,707 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Ristretto255
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_Ristretto255 extends ParagonIE_Sodium_Core_Ed25519
|
||||
{
|
||||
const crypto_core_ristretto255_HASHBYTES = 64;
|
||||
const HASH_SC_L = 48;
|
||||
const CORE_H2C_SHA256 = 1;
|
||||
const CORE_H2C_SHA512 = 2;
|
||||
|
||||
/**
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $f
|
||||
* @param int $b
|
||||
* @return ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
*/
|
||||
public static function fe_cneg(ParagonIE_Sodium_Core_Curve25519_Fe $f, $b)
|
||||
{
|
||||
$negf = self::fe_neg($f);
|
||||
return self::fe_cmov($f, $negf, $b);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $f
|
||||
* @return ParagonIE_Sodium_Core_Curve25519_Fe
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function fe_abs(ParagonIE_Sodium_Core_Curve25519_Fe $f)
|
||||
{
|
||||
return self::fe_cneg($f, self::fe_isnegative($f));
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns 0 if this field element results in all NUL bytes.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $f
|
||||
* @return int
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function fe_iszero(ParagonIE_Sodium_Core_Curve25519_Fe $f)
|
||||
{
|
||||
static $zero;
|
||||
if ($zero === null) {
|
||||
$zero = str_repeat("\x00", 32);
|
||||
}
|
||||
/** @var string $zero */
|
||||
$str = self::fe_tobytes($f);
|
||||
|
||||
$d = 0;
|
||||
for ($i = 0; $i < 32; ++$i) {
|
||||
$d |= self::chrToInt($str[$i]);
|
||||
}
|
||||
return (($d - 1) >> 31) & 1;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $u
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $v
|
||||
* @return array{x: ParagonIE_Sodium_Core_Curve25519_Fe, nonsquare: int}
|
||||
*
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_sqrt_ratio_m1(
|
||||
ParagonIE_Sodium_Core_Curve25519_Fe $u,
|
||||
ParagonIE_Sodium_Core_Curve25519_Fe $v
|
||||
) {
|
||||
$sqrtm1 = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$sqrtm1);
|
||||
|
||||
$v3 = self::fe_mul(
|
||||
self::fe_sq($v),
|
||||
$v
|
||||
); /* v3 = v^3 */
|
||||
$x = self::fe_mul(
|
||||
self::fe_mul(
|
||||
self::fe_sq($v3),
|
||||
$u
|
||||
),
|
||||
$v
|
||||
); /* x = uv^7 */
|
||||
|
||||
$x = self::fe_mul(
|
||||
self::fe_mul(
|
||||
self::fe_pow22523($x), /* x = (uv^7)^((q-5)/8) */
|
||||
$v3
|
||||
),
|
||||
$u
|
||||
); /* x = uv^3(uv^7)^((q-5)/8) */
|
||||
|
||||
$vxx = self::fe_mul(
|
||||
self::fe_sq($x),
|
||||
$v
|
||||
); /* vx^2 */
|
||||
|
||||
$m_root_check = self::fe_sub($vxx, $u); /* vx^2-u */
|
||||
$p_root_check = self::fe_add($vxx, $u); /* vx^2+u */
|
||||
$f_root_check = self::fe_mul($u, $sqrtm1); /* u*sqrt(-1) */
|
||||
$f_root_check = self::fe_add($vxx, $f_root_check); /* vx^2+u*sqrt(-1) */
|
||||
|
||||
$has_m_root = self::fe_iszero($m_root_check);
|
||||
$has_p_root = self::fe_iszero($p_root_check);
|
||||
$has_f_root = self::fe_iszero($f_root_check);
|
||||
|
||||
$x_sqrtm1 = self::fe_mul($x, $sqrtm1); /* x*sqrt(-1) */
|
||||
|
||||
$x = self::fe_abs(
|
||||
self::fe_cmov($x, $x_sqrtm1, $has_p_root | $has_f_root)
|
||||
);
|
||||
return array(
|
||||
'x' => $x,
|
||||
'nonsquare' => $has_m_root | $has_p_root
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return int
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_point_is_canonical($s)
|
||||
{
|
||||
$c = (self::chrToInt($s[31]) & 0x7f) ^ 0x7f;
|
||||
for ($i = 30; $i > 0; --$i) {
|
||||
$c |= self::chrToInt($s[$i]) ^ 0xff;
|
||||
}
|
||||
$c = ($c - 1) >> 8;
|
||||
$d = (0xed - 1 - self::chrToInt($s[0])) >> 8;
|
||||
$e = self::chrToInt($s[31]) >> 7;
|
||||
|
||||
return 1 - ((($c & $d) | $e | self::chrToInt($s[0])) & 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @param bool $skipCanonicalCheck
|
||||
* @return array{h: ParagonIE_Sodium_Core_Curve25519_Ge_P3, res: int}
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_frombytes($s, $skipCanonicalCheck = false)
|
||||
{
|
||||
if (!$skipCanonicalCheck) {
|
||||
if (!self::ristretto255_point_is_canonical($s)) {
|
||||
throw new SodiumException('S is not canonical');
|
||||
}
|
||||
}
|
||||
|
||||
$s_ = self::fe_frombytes($s);
|
||||
$ss = self::fe_sq($s_); /* ss = s^2 */
|
||||
|
||||
$u1 = self::fe_sub(self::fe_1(), $ss); /* u1 = 1-ss */
|
||||
$u1u1 = self::fe_sq($u1); /* u1u1 = u1^2 */
|
||||
|
||||
$u2 = self::fe_add(self::fe_1(), $ss); /* u2 = 1+ss */
|
||||
$u2u2 = self::fe_sq($u2); /* u2u2 = u2^2 */
|
||||
|
||||
$v = self::fe_mul(
|
||||
ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$d),
|
||||
$u1u1
|
||||
); /* v = d*u1^2 */
|
||||
$v = self::fe_neg($v); /* v = -d*u1^2 */
|
||||
$v = self::fe_sub($v, $u2u2); /* v = -(d*u1^2)-u2^2 */
|
||||
$v_u2u2 = self::fe_mul($v, $u2u2); /* v_u2u2 = v*u2^2 */
|
||||
|
||||
// fe25519_1(one);
|
||||
// notsquare = ristretto255_sqrt_ratio_m1(inv_sqrt, one, v_u2u2);
|
||||
$one = self::fe_1();
|
||||
$result = self::ristretto255_sqrt_ratio_m1($one, $v_u2u2);
|
||||
$inv_sqrt = $result['x'];
|
||||
$notsquare = $result['nonsquare'];
|
||||
|
||||
$h = new ParagonIE_Sodium_Core_Curve25519_Ge_P3();
|
||||
|
||||
$h->X = self::fe_mul($inv_sqrt, $u2);
|
||||
$h->Y = self::fe_mul(self::fe_mul($inv_sqrt, $h->X), $v);
|
||||
|
||||
$h->X = self::fe_mul($h->X, $s_);
|
||||
$h->X = self::fe_abs(
|
||||
self::fe_add($h->X, $h->X)
|
||||
);
|
||||
$h->Y = self::fe_mul($u1, $h->Y);
|
||||
$h->Z = self::fe_1();
|
||||
$h->T = self::fe_mul($h->X, $h->Y);
|
||||
|
||||
$res = - ((1 - $notsquare) | self::fe_isnegative($h->T) | self::fe_iszero($h->Y));
|
||||
return array('h' => $h, 'res' => $res);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Ge_P3 $h
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_p3_tobytes(ParagonIE_Sodium_Core_Curve25519_Ge_P3 $h)
|
||||
{
|
||||
$sqrtm1 = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$sqrtm1);
|
||||
$invsqrtamd = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$invsqrtamd);
|
||||
|
||||
$u1 = self::fe_add($h->Z, $h->Y); /* u1 = Z+Y */
|
||||
$zmy = self::fe_sub($h->Z, $h->Y); /* zmy = Z-Y */
|
||||
$u1 = self::fe_mul($u1, $zmy); /* u1 = (Z+Y)*(Z-Y) */
|
||||
$u2 = self::fe_mul($h->X, $h->Y); /* u2 = X*Y */
|
||||
|
||||
$u1_u2u2 = self::fe_mul(self::fe_sq($u2), $u1); /* u1_u2u2 = u1*u2^2 */
|
||||
$one = self::fe_1();
|
||||
|
||||
// fe25519_1(one);
|
||||
// (void) ristretto255_sqrt_ratio_m1(inv_sqrt, one, u1_u2u2);
|
||||
$result = self::ristretto255_sqrt_ratio_m1($one, $u1_u2u2);
|
||||
$inv_sqrt = $result['x'];
|
||||
|
||||
$den1 = self::fe_mul($inv_sqrt, $u1); /* den1 = inv_sqrt*u1 */
|
||||
$den2 = self::fe_mul($inv_sqrt, $u2); /* den2 = inv_sqrt*u2 */
|
||||
$z_inv = self::fe_mul($h->T, self::fe_mul($den1, $den2)); /* z_inv = den1*den2*T */
|
||||
|
||||
$ix = self::fe_mul($h->X, $sqrtm1); /* ix = X*sqrt(-1) */
|
||||
$iy = self::fe_mul($h->Y, $sqrtm1); /* iy = Y*sqrt(-1) */
|
||||
$eden = self::fe_mul($den1, $invsqrtamd);
|
||||
|
||||
$t_z_inv = self::fe_mul($h->T, $z_inv); /* t_z_inv = T*z_inv */
|
||||
$rotate = self::fe_isnegative($t_z_inv);
|
||||
|
||||
$x_ = self::fe_copy($h->X);
|
||||
$y_ = self::fe_copy($h->Y);
|
||||
$den_inv = self::fe_copy($den2);
|
||||
|
||||
$x_ = self::fe_cmov($x_, $iy, $rotate);
|
||||
$y_ = self::fe_cmov($y_, $ix, $rotate);
|
||||
$den_inv = self::fe_cmov($den_inv, $eden, $rotate);
|
||||
|
||||
$x_z_inv = self::fe_mul($x_, $z_inv);
|
||||
$y_ = self::fe_cneg($y_, self::fe_isnegative($x_z_inv));
|
||||
|
||||
|
||||
// fe25519_sub(s_, h->Z, y_);
|
||||
// fe25519_mul(s_, den_inv, s_);
|
||||
// fe25519_abs(s_, s_);
|
||||
// fe25519_tobytes(s, s_);
|
||||
return self::fe_tobytes(
|
||||
self::fe_abs(
|
||||
self::fe_mul(
|
||||
$den_inv,
|
||||
self::fe_sub($h->Z, $y_)
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ParagonIE_Sodium_Core_Curve25519_Fe $t
|
||||
* @return ParagonIE_Sodium_Core_Curve25519_Ge_P3
|
||||
*
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_elligator(ParagonIE_Sodium_Core_Curve25519_Fe $t)
|
||||
{
|
||||
$sqrtm1 = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$sqrtm1);
|
||||
$onemsqd = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$onemsqd);
|
||||
$d = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$d);
|
||||
$sqdmone = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$sqdmone);
|
||||
$sqrtadm1 = ParagonIE_Sodium_Core_Curve25519_Fe::fromArray(self::$sqrtadm1);
|
||||
|
||||
$one = self::fe_1();
|
||||
$r = self::fe_mul($sqrtm1, self::fe_sq($t)); /* r = sqrt(-1)*t^2 */
|
||||
$u = self::fe_mul(self::fe_add($r, $one), $onemsqd); /* u = (r+1)*(1-d^2) */
|
||||
$c = self::fe_neg(self::fe_1()); /* c = -1 */
|
||||
$rpd = self::fe_add($r, $d); /* rpd = r+d */
|
||||
|
||||
$v = self::fe_mul(
|
||||
self::fe_sub(
|
||||
$c,
|
||||
self::fe_mul($r, $d)
|
||||
),
|
||||
$rpd
|
||||
); /* v = (c-r*d)*(r+d) */
|
||||
|
||||
$result = self::ristretto255_sqrt_ratio_m1($u, $v);
|
||||
$s = $result['x'];
|
||||
$wasnt_square = 1 - $result['nonsquare'];
|
||||
|
||||
$s_prime = self::fe_neg(
|
||||
self::fe_abs(
|
||||
self::fe_mul($s, $t)
|
||||
)
|
||||
); /* s_prime = -|s*t| */
|
||||
$s = self::fe_cmov($s, $s_prime, $wasnt_square);
|
||||
$c = self::fe_cmov($c, $r, $wasnt_square);
|
||||
|
||||
// fe25519_sub(n, r, one); /* n = r-1 */
|
||||
// fe25519_mul(n, n, c); /* n = c*(r-1) */
|
||||
// fe25519_mul(n, n, ed25519_sqdmone); /* n = c*(r-1)*(d-1)^2 */
|
||||
// fe25519_sub(n, n, v); /* n = c*(r-1)*(d-1)^2-v */
|
||||
$n = self::fe_sub(
|
||||
self::fe_mul(
|
||||
self::fe_mul(
|
||||
self::fe_sub($r, $one),
|
||||
$c
|
||||
),
|
||||
$sqdmone
|
||||
),
|
||||
$v
|
||||
); /* n = c*(r-1)*(d-1)^2-v */
|
||||
|
||||
$w0 = self::fe_mul(
|
||||
self::fe_add($s, $s),
|
||||
$v
|
||||
); /* w0 = 2s*v */
|
||||
|
||||
$w1 = self::fe_mul($n, $sqrtadm1); /* w1 = n*sqrt(ad-1) */
|
||||
$ss = self::fe_sq($s); /* ss = s^2 */
|
||||
$w2 = self::fe_sub($one, $ss); /* w2 = 1-s^2 */
|
||||
$w3 = self::fe_add($one, $ss); /* w3 = 1+s^2 */
|
||||
|
||||
return new ParagonIE_Sodium_Core_Curve25519_Ge_P3(
|
||||
self::fe_mul($w0, $w3),
|
||||
self::fe_mul($w2, $w1),
|
||||
self::fe_mul($w1, $w3),
|
||||
self::fe_mul($w0, $w2)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $h
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_from_hash($h)
|
||||
{
|
||||
if (self::strlen($h) !== 64) {
|
||||
throw new SodiumException('Hash must be 64 bytes');
|
||||
}
|
||||
//fe25519_frombytes(r0, h);
|
||||
//fe25519_frombytes(r1, h + 32);
|
||||
$r0 = self::fe_frombytes(self::substr($h, 0, 32));
|
||||
$r1 = self::fe_frombytes(self::substr($h, 32, 32));
|
||||
|
||||
//ristretto255_elligator(&p0, r0);
|
||||
//ristretto255_elligator(&p1, r1);
|
||||
$p0 = self::ristretto255_elligator($r0);
|
||||
$p1 = self::ristretto255_elligator($r1);
|
||||
|
||||
//ge25519_p3_to_cached(&p1_cached, &p1);
|
||||
//ge25519_add_cached(&p_p1p1, &p0, &p1_cached);
|
||||
$p_p1p1 = self::ge_add(
|
||||
$p0,
|
||||
self::ge_p3_to_cached($p1)
|
||||
);
|
||||
|
||||
//ge25519_p1p1_to_p3(&p, &p_p1p1);
|
||||
//ristretto255_p3_tobytes(s, &p);
|
||||
return self::ristretto255_p3_tobytes(
|
||||
self::ge_p1p1_to_p3($p_p1p1)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $p
|
||||
* @return int
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function is_valid_point($p)
|
||||
{
|
||||
$result = self::ristretto255_frombytes($p);
|
||||
if ($result['res'] !== 0) {
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $p
|
||||
* @param string $q
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_add($p, $q)
|
||||
{
|
||||
$p_res = self::ristretto255_frombytes($p);
|
||||
$q_res = self::ristretto255_frombytes($q);
|
||||
if ($p_res['res'] !== 0 || $q_res['res'] !== 0) {
|
||||
throw new SodiumException('Could not add points');
|
||||
}
|
||||
$p_p3 = $p_res['h'];
|
||||
$q_p3 = $q_res['h'];
|
||||
$q_cached = self::ge_p3_to_cached($q_p3);
|
||||
$r_p1p1 = self::ge_add($p_p3, $q_cached);
|
||||
$r_p3 = self::ge_p1p1_to_p3($r_p1p1);
|
||||
return self::ristretto255_p3_tobytes($r_p3);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $p
|
||||
* @param string $q
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_sub($p, $q)
|
||||
{
|
||||
$p_res = self::ristretto255_frombytes($p);
|
||||
$q_res = self::ristretto255_frombytes($q);
|
||||
if ($p_res['res'] !== 0 || $q_res['res'] !== 0) {
|
||||
throw new SodiumException('Could not add points');
|
||||
}
|
||||
$p_p3 = $p_res['h'];
|
||||
$q_p3 = $q_res['h'];
|
||||
$q_cached = self::ge_p3_to_cached($q_p3);
|
||||
$r_p1p1 = self::ge_sub($p_p3, $q_cached);
|
||||
$r_p3 = self::ge_p1p1_to_p3($r_p1p1);
|
||||
return self::ristretto255_p3_tobytes($r_p3);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $hLen
|
||||
* @param ?string $ctx
|
||||
* @param string $msg
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @psalm-suppress PossiblyInvalidArgument hash API
|
||||
*/
|
||||
protected static function h2c_string_to_hash_sha256($hLen, $ctx, $msg)
|
||||
{
|
||||
$h = array_fill(0, $hLen, 0);
|
||||
$ctx_len = !is_null($ctx) ? self::strlen($ctx) : 0;
|
||||
if ($hLen > 0xff) {
|
||||
throw new SodiumException('Hash must be less than 256 bytes');
|
||||
}
|
||||
|
||||
if ($ctx_len > 0xff) {
|
||||
$st = hash_init('sha256');
|
||||
self::hash_update($st, "H2C-OVERSIZE-DST-");
|
||||
self::hash_update($st, $ctx);
|
||||
$ctx = hash_final($st, true);
|
||||
$ctx_len = 32;
|
||||
}
|
||||
$t = array(0, $hLen, 0);
|
||||
$ux = str_repeat("\0", 64);
|
||||
$st = hash_init('sha256');
|
||||
self::hash_update($st, $ux);
|
||||
self::hash_update($st, $msg);
|
||||
self::hash_update($st, self::intArrayToString($t));
|
||||
self::hash_update($st, $ctx);
|
||||
self::hash_update($st, self::intToChr($ctx_len));
|
||||
$u0 = hash_final($st, true);
|
||||
|
||||
for ($i = 0; $i < $hLen; $i += 64) {
|
||||
$ux = self::xorStrings($ux, $u0);
|
||||
++$t[2];
|
||||
$st = hash_init('sha256');
|
||||
self::hash_update($st, $ux);
|
||||
self::hash_update($st, self::intToChr($t[2]));
|
||||
self::hash_update($st, $ctx);
|
||||
self::hash_update($st, self::intToChr($ctx_len));
|
||||
$ux = hash_final($st, true);
|
||||
$amount = min($hLen - $i, 64);
|
||||
for ($j = 0; $j < $amount; ++$j) {
|
||||
$h[$i + $j] = self::chrToInt($ux[$i]);
|
||||
}
|
||||
}
|
||||
return self::intArrayToString(array_slice($h, 0, $hLen));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $hLen
|
||||
* @param ?string $ctx
|
||||
* @param string $msg
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @psalm-suppress PossiblyInvalidArgument hash API
|
||||
*/
|
||||
protected static function h2c_string_to_hash_sha512($hLen, $ctx, $msg)
|
||||
{
|
||||
$h = array_fill(0, $hLen, 0);
|
||||
$ctx_len = !is_null($ctx) ? self::strlen($ctx) : 0;
|
||||
if ($hLen > 0xff) {
|
||||
throw new SodiumException('Hash must be less than 256 bytes');
|
||||
}
|
||||
|
||||
if ($ctx_len > 0xff) {
|
||||
$st = hash_init('sha256');
|
||||
self::hash_update($st, "H2C-OVERSIZE-DST-");
|
||||
self::hash_update($st, $ctx);
|
||||
$ctx = hash_final($st, true);
|
||||
$ctx_len = 32;
|
||||
}
|
||||
$t = array(0, $hLen, 0);
|
||||
$ux = str_repeat("\0", 128);
|
||||
$st = hash_init('sha512');
|
||||
self::hash_update($st, $ux);
|
||||
self::hash_update($st, $msg);
|
||||
self::hash_update($st, self::intArrayToString($t));
|
||||
self::hash_update($st, $ctx);
|
||||
self::hash_update($st, self::intToChr($ctx_len));
|
||||
$u0 = hash_final($st, true);
|
||||
|
||||
for ($i = 0; $i < $hLen; $i += 128) {
|
||||
$ux = self::xorStrings($ux, $u0);
|
||||
++$t[2];
|
||||
$st = hash_init('sha512');
|
||||
self::hash_update($st, $ux);
|
||||
self::hash_update($st, self::intToChr($t[2]));
|
||||
self::hash_update($st, $ctx);
|
||||
self::hash_update($st, self::intToChr($ctx_len));
|
||||
$ux = hash_final($st, true);
|
||||
$amount = min($hLen - $i, 128);
|
||||
for ($j = 0; $j < $amount; ++$j) {
|
||||
$h[$i + $j] = self::chrToInt($ux[$i]);
|
||||
}
|
||||
}
|
||||
return self::intArrayToString(array_slice($h, 0, $hLen));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $hLen
|
||||
* @param ?string $ctx
|
||||
* @param string $msg
|
||||
* @param int $hash_alg
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function h2c_string_to_hash($hLen, $ctx, $msg, $hash_alg)
|
||||
{
|
||||
switch ($hash_alg) {
|
||||
case self::CORE_H2C_SHA256:
|
||||
return self::h2c_string_to_hash_sha256($hLen, $ctx, $msg);
|
||||
case self::CORE_H2C_SHA512:
|
||||
return self::h2c_string_to_hash_sha512($hLen, $ctx, $msg);
|
||||
default:
|
||||
throw new SodiumException('Invalid H2C hash algorithm');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param ?string $ctx
|
||||
* @param string $msg
|
||||
* @param int $hash_alg
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
protected static function _string_to_element($ctx, $msg, $hash_alg)
|
||||
{
|
||||
return self::ristretto255_from_hash(
|
||||
self::h2c_string_to_hash(self::crypto_core_ristretto255_HASHBYTES, $ctx, $msg, $hash_alg)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws Exception
|
||||
*/
|
||||
public static function ristretto255_random()
|
||||
{
|
||||
return self::ristretto255_from_hash(
|
||||
ParagonIE_Sodium_Compat::randombytes_buf(self::crypto_core_ristretto255_HASHBYTES)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_scalar_random()
|
||||
{
|
||||
return self::scalar_random();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_scalar_complement($s)
|
||||
{
|
||||
return self::scalar_complement($s);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return string
|
||||
*/
|
||||
public static function ristretto255_scalar_invert($s)
|
||||
{
|
||||
return self::sc25519_invert($s);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_scalar_negate($s)
|
||||
{
|
||||
return self::scalar_negate($s);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
*/
|
||||
public static function ristretto255_scalar_add($x, $y)
|
||||
{
|
||||
return self::scalar_add($x, $y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
*/
|
||||
public static function ristretto255_scalar_sub($x, $y)
|
||||
{
|
||||
return self::scalar_sub($x, $y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $x
|
||||
* @param string $y
|
||||
* @return string
|
||||
*/
|
||||
public static function ristretto255_scalar_mul($x, $y)
|
||||
{
|
||||
return self::sc25519_mul($x, $y);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $ctx
|
||||
* @param string $msg
|
||||
* @param int $hash_alg
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function ristretto255_scalar_from_string($ctx, $msg, $hash_alg)
|
||||
{
|
||||
$h = array_fill(0, 64, 0);
|
||||
$h_be = self::stringToIntArray(
|
||||
self::h2c_string_to_hash(
|
||||
self::HASH_SC_L, $ctx, $msg, $hash_alg
|
||||
)
|
||||
);
|
||||
|
||||
for ($i = 0; $i < self::HASH_SC_L; ++$i) {
|
||||
$h[$i] = $h_be[self::HASH_SC_L - 1 - $i];
|
||||
}
|
||||
return self::ristretto255_scalar_reduce(self::intArrayToString($h));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $s
|
||||
* @return string
|
||||
*/
|
||||
public static function ristretto255_scalar_reduce($s)
|
||||
{
|
||||
return self::sc_reduce($s);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $n
|
||||
* @param string $p
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalarmult_ristretto255($n, $p)
|
||||
{
|
||||
if (self::strlen($n) !== 32) {
|
||||
throw new SodiumException('Scalar must be 32 bytes, ' . self::strlen($p) . ' given.');
|
||||
}
|
||||
if (self::strlen($p) !== 32) {
|
||||
throw new SodiumException('Point must be 32 bytes, ' . self::strlen($p) . ' given.');
|
||||
}
|
||||
$result = self::ristretto255_frombytes($p);
|
||||
if ($result['res'] !== 0) {
|
||||
throw new SodiumException('Could not multiply points');
|
||||
}
|
||||
$P = $result['h'];
|
||||
|
||||
$t = self::stringToIntArray($n);
|
||||
$t[31] &= 0x7f;
|
||||
$Q = self::ge_scalarmult(self::intArrayToString($t), $P);
|
||||
$q = self::ristretto255_p3_tobytes($Q);
|
||||
if (ParagonIE_Sodium_Compat::is_zero($q)) {
|
||||
throw new SodiumException('An unknown error has occurred');
|
||||
}
|
||||
return $q;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $n
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
*/
|
||||
public static function scalarmult_ristretto255_base($n)
|
||||
{
|
||||
$t = self::stringToIntArray($n);
|
||||
$t[31] &= 0x7f;
|
||||
$Q = self::ge_scalarmult_base(self::intArrayToString($t));
|
||||
$q = self::ristretto255_p3_tobytes($Q);
|
||||
if (ParagonIE_Sodium_Compat::is_zero($q)) {
|
||||
throw new SodiumException('An unknown error has occurred');
|
||||
}
|
||||
return $q;
|
||||
}
|
||||
}
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_Salsa20', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_Salsa20
|
||||
*/
|
||||
abstract class ParagonIE_Sodium_Core_Salsa20 extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
const ROUNDS = 20;
|
||||
|
||||
/**
|
||||
* Calculate an salsa20 hash of a single block
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $in
|
||||
* @param string $k
|
||||
* @param string|null $c
|
||||
* @return string
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function core_salsa20($in, $k, $c = null)
|
||||
{
|
||||
if (self::strlen($k) < 32) {
|
||||
throw new RangeException('Key must be 32 bytes long');
|
||||
}
|
||||
if ($c === null) {
|
||||
$j0 = $x0 = 0x61707865;
|
||||
$j5 = $x5 = 0x3320646e;
|
||||
$j10 = $x10 = 0x79622d32;
|
||||
$j15 = $x15 = 0x6b206574;
|
||||
} else {
|
||||
$j0 = $x0 = self::load_4(self::substr($c, 0, 4));
|
||||
$j5 = $x5 = self::load_4(self::substr($c, 4, 4));
|
||||
$j10 = $x10 = self::load_4(self::substr($c, 8, 4));
|
||||
$j15 = $x15 = self::load_4(self::substr($c, 12, 4));
|
||||
}
|
||||
$j1 = $x1 = self::load_4(self::substr($k, 0, 4));
|
||||
$j2 = $x2 = self::load_4(self::substr($k, 4, 4));
|
||||
$j3 = $x3 = self::load_4(self::substr($k, 8, 4));
|
||||
$j4 = $x4 = self::load_4(self::substr($k, 12, 4));
|
||||
$j6 = $x6 = self::load_4(self::substr($in, 0, 4));
|
||||
$j7 = $x7 = self::load_4(self::substr($in, 4, 4));
|
||||
$j8 = $x8 = self::load_4(self::substr($in, 8, 4));
|
||||
$j9 = $x9 = self::load_4(self::substr($in, 12, 4));
|
||||
$j11 = $x11 = self::load_4(self::substr($k, 16, 4));
|
||||
$j12 = $x12 = self::load_4(self::substr($k, 20, 4));
|
||||
$j13 = $x13 = self::load_4(self::substr($k, 24, 4));
|
||||
$j14 = $x14 = self::load_4(self::substr($k, 28, 4));
|
||||
|
||||
for ($i = self::ROUNDS; $i > 0; $i -= 2) {
|
||||
$x4 ^= self::rotate($x0 + $x12, 7);
|
||||
$x8 ^= self::rotate($x4 + $x0, 9);
|
||||
$x12 ^= self::rotate($x8 + $x4, 13);
|
||||
$x0 ^= self::rotate($x12 + $x8, 18);
|
||||
|
||||
$x9 ^= self::rotate($x5 + $x1, 7);
|
||||
$x13 ^= self::rotate($x9 + $x5, 9);
|
||||
$x1 ^= self::rotate($x13 + $x9, 13);
|
||||
$x5 ^= self::rotate($x1 + $x13, 18);
|
||||
|
||||
$x14 ^= self::rotate($x10 + $x6, 7);
|
||||
$x2 ^= self::rotate($x14 + $x10, 9);
|
||||
$x6 ^= self::rotate($x2 + $x14, 13);
|
||||
$x10 ^= self::rotate($x6 + $x2, 18);
|
||||
|
||||
$x3 ^= self::rotate($x15 + $x11, 7);
|
||||
$x7 ^= self::rotate($x3 + $x15, 9);
|
||||
$x11 ^= self::rotate($x7 + $x3, 13);
|
||||
$x15 ^= self::rotate($x11 + $x7, 18);
|
||||
|
||||
$x1 ^= self::rotate($x0 + $x3, 7);
|
||||
$x2 ^= self::rotate($x1 + $x0, 9);
|
||||
$x3 ^= self::rotate($x2 + $x1, 13);
|
||||
$x0 ^= self::rotate($x3 + $x2, 18);
|
||||
|
||||
$x6 ^= self::rotate($x5 + $x4, 7);
|
||||
$x7 ^= self::rotate($x6 + $x5, 9);
|
||||
$x4 ^= self::rotate($x7 + $x6, 13);
|
||||
$x5 ^= self::rotate($x4 + $x7, 18);
|
||||
|
||||
$x11 ^= self::rotate($x10 + $x9, 7);
|
||||
$x8 ^= self::rotate($x11 + $x10, 9);
|
||||
$x9 ^= self::rotate($x8 + $x11, 13);
|
||||
$x10 ^= self::rotate($x9 + $x8, 18);
|
||||
|
||||
$x12 ^= self::rotate($x15 + $x14, 7);
|
||||
$x13 ^= self::rotate($x12 + $x15, 9);
|
||||
$x14 ^= self::rotate($x13 + $x12, 13);
|
||||
$x15 ^= self::rotate($x14 + $x13, 18);
|
||||
}
|
||||
|
||||
$x0 += $j0;
|
||||
$x1 += $j1;
|
||||
$x2 += $j2;
|
||||
$x3 += $j3;
|
||||
$x4 += $j4;
|
||||
$x5 += $j5;
|
||||
$x6 += $j6;
|
||||
$x7 += $j7;
|
||||
$x8 += $j8;
|
||||
$x9 += $j9;
|
||||
$x10 += $j10;
|
||||
$x11 += $j11;
|
||||
$x12 += $j12;
|
||||
$x13 += $j13;
|
||||
$x14 += $j14;
|
||||
$x15 += $j15;
|
||||
|
||||
return self::store32_le($x0) .
|
||||
self::store32_le($x1) .
|
||||
self::store32_le($x2) .
|
||||
self::store32_le($x3) .
|
||||
self::store32_le($x4) .
|
||||
self::store32_le($x5) .
|
||||
self::store32_le($x6) .
|
||||
self::store32_le($x7) .
|
||||
self::store32_le($x8) .
|
||||
self::store32_le($x9) .
|
||||
self::store32_le($x10) .
|
||||
self::store32_le($x11) .
|
||||
self::store32_le($x12) .
|
||||
self::store32_le($x13) .
|
||||
self::store32_le($x14) .
|
||||
self::store32_le($x15);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $len
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function salsa20($len, $nonce, $key)
|
||||
{
|
||||
if (self::strlen($key) !== 32) {
|
||||
throw new RangeException('Key must be 32 bytes long');
|
||||
}
|
||||
$kcopy = '' . $key;
|
||||
$in = self::substr($nonce, 0, 8) . str_repeat("\0", 8);
|
||||
$c = '';
|
||||
while ($len >= 64) {
|
||||
$c .= self::core_salsa20($in, $kcopy, null);
|
||||
$u = 1;
|
||||
// Internal counter.
|
||||
for ($i = 8; $i < 16; ++$i) {
|
||||
$u += self::chrToInt($in[$i]);
|
||||
$in[$i] = self::intToChr($u & 0xff);
|
||||
$u >>= 8;
|
||||
}
|
||||
$len -= 64;
|
||||
}
|
||||
if ($len > 0) {
|
||||
$c .= self::substr(
|
||||
self::core_salsa20($in, $kcopy, null),
|
||||
0,
|
||||
$len
|
||||
);
|
||||
}
|
||||
try {
|
||||
ParagonIE_Sodium_Compat::memzero($kcopy);
|
||||
} catch (SodiumException $ex) {
|
||||
$kcopy = null;
|
||||
}
|
||||
return $c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $m
|
||||
* @param string $n
|
||||
* @param int $ic
|
||||
* @param string $k
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function salsa20_xor_ic($m, $n, $ic, $k)
|
||||
{
|
||||
$mlen = self::strlen($m);
|
||||
if ($mlen < 1) {
|
||||
return '';
|
||||
}
|
||||
$kcopy = self::substr($k, 0, 32);
|
||||
$in = self::substr($n, 0, 8);
|
||||
// Initialize the counter
|
||||
$in .= ParagonIE_Sodium_Core_Util::store64_le($ic);
|
||||
|
||||
$c = '';
|
||||
while ($mlen >= 64) {
|
||||
$block = self::core_salsa20($in, $kcopy, null);
|
||||
$c .= self::xorStrings(
|
||||
self::substr($m, 0, 64),
|
||||
self::substr($block, 0, 64)
|
||||
);
|
||||
$u = 1;
|
||||
for ($i = 8; $i < 16; ++$i) {
|
||||
$u += self::chrToInt($in[$i]);
|
||||
$in[$i] = self::intToChr($u & 0xff);
|
||||
$u >>= 8;
|
||||
}
|
||||
|
||||
$mlen -= 64;
|
||||
$m = self::substr($m, 64);
|
||||
}
|
||||
|
||||
if ($mlen) {
|
||||
$block = self::core_salsa20($in, $kcopy, null);
|
||||
$c .= self::xorStrings(
|
||||
self::substr($m, 0, $mlen),
|
||||
self::substr($block, 0, $mlen)
|
||||
);
|
||||
}
|
||||
try {
|
||||
ParagonIE_Sodium_Compat::memzero($block);
|
||||
ParagonIE_Sodium_Compat::memzero($kcopy);
|
||||
} catch (SodiumException $ex) {
|
||||
$block = null;
|
||||
$kcopy = null;
|
||||
}
|
||||
|
||||
return $c;
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $message
|
||||
* @param string $nonce
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function salsa20_xor($message, $nonce, $key)
|
||||
{
|
||||
return self::xorStrings(
|
||||
$message,
|
||||
self::salsa20(
|
||||
self::strlen($message),
|
||||
$nonce,
|
||||
$key
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $u
|
||||
* @param int $c
|
||||
* @return int
|
||||
*/
|
||||
public static function rotate($u, $c)
|
||||
{
|
||||
$u &= 0xffffffff;
|
||||
$c %= 32;
|
||||
return (int) (0xffffffff & (
|
||||
($u << $c)
|
||||
|
|
||||
($u >> (32 - $c))
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* Class ParagonIE_Sodium_Core_SecretStream_State
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_SecretStream_State
|
||||
{
|
||||
/** @var string $key */
|
||||
protected $key;
|
||||
|
||||
/** @var int $counter */
|
||||
protected $counter;
|
||||
|
||||
/** @var string $nonce */
|
||||
protected $nonce;
|
||||
|
||||
/** @var string $_pad */
|
||||
protected $_pad;
|
||||
|
||||
/**
|
||||
* ParagonIE_Sodium_Core_SecretStream_State constructor.
|
||||
* @param string $key
|
||||
* @param string|null $nonce
|
||||
*/
|
||||
public function __construct($key, $nonce = null)
|
||||
{
|
||||
$this->key = $key;
|
||||
$this->counter = 1;
|
||||
if (is_null($nonce)) {
|
||||
$nonce = str_repeat("\0", 12);
|
||||
}
|
||||
$this->nonce = str_pad($nonce, 12, "\0", STR_PAD_RIGHT);;
|
||||
$this->_pad = str_repeat("\0", 4);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function counterReset()
|
||||
{
|
||||
$this->counter = 1;
|
||||
$this->_pad = str_repeat("\0", 4);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getKey()
|
||||
{
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getCounter()
|
||||
{
|
||||
return ParagonIE_Sodium_Core_Util::store32_le($this->counter);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getNonce()
|
||||
{
|
||||
if (!is_string($this->nonce)) {
|
||||
$this->nonce = str_repeat("\0", 12);
|
||||
}
|
||||
if (ParagonIE_Sodium_Core_Util::strlen($this->nonce) !== 12) {
|
||||
$this->nonce = str_pad($this->nonce, 12, "\0", STR_PAD_RIGHT);
|
||||
}
|
||||
return $this->nonce;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function getCombinedNonce()
|
||||
{
|
||||
return $this->getCounter() .
|
||||
ParagonIE_Sodium_Core_Util::substr($this->getNonce(), 0, 8);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return self
|
||||
*/
|
||||
public function incrementCounter()
|
||||
{
|
||||
++$this->counter;
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return bool
|
||||
*/
|
||||
public function needsRekey()
|
||||
{
|
||||
return ($this->counter & 0xffff) === 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $newKeyAndNonce
|
||||
* @return self
|
||||
*/
|
||||
public function rekey($newKeyAndNonce)
|
||||
{
|
||||
$this->key = ParagonIE_Sodium_Core_Util::substr($newKeyAndNonce, 0, 32);
|
||||
$this->nonce = str_pad(
|
||||
ParagonIE_Sodium_Core_Util::substr($newKeyAndNonce, 32),
|
||||
12,
|
||||
"\0",
|
||||
STR_PAD_RIGHT
|
||||
);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $str
|
||||
* @return self
|
||||
*/
|
||||
public function xorNonce($str)
|
||||
{
|
||||
$this->nonce = ParagonIE_Sodium_Core_Util::xorStrings(
|
||||
$this->getNonce(),
|
||||
str_pad(
|
||||
ParagonIE_Sodium_Core_Util::substr($str, 0, 8),
|
||||
12,
|
||||
"\0",
|
||||
STR_PAD_RIGHT
|
||||
)
|
||||
);
|
||||
return $this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string $string
|
||||
* @return self
|
||||
*/
|
||||
public static function fromString($string)
|
||||
{
|
||||
$state = new ParagonIE_Sodium_Core_SecretStream_State(
|
||||
ParagonIE_Sodium_Core_Util::substr($string, 0, 32)
|
||||
);
|
||||
$state->counter = ParagonIE_Sodium_Core_Util::load_4(
|
||||
ParagonIE_Sodium_Core_Util::substr($string, 32, 4)
|
||||
);
|
||||
$state->nonce = ParagonIE_Sodium_Core_Util::substr($string, 36, 12);
|
||||
$state->_pad = ParagonIE_Sodium_Core_Util::substr($string, 48, 8);
|
||||
return $state;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return string
|
||||
*/
|
||||
public function toString()
|
||||
{
|
||||
return $this->key .
|
||||
$this->getCounter() .
|
||||
$this->nonce .
|
||||
$this->_pad;
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
<?php
|
||||
|
||||
if (class_exists('ParagonIE_Sodium_Core_SipHash', false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Class ParagonIE_SodiumCompat_Core_SipHash
|
||||
*
|
||||
* Only uses 32-bit arithmetic, while the original SipHash used 64-bit integers
|
||||
*/
|
||||
class ParagonIE_Sodium_Core_SipHash extends ParagonIE_Sodium_Core_Util
|
||||
{
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int[] $v
|
||||
* @return int[]
|
||||
*
|
||||
*/
|
||||
public static function sipRound(array $v)
|
||||
{
|
||||
# v0 += v1;
|
||||
list($v[0], $v[1]) = self::add(
|
||||
array($v[0], $v[1]),
|
||||
array($v[2], $v[3])
|
||||
);
|
||||
|
||||
# v1=ROTL(v1,13);
|
||||
list($v[2], $v[3]) = self::rotl_64((int) $v[2], (int) $v[3], 13);
|
||||
|
||||
# v1 ^= v0;
|
||||
$v[2] = (int) $v[2] ^ (int) $v[0];
|
||||
$v[3] = (int) $v[3] ^ (int) $v[1];
|
||||
|
||||
# v0=ROTL(v0,32);
|
||||
list($v[0], $v[1]) = self::rotl_64((int) $v[0], (int) $v[1], 32);
|
||||
|
||||
# v2 += v3;
|
||||
list($v[4], $v[5]) = self::add(
|
||||
array((int) $v[4], (int) $v[5]),
|
||||
array((int) $v[6], (int) $v[7])
|
||||
);
|
||||
|
||||
# v3=ROTL(v3,16);
|
||||
list($v[6], $v[7]) = self::rotl_64((int) $v[6], (int) $v[7], 16);
|
||||
|
||||
# v3 ^= v2;
|
||||
$v[6] = (int) $v[6] ^ (int) $v[4];
|
||||
$v[7] = (int) $v[7] ^ (int) $v[5];
|
||||
|
||||
# v0 += v3;
|
||||
list($v[0], $v[1]) = self::add(
|
||||
array((int) $v[0], (int) $v[1]),
|
||||
array((int) $v[6], (int) $v[7])
|
||||
);
|
||||
|
||||
# v3=ROTL(v3,21);
|
||||
list($v[6], $v[7]) = self::rotl_64((int) $v[6], (int) $v[7], 21);
|
||||
|
||||
# v3 ^= v0;
|
||||
$v[6] = (int) $v[6] ^ (int) $v[0];
|
||||
$v[7] = (int) $v[7] ^ (int) $v[1];
|
||||
|
||||
# v2 += v1;
|
||||
list($v[4], $v[5]) = self::add(
|
||||
array((int) $v[4], (int) $v[5]),
|
||||
array((int) $v[2], (int) $v[3])
|
||||
);
|
||||
|
||||
# v1=ROTL(v1,17);
|
||||
list($v[2], $v[3]) = self::rotl_64((int) $v[2], (int) $v[3], 17);
|
||||
|
||||
# v1 ^= v2;;
|
||||
$v[2] = (int) $v[2] ^ (int) $v[4];
|
||||
$v[3] = (int) $v[3] ^ (int) $v[5];
|
||||
|
||||
# v2=ROTL(v2,32)
|
||||
list($v[4], $v[5]) = self::rotl_64((int) $v[4], (int) $v[5], 32);
|
||||
|
||||
return $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add two 32 bit integers representing a 64-bit integer.
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int[] $a
|
||||
* @param int[] $b
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
public static function add(array $a, array $b)
|
||||
{
|
||||
/** @var int $x1 */
|
||||
$x1 = $a[1] + $b[1];
|
||||
/** @var int $c */
|
||||
$c = $x1 >> 32; // Carry if ($a + $b) > 0xffffffff
|
||||
/** @var int $x0 */
|
||||
$x0 = $a[0] + $b[0] + $c;
|
||||
return array(
|
||||
$x0 & 0xffffffff,
|
||||
$x1 & 0xffffffff
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param int $int0
|
||||
* @param int $int1
|
||||
* @param int $c
|
||||
* @return array<int, mixed>
|
||||
*/
|
||||
public static function rotl_64($int0, $int1, $c)
|
||||
{
|
||||
$int0 &= 0xffffffff;
|
||||
$int1 &= 0xffffffff;
|
||||
$c &= 63;
|
||||
if ($c === 32) {
|
||||
return array($int1, $int0);
|
||||
}
|
||||
if ($c > 31) {
|
||||
$tmp = $int1;
|
||||
$int1 = $int0;
|
||||
$int0 = $tmp;
|
||||
$c &= 31;
|
||||
}
|
||||
if ($c === 0) {
|
||||
return array($int0, $int1);
|
||||
}
|
||||
return array(
|
||||
0xffffffff & (
|
||||
($int0 << $c)
|
||||
|
|
||||
($int1 >> (32 - $c))
|
||||
),
|
||||
0xffffffff & (
|
||||
($int1 << $c)
|
||||
|
|
||||
($int0 >> (32 - $c))
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implements Siphash-2-4 using only 32-bit numbers.
|
||||
*
|
||||
* When we split an int into two, the higher bits go to the lower index.
|
||||
* e.g. 0xDEADBEEFAB10C92D becomes [
|
||||
* 0 => 0xDEADBEEF,
|
||||
* 1 => 0xAB10C92D
|
||||
* ].
|
||||
*
|
||||
* @internal You should not use this directly from another application
|
||||
*
|
||||
* @param string $in
|
||||
* @param string $key
|
||||
* @return string
|
||||
* @throws SodiumException
|
||||
* @throws TypeError
|
||||
*/
|
||||
public static function sipHash24($in, $key)
|
||||
{
|
||||
$inlen = self::strlen($in);
|
||||
|
||||
# /* "somepseudorandomlygeneratedbytes" */
|
||||
# u64 v0 = 0x736f6d6570736575ULL;
|
||||
# u64 v1 = 0x646f72616e646f6dULL;
|
||||
# u64 v2 = 0x6c7967656e657261ULL;
|
||||
# u64 v3 = 0x7465646279746573ULL;
|
||||
$v = array(
|
||||
0x736f6d65, // 0
|
||||
0x70736575, // 1
|
||||
0x646f7261, // 2
|
||||
0x6e646f6d, // 3
|
||||
0x6c796765, // 4
|
||||
0x6e657261, // 5
|
||||
0x74656462, // 6
|
||||
0x79746573 // 7
|
||||
);
|
||||
// v0 => $v[0], $v[1]
|
||||
// v1 => $v[2], $v[3]
|
||||
// v2 => $v[4], $v[5]
|
||||
// v3 => $v[6], $v[7]
|
||||
|
||||
# u64 k0 = LOAD64_LE( k );
|
||||
# u64 k1 = LOAD64_LE( k + 8 );
|
||||
$k = array(
|
||||
self::load_4(self::substr($key, 4, 4)),
|
||||
self::load_4(self::substr($key, 0, 4)),
|
||||
self::load_4(self::substr($key, 12, 4)),
|
||||
self::load_4(self::substr($key, 8, 4))
|
||||
);
|
||||
// k0 => $k[0], $k[1]
|
||||
// k1 => $k[2], $k[3]
|
||||
|
||||
# b = ( ( u64 )inlen ) << 56;
|
||||
$b = array(
|
||||
$inlen << 24,
|
||||
0
|
||||
);
|
||||
// See docblock for why the 0th index gets the higher bits.
|
||||
|
||||
# v3 ^= k1;
|
||||
$v[6] ^= $k[2];
|
||||
$v[7] ^= $k[3];
|
||||
# v2 ^= k0;
|
||||
$v[4] ^= $k[0];
|
||||
$v[5] ^= $k[1];
|
||||
# v1 ^= k1;
|
||||
$v[2] ^= $k[2];
|
||||
$v[3] ^= $k[3];
|
||||
# v0 ^= k0;
|
||||
$v[0] ^= $k[0];
|
||||
$v[1] ^= $k[1];
|
||||
|
||||
$left = $inlen;
|
||||
# for ( ; in != end; in += 8 )
|
||||
while ($left >= 8) {
|
||||
# m = LOAD64_LE( in );
|
||||
$m = array(
|
||||
self::load_4(self::substr($in, 4, 4)),
|
||||
self::load_4(self::substr($in, 0, 4))
|
||||
);
|
||||
|
||||
# v3 ^= m;
|
||||
$v[6] ^= $m[0];
|
||||
$v[7] ^= $m[1];
|
||||
|
||||
# SIPROUND;
|
||||
# SIPROUND;
|
||||
$v = self::sipRound($v);
|
||||
$v = self::sipRound($v);
|
||||
|
||||
# v0 ^= m;
|
||||
$v[0] ^= $m[0];
|
||||
$v[1] ^= $m[1];
|
||||
|
||||
$in = self::substr($in, 8);
|
||||
$left -= 8;
|
||||
}
|
||||
|
||||
# switch( left )
|
||||
# {
|
||||
# case 7: b |= ( ( u64 )in[ 6] ) << 48;
|
||||
# case 6: b |= ( ( u64 )in[ 5] ) << 40;
|
||||
# case 5: b |= ( ( u64 )in[ 4] ) << 32;
|
||||
# case 4: b |= ( ( u64 )in[ 3] ) << 24;
|
||||
# case 3: b |= ( ( u64 )in[ 2] ) << 16;
|
||||
# case 2: b |= ( ( u64 )in[ 1] ) << 8;
|
||||
# case 1: b |= ( ( u64 )in[ 0] ); break;
|
||||
# case 0: break;
|
||||
# }
|
||||
switch ($left) {
|
||||
case 7:
|
||||
$b[0] |= self::chrToInt($in[6]) << 16;
|
||||
case 6:
|
||||
$b[0] |= self::chrToInt($in[5]) << 8;
|
||||
case 5:
|
||||
$b[0] |= self::chrToInt($in[4]);
|
||||
case 4:
|
||||
$b[1] |= self::chrToInt($in[3]) << 24;
|
||||
case 3:
|
||||
$b[1] |= self::chrToInt($in[2]) << 16;
|
||||
case 2:
|
||||
$b[1] |= self::chrToInt($in[1]) << 8;
|
||||
case 1:
|
||||
$b[1] |= self::chrToInt($in[0]);
|
||||
case 0:
|
||||
break;
|
||||
}
|
||||
// See docblock for why the 0th index gets the higher bits.
|
||||
|
||||
# v3 ^= b;
|
||||
$v[6] ^= $b[0];
|
||||
$v[7] ^= $b[1];
|
||||
|
||||
# SIPROUND;
|
||||
# SIPROUND;
|
||||
$v = self::sipRound($v);
|
||||
$v = self::sipRound($v);
|
||||
|
||||
# v0 ^= b;
|
||||
$v[0] ^= $b[0];
|
||||
$v[1] ^= $b[1];
|
||||
|
||||
// Flip the lower 8 bits of v2 which is ($v[4], $v[5]) in our implementation
|
||||
# v2 ^= 0xff;
|
||||
$v[5] ^= 0xff;
|
||||
|
||||
# SIPROUND;
|
||||
# SIPROUND;
|
||||
# SIPROUND;
|
||||
# SIPROUND;
|
||||
$v = self::sipRound($v);
|
||||
$v = self::sipRound($v);
|
||||
$v = self::sipRound($v);
|
||||
$v = self::sipRound($v);
|
||||
|
||||
# b = v0 ^ v1 ^ v2 ^ v3;
|
||||
# STORE64_LE( out, b );
|
||||
return self::store32_le($v[1] ^ $v[3] ^ $v[5] ^ $v[7]) .
|
||||
self::store32_le($v[0] ^ $v[2] ^ $v[4] ^ $v[6]);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user