diff --git a/src/Common/Argon2S2K.php b/src/Common/Argon2S2K.php index 568b5f9e..d5cf72d8 100644 --- a/src/Common/Argon2S2K.php +++ b/src/Common/Argon2S2K.php @@ -10,10 +10,7 @@ use OpenPGP\Enum\S2kType; use OpenPGP\Type\S2KInterface; -use Symfony\Component\Process\{ - ExecutableFinder, - Process, -}; +use Symfony\Component\Process\{ExecutableFinder, Process}; use Symfony\Component\Process\Exception\ProcessFailedException; /** @@ -46,7 +43,7 @@ class Argon2S2K implements S2KInterface /** * argon2 command */ - const ARGON2_COMMAND = 'argon2'; + const ARGON2_COMMAND = "argon2"; /** * Argon2 command path @@ -71,25 +68,23 @@ public function __construct( private readonly string $salt, private readonly int $iteration = 3, private readonly int $parallelism = 1, - private readonly int $memoryExponent = 16, - ) - { + private readonly int $memoryExponent = 16 + ) { $finder = new ExecutableFinder(); - if (empty($this->argon2Path = $finder->find(self::ARGON2_COMMAND))) { - if (!function_exists('sodium_crypto_pwhash')) { + if (empty(($this->argon2Path = $finder->find(self::ARGON2_COMMAND)))) { + if (!function_exists("sodium_crypto_pwhash")) { throw new \RuntimeException( - 'Argon2 string to key is unsupported.', + "Argon2 string to key is unsupported." ); - } - elseif ($parallelism > self::PHP_PARALLELISM) { + } elseif ($parallelism > self::PHP_PARALLELISM) { throw new \InvalidArgumentException( - 'PHP Argon2 only support 1 parallelism.', + "PHP Argon2 only support 1 parallelism." ); } } if (strlen($salt) !== self::SALT_LENGTH) { throw new \InvalidArgumentException( - 'Salt size must be ' . self::SALT_LENGTH . ' bytes.', + "Salt size must be " . self::SALT_LENGTH . " bytes." ); } $this->type = S2kType::Argon2; @@ -112,9 +107,7 @@ public function toBytes(): string /** * {@inheritdoc} */ - public function produceKey( - string $passphrase, int $length - ): string + public function produceKey(string $passphrase, int $length): string { if (empty($this->argon2Path)) { return sodium_crypto_pwhash( @@ -122,23 +115,28 @@ public function produceKey( $passphrase, $this->salt, $this->iteration, - 1 << ($this->memoryExponent + 10), + 1 << $this->memoryExponent + 10 ); - } - else { + } else { $process = new Process([ - $this->argon2Path, $this->salt, '-id', '-r', - '-l', $length, - '-t', $this->iteration, - '-p', $this->parallelism, - '-m', $this->memoryExponent, + $this->argon2Path, + $this->salt, + "-id", + "-r", + "-l", + $length, + "-t", + $this->iteration, + "-p", + $this->parallelism, + "-m", + $this->memoryExponent, ]); $process->setInput($passphrase); try { $process->mustRun(); return hex2bin(trim($process->getOutput())); - } - catch (ProcessFailedException $ex) { + } catch (ProcessFailedException $ex) { throw $ex; } } @@ -158,9 +156,7 @@ public static function fromBytes(string $bytes): self $iteration = ord($bytes[$offset++]); $parallelism = ord($bytes[$offset++]); $memoryExponent = ord($bytes[$offset++]); - return new self( - $salt, $iteration, $parallelism, $memoryExponent - ); + return new self($salt, $iteration, $parallelism, $memoryExponent); } /** @@ -172,6 +168,6 @@ public static function argon2Supported(): bool { $finder = new ExecutableFinder(); return !empty($finder->find(self::ARGON2_COMMAND)) || - function_exists('sodium_crypto_pwhash'); + function_exists("sodium_crypto_pwhash"); } } diff --git a/src/Common/Armor.php b/src/Common/Armor.php index 332b2994..d3ba80a8 100644 --- a/src/Common/Armor.php +++ b/src/Common/Armor.php @@ -16,36 +16,36 @@ * * Class that represents an OpenPGP Base64 Conversions. * See RFC 9580, section 6. - * + * * @package OpenPGP * @category Common * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ final class Armor { - const MESSAGE_BEGIN = "-----BEGIN PGP MESSAGE-----\n"; + const MESSAGE_BEGIN = "-----BEGIN PGP MESSAGE-----\n"; const SIGNED_MESSAGE_BEGIN = "-----BEGIN PGP SIGNED MESSAGE-----\n"; - const MESSAGE_END = "-----END PGP MESSAGE-----\n"; + const MESSAGE_END = "-----END PGP MESSAGE-----\n"; const MULTIPART_SECTION_MESSAGE_BEGIN = "-----BEGIN PGP MESSAGE, PART %u/%u-----\n"; - const MULTIPART_SECTION_MESSAGE_END = "-----END PGP MESSAGE, PART %u/%u-----\n"; + const MULTIPART_SECTION_MESSAGE_END = "-----END PGP MESSAGE, PART %u/%u-----\n"; const MULTIPART_LAST_MESSAGE_BEGIN = "-----BEGIN PGP MESSAGE, PART %u-----\n"; - const MULTIPART_LAST_MESSAGE_END = "-----END PGP MESSAGE, PART %u-----\n"; + const MULTIPART_LAST_MESSAGE_END = "-----END PGP MESSAGE, PART %u-----\n"; const PUBLIC_KEY_BLOCK_BEGIN = "-----BEGIN PGP PUBLIC KEY BLOCK-----\n"; - const PUBLIC_KEY_BLOCK_END = "-----END PGP PUBLIC KEY BLOCK-----\n"; + const PUBLIC_KEY_BLOCK_END = "-----END PGP PUBLIC KEY BLOCK-----\n"; const PRIVATE_KEY_BLOCK_BEGIN = "-----BEGIN PGP PRIVATE KEY BLOCK-----\n"; - const PRIVATE_KEY_BLOCK_END = "-----END PGP PRIVATE KEY BLOCK-----\n"; + const PRIVATE_KEY_BLOCK_END = "-----END PGP PRIVATE KEY BLOCK-----\n"; const SIGNATURE_BEGIN = "-----BEGIN PGP SIGNATURE-----\n"; - const SIGNATURE_END = "-----END PGP SIGNATURE-----\n"; + const SIGNATURE_END = "-----END PGP SIGNATURE-----\n"; - const DASH_PATTERN = '/^- /m'; - const EMPTY_PATTERN = '/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/'; + const DASH_PATTERN = "/^- /m"; + const EMPTY_PATTERN = '/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/'; const HEADER_PATTERN = '/^([^\s:]|[^\s:][^:]*[^\s:]): .+$/'; - const SPLIT_PATTERN = '/^-----[^-]+-----$/'; + const SPLIT_PATTERN = '/^-----[^-]+-----$/'; const TRUNK_SIZE = 76; @@ -61,10 +61,9 @@ final class Armor public function __construct( private ArmorType $type, private array $headers = [], - private string $data = '', - private string $text = '', - ) - { + private string $data = "", + private string $text = "" + ) { } /** @@ -132,11 +131,11 @@ public function assert(ArmorType $type): self * @return self */ public static function decode( - string $armoredText, bool $checksumRequired = false - ): self - { + string $armoredText, + bool $checksumRequired = false + ): self { $textDone = false; - $checksum = ''; + $checksum = ""; $type = null; $headers = []; @@ -150,31 +149,29 @@ public static function decode( $line = rtrim($line, Helper::SPACES); if ($type === null && preg_match(self::SPLIT_PATTERN, $line)) { $type = ArmorType::fromBegin($line); - } - else { + } else { if (preg_match(self::HEADER_PATTERN, $line)) { $headers[] = $line; - } - elseif (!$textDone && $type === ArmorType::SignedMessage) { + } elseif ( + !$textDone && + $type === ArmorType::SignedMessage + ) { if (!preg_match(self::SPLIT_PATTERN, $line)) { $textLines[] = $line; - } - else { + } else { $textDone = true; /// Remove first empty line (not included in the message digest) if (isset($textLines[0]) && empty($textLines[0])) { unset($textLines[0]); } } - } - elseif (!preg_match(self::SPLIT_PATTERN, $line)) { + } elseif (!preg_match(self::SPLIT_PATTERN, $line)) { if (preg_match(self::EMPTY_PATTERN, $line)) { continue; } - if (strpos($line, '=') === 0) { + if (strpos($line, "=") === 0) { $checksum = substr($line, 1); - } - else { + } else { $dataLines[] = $line; } } @@ -183,12 +180,11 @@ public static function decode( } $data = Strings::base64_decode(implode($dataLines)); - if (strcmp($checksum, self::crc24Checksum($data)) !== 0 && - (!empty($checksum) || $checksumRequired) + if ( + strcmp($checksum, self::crc24Checksum($data)) !== 0 && + (!empty($checksum) || $checksumRequired) ) { - throw new \RuntimeException( - 'Ascii armor integrity check failed!' - ); + throw new \RuntimeException("Ascii armor integrity check failed!"); } return new self( @@ -196,8 +192,10 @@ public static function decode( $headers, $data, preg_replace( - self::DASH_PATTERN, '', implode(Helper::CRLF, $textLines) - ), // Reverse dash-escaped text + self::DASH_PATTERN, + "", + implode(Helper::CRLF, $textLines) + ) // Reverse dash-escaped text ); } @@ -216,67 +214,109 @@ public static function decode( public static function encode( ArmorType $type, string $data, - string $text = '', + string $text = "", array $hashAlgos = [], int $partIndex = 0, int $partTotal = 0, - string $customComment = '', - ): string - { - $result = match($type) { + string $customComment = "" + ): string { + $result = match ($type) { ArmorType::MultipartSection => [ - sprintf(self::MULTIPART_SECTION_MESSAGE_BEGIN, $partIndex, $partTotal), + sprintf( + self::MULTIPART_SECTION_MESSAGE_BEGIN, + $partIndex, + $partTotal + ), self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, - sprintf(self::MULTIPART_SECTION_MESSAGE_END, $partIndex, $partTotal), + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, + sprintf( + self::MULTIPART_SECTION_MESSAGE_END, + $partIndex, + $partTotal + ), ], ArmorType::MultipartLast => [ sprintf(self::MULTIPART_LAST_MESSAGE_BEGIN, $partIndex), self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, sprintf(self::MULTIPART_LAST_MESSAGE_END, $partIndex), ], ArmorType::SignedMessage => [ self::SIGNED_MESSAGE_BEGIN, - !empty($hashAlgos) ? implode( - Helper::EOL, - array_map(static fn ($hashAlgo) => "Hash: $hashAlgo", $hashAlgos) - ) . Helper::EOL . Helper::EOL : Helper::EOL, - preg_replace(self::DASH_PATTERN, '- - ', $text) . Helper::EOL, // Dash-escape text + !empty($hashAlgos) + ? implode( + Helper::EOL, + array_map( + static fn($hashAlgo) => "Hash: $hashAlgo", + $hashAlgos + ) + ) . + Helper::EOL . + Helper::EOL + : Helper::EOL, + preg_replace(self::DASH_PATTERN, "- - ", $text) . Helper::EOL, // Dash-escape text self::SIGNATURE_BEGIN, self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, self::SIGNATURE_END, ], ArmorType::Message => [ self::MESSAGE_BEGIN, self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, self::MESSAGE_END, ], ArmorType::PublicKey => [ self::PUBLIC_KEY_BLOCK_BEGIN, self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, self::PUBLIC_KEY_BLOCK_END, ], ArmorType::PrivateKey => [ self::PRIVATE_KEY_BLOCK_BEGIN, self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, self::PRIVATE_KEY_BLOCK_END, ], ArmorType::Signature => [ self::SIGNATURE_BEGIN, self::addHeader($customComment) . Helper::EOL, - chunk_split(Strings::base64_encode($data), self::TRUNK_SIZE, Helper::EOL), - '=' . self::crc24Checksum($data) . Helper::EOL, + chunk_split( + Strings::base64_encode($data), + self::TRUNK_SIZE, + Helper::EOL + ), + "=" . self::crc24Checksum($data) . Helper::EOL, self::SIGNATURE_END, ], }; @@ -289,14 +329,14 @@ public static function encode( * @param string $customComment * @return string */ - private static function addHeader(string $customComment = ''): string + private static function addHeader(string $customComment = ""): string { $headers = [ - 'Version: ' . Config::VERSION . Helper::EOL, - 'Comment: ' . Config::COMMENT . Helper::EOL, + "Version: " . Config::VERSION . Helper::EOL, + "Comment: " . Config::COMMENT . Helper::EOL, ]; if (!empty($customComment)) { - $headers[] = 'Comment: ' . $customComment . Helper::EOL; + $headers[] = "Comment: " . $customComment . Helper::EOL; } return implode($headers); } @@ -319,8 +359,6 @@ private static function crc24Checksum(string $data): string } } } - return Strings::base64_encode( - substr(pack('N', $crc & 0xffffff), 1) - ); + return Strings::base64_encode(substr(pack("N", $crc & 0xffffff), 1)); } } diff --git a/src/Common/Config.php b/src/Common/Config.php index 17ba5c7f..23dd32d8 100644 --- a/src/Common/Config.php +++ b/src/Common/Config.php @@ -12,12 +12,9 @@ AeadAlgorithm, CompressionAlgorithm, HashAlgorithm, - SymmetricAlgorithm, -}; -use Psr\Log\{ - LoggerInterface, - NullLogger, + SymmetricAlgorithm }; +use Psr\Log\{LoggerInterface, NullLogger}; /** * Config class @@ -28,18 +25,18 @@ */ final class Config { - const VERSION = 'PHP Privacy v2'; - const COMMENT = 'https://github.com/web-of-trust/php-privacy'; + const VERSION = "PHP Privacy v2"; + const COMMENT = "https://github.com/web-of-trust/php-privacy"; - const CIPHER_MODE = 'cfb'; - const HKDF_ALGO = 'sha256'; + const CIPHER_MODE = "cfb"; + const HKDF_ALGO = "sha256"; const PADDING_MIN = 16; const PADDING_MAX = 32; - const SALT_NOTATION = 'salt@openpgp.org'; + const SALT_NOTATION = "salt@openpgp.org"; - const AEAD_SUPPORTED = true; + const AEAD_SUPPORTED = true; const AEAD_CHUNK_SIZE_MIN = 10; const AEAD_CHUNK_SIZE_MAX = 16; @@ -107,8 +104,7 @@ public static function getPreferredSymmetric(): SymmetricAlgorithm */ public static function setPreferredSymmetric( SymmetricAlgorithm $symmetric - ): void - { + ): void { Helper::assertSymmetric($symmetric); self::$preferredSymmetric = $symmetric; } @@ -130,8 +126,7 @@ public static function getPreferredCompression(): CompressionAlgorithm */ public static function setPreferredCompression( CompressionAlgorithm $compression - ): void - { + ): void { self::$preferredCompression = $compression; } @@ -150,9 +145,7 @@ public static function getPreferredAead(): AeadAlgorithm * * @param AeadAlgorithm $algo */ - public static function setPreferredAead( - AeadAlgorithm $algo - ): void + public static function setPreferredAead(AeadAlgorithm $algo): void { self::$preferredAead = $algo; } @@ -255,8 +248,9 @@ public static function getArgon2MemoryExponent(): int * * @param int $argon2MemoryExponent */ - public static function setArgon2MemoryExponent(int $argon2MemoryExponent): void - { + public static function setArgon2MemoryExponent( + int $argon2MemoryExponent + ): void { self::$argon2MemoryExponent = $argon2MemoryExponent; } diff --git a/src/Common/GenericS2K.php b/src/Common/GenericS2K.php index 49ab4b05..8f7eec93 100644 --- a/src/Common/GenericS2K.php +++ b/src/Common/GenericS2K.php @@ -8,10 +8,7 @@ namespace OpenPGP\Common; -use OpenPGP\Enum\{ - HashAlgorithm, - S2kType, -}; +use OpenPGP\Enum\{HashAlgorithm, S2kType}; use OpenPGP\Type\S2KInterface; /** @@ -65,15 +62,14 @@ public function __construct( private readonly string $salt, private readonly S2kType $type = S2kType::Iterated, private readonly HashAlgorithm $hash = HashAlgorithm::Sha256, - private readonly int $itCount = self::DEFAULT_IT_COUNT, - ) - { + private readonly int $itCount = self::DEFAULT_IT_COUNT + ) { if ($type === S2kType::Argon2) { throw new \InvalidArgumentException( - "S2k type {$type->name} is invalid argument.", + "S2k type {$type->name} is invalid argument." ); } - $this->count = (16 + ($itCount & 15)) << (($itCount >> 4) + self::EXPBIAS); + $this->count = 16 + ($itCount & 15) << ($itCount >> 4) + self::EXPBIAS; } /** @@ -81,11 +77,11 @@ public function __construct( */ public function toBytes(): string { - return match($this->type) { + return match ($this->type) { S2kType::Simple => implode([ chr($this->type->value), - chr($this->hash->value)], - ), + chr($this->hash->value), + ]), S2kType::Salted => implode([ chr($this->type->value), chr($this->hash->value), @@ -97,32 +93,25 @@ public function toBytes(): string $this->salt, chr($this->itCount), ]), - S2kType::GNU => implode([ - chr($this->type->value), - 'GNU', - "\x01", - ]), - default => '', + S2kType::GNU => implode([chr($this->type->value), "GNU", "\x01"]), + default => "", }; } /** * {@inheritdoc} */ - public function produceKey( - string $passphrase, int $length - ): string + public function produceKey(string $passphrase, int $length): string { - return match($this->type) { + return match ($this->type) { S2kType::Simple => $this->hash($passphrase, $length), - S2kType::Salted => $this->hash( - $this->salt . $passphrase, $length - ), + S2kType::Salted => $this->hash($this->salt . $passphrase, $length), S2kType::Iterated => $this->hash( - $this->iterate($this->salt . $passphrase), $length + $this->iterate($this->salt . $passphrase), + $length ), S2kType::GNU => $this->hash($passphrase, $length), - default => '', + default => "", }; } @@ -159,21 +148,25 @@ public static function fromBytes(string $bytes): self $salt = match ($type) { S2kType::Salted, S2kType::Iterated => substr( - $bytes, 2, self::SALT_LENGTH + $bytes, + 2, + self::SALT_LENGTH ), - default => '', + default => "", }; - $itCount = $type === S2kType::Iterated ? - ord($bytes[self::SALT_LENGTH + 2]) : 0; + $itCount = + $type === S2kType::Iterated + ? ord($bytes[self::SALT_LENGTH + 2]) + : 0; return new self($salt, $type, $hash, $itCount); } private function iterate(string $data): string { - if (strlen($data) >= $this->count) return $data; - $data = str_repeat( - $data, (int) ceil($this->count / strlen($data)) - ); + if (strlen($data) >= $this->count) { + return $data; + } + $data = str_repeat($data, (int) ceil($this->count / strlen($data))); return substr($data, 0, $this->count); } diff --git a/src/Common/Helper.php b/src/Common/Helper.php index aa05e595..b4136c22 100644 --- a/src/Common/Helper.php +++ b/src/Common/Helper.php @@ -8,11 +8,7 @@ namespace OpenPGP\Common; -use OpenPGP\Enum\{ - HashAlgorithm, - S2kType, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{HashAlgorithm, S2kType, SymmetricAlgorithm}; use OpenPGP\Type\S2KInterface; use phpseclib3\Crypt\Random; use phpseclib3\Math\BigInteger; @@ -64,7 +60,7 @@ public static function bin2BigInt(string $bytes): BigInteger */ public static function bit2ByteLength(int $bitLength): int { - return ($bitLength + 7) >> 3; + return $bitLength + 7 >> 3; } /** @@ -75,8 +71,7 @@ public static function bit2ByteLength(int $bitLength): int */ public static function generatePrefix( SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes256 - ): string - { + ): string { $size = $symmetric->blockSize(); $prefix = Random::string($size); $repeat = $prefix[$size - 2] . $prefix[$size - 1]; @@ -92,12 +87,11 @@ public static function generatePrefix( * @return int */ public static function bytesToLong( - string $bytes, int $offset = 0, bool $be = true - ): int - { - $unpacked = unpack( - $be ? 'N' : 'V', substr($bytes, $offset, 4) - ); + string $bytes, + int $offset = 0, + bool $be = true + ): int { + $unpacked = unpack($be ? "N" : "V", substr($bytes, $offset, 4)); return (int) array_pop($unpacked); } @@ -110,12 +104,11 @@ public static function bytesToLong( * @return int */ public static function bytesToShort( - string $bytes, int $offset = 0, bool $be = true - ): int - { - $unpacked = unpack( - $be ? 'n' : 'v', substr($bytes, $offset, 2) - ); + string $bytes, + int $offset = 0, + bool $be = true + ): int { + $unpacked = unpack($be ? "n" : "v", substr($bytes, $offset, 2)); return (int) array_pop($unpacked); } @@ -127,19 +120,19 @@ public static function bytesToShort( */ public static function stringToKey( S2kType $type = S2kType::Iterated - ): S2KInterface - { - return $type === S2kType::Argon2 ? - new Argon2S2K( + ): S2KInterface { + return $type === S2kType::Argon2 + ? new Argon2S2K( self::generatePassword(Argon2S2K::SALT_LENGTH), Config::getArgon2Iteration(), Config::getArgon2Parallelism(), - Config::getArgon2MemoryExponent(), - ) : new GenericS2K( + Config::getArgon2MemoryExponent() + ) + : new GenericS2K( Random::string(GenericS2K::SALT_LENGTH), $type, Config::getPreferredHash(), - Config::getS2kItCount(), + Config::getS2kItCount() ); } @@ -151,11 +144,10 @@ public static function stringToKey( */ public static function computeChecksum(string $text): string { - $sum = array_sum(array_map( - static fn ($char) => ord($char), - str_split($text), - )); - return pack('n', $sum & 0xffff); + $sum = array_sum( + array_map(static fn($char) => ord($char), str_split($text)) + ); + return pack("n", $sum & 0xffff); } /** @@ -164,12 +156,12 @@ public static function computeChecksum(string $text): string * @param int $length * @return string */ - public static function generatePassword(int $length = 32): string + public static function generatePassword(int $length = 32): string { return preg_replace_callback( - '/\*/u', - static fn () => chr(random_int(40, 126)), - str_repeat('*', $length), + "/\*/u", + static fn() => chr(random_int(40, 126)), + str_repeat("*", $length) ); } @@ -183,8 +175,8 @@ public static function removeTrailingSpaces(string $text): string { $lines = explode(self::EOL, $text); $lines = array_map( - static fn ($line) => rtrim($line, self::SPACES), - $lines, + static fn($line) => rtrim($line, self::SPACES), + $lines ); return implode(self::EOL, $lines); } @@ -199,15 +191,13 @@ public static function simpleLength(int $length): string { if ($length < 192) { return chr($length); - } - elseif ($length < 8384) { + } elseif ($length < 8384) { return implode([ - chr(((($length - 192) >> 8) & 0xff) + 192), - chr(($length - 192) & 0xff), + chr((($length - 192 >> 8) & 0xff) + 192), + chr(($length - 192) & 0xff), ]); - } - else { - return implode(["\xff", pack('N', $length)]); + } else { + return implode(["\xff", pack("N", $length)]); } } @@ -225,7 +215,7 @@ public static function assertHash(HashAlgorithm $hash): void case HashAlgorithm::Sha1: case HashAlgorithm::Ripemd160: throw new \RuntimeException( - "Hash {$hash->name} is unsupported.", + "Hash {$hash->name} is unsupported." ); } } @@ -244,7 +234,7 @@ public static function assertSymmetric(SymmetricAlgorithm $symmetric): void case SymmetricAlgorithm::TripleDes: case SymmetricAlgorithm::Cast5: throw new \RuntimeException( - "Symmetric {$symmetric->name} is unsupported.", + "Symmetric {$symmetric->name} is unsupported." ); } } diff --git a/src/Cryptor/Aead/AeadCipher.php b/src/Cryptor/Aead/AeadCipher.php index be99bae8..a945c147 100644 --- a/src/Cryptor/Aead/AeadCipher.php +++ b/src/Cryptor/Aead/AeadCipher.php @@ -26,7 +26,9 @@ interface AeadCipher * @return string The cipher text output. */ function encrypt( - string $plainText, string $nonce, string $aData = '' + string $plainText, + string $nonce, + string $aData = "" ): string; /** @@ -38,7 +40,9 @@ function encrypt( * @return string The plain text output. */ function decrypt( - string $cipherText, string $nonce, string $aData = '' + string $cipherText, + string $nonce, + string $aData = "" ): string; /** diff --git a/src/Cryptor/Aead/EAX.php b/src/Cryptor/Aead/EAX.php index 49261684..f39e736a 100644 --- a/src/Cryptor/Aead/EAX.php +++ b/src/Cryptor/Aead/EAX.php @@ -34,7 +34,7 @@ final class EAX implements AeadCipher const H_TAG = "\x01"; const C_TAG = "\x02"; - const CIPHER_MODE = 'ctr'; + const CIPHER_MODE = "ctr"; private readonly BlockCipher $cipher; private readonly CMac $mac; @@ -52,26 +52,26 @@ final class EAX implements AeadCipher */ public function __construct( private readonly string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ) - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ) { $this->cipher = $symmetric->cipherEngine(self::CIPHER_MODE); $this->cipher->setKey($key); $this->mac = new CMac($symmetric); $size = $this->mac->getMacSize(); $this->zeroBlock = str_repeat(self::N_TAG, $size); - $this->oneBlock = str_repeat(self::N_TAG, $size - 1) . self::H_TAG; - $this->twoBlock = str_repeat(self::N_TAG, $size - 1) . self::C_TAG; + $this->oneBlock = str_repeat(self::N_TAG, $size - 1) . self::H_TAG; + $this->twoBlock = str_repeat(self::N_TAG, $size - 1) . self::C_TAG; } /** * {@inheritdoc} */ public function encrypt( - string $plainText, string $nonce, string $aData = '' - ): string - { + string $plainText, + string $nonce, + string $aData = "" + ): string { $omacNonce = $this->omac($this->zeroBlock, $nonce); $omacAdata = $this->omac($this->oneBlock, $aData); @@ -86,14 +86,15 @@ public function encrypt( * {@inheritdoc} */ public function decrypt( - string $cipherText, string $nonce, string $aData = '' - ): string - { + string $cipherText, + string $nonce, + string $aData = "" + ): string { $length = strlen($cipherText); $tagLength = $this->mac->getMacSize(); if ($length < $tagLength) { - throw new \LengthException('Invalid EAX cipher text.'); + throw new \LengthException("Invalid EAX cipher text."); } $ciphered = substr($cipherText, 0, $length - $tagLength); $ctTag = substr($cipherText, $length - $tagLength); @@ -104,7 +105,7 @@ public function decrypt( $tag = $omacCiphered ^ $omacAdata ^ $omacNonce; if (strcmp($ctTag, $tag) !== 0) { - throw new \RuntimeException('Authentication tag mismatch!'); + throw new \RuntimeException("Authentication tag mismatch!"); } return $this->crypt($ciphered, $omacNonce); @@ -120,9 +121,7 @@ public function getNonce(string $iv, string $chunkIndex): string private function omac(string $tag, string $message): string { - return $this->mac->generate( - implode([$tag, $message]), $this->key - ); + return $this->mac->generate(implode([$tag, $message]), $this->key); } private function crypt(string $text, string $iv): string diff --git a/src/Cryptor/Aead/GCM.php b/src/Cryptor/Aead/GCM.php index 81cfe12c..fd8296a5 100644 --- a/src/Cryptor/Aead/GCM.php +++ b/src/Cryptor/Aead/GCM.php @@ -21,8 +21,8 @@ */ final class GCM implements AeadCipher { - const CIPHER_MODE = 'gcm'; - const TAG_LENGTH = 16; + const CIPHER_MODE = "gcm"; + const TAG_LENGTH = 16; private readonly BlockCipher $cipher; @@ -35,9 +35,8 @@ final class GCM implements AeadCipher */ public function __construct( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ) - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ) { $this->cipher = $symmetric->cipherEngine(self::CIPHER_MODE); $this->cipher->setKey($key); } @@ -46,9 +45,10 @@ public function __construct( * {@inheritdoc} */ public function encrypt( - string $plainText, string $nonce, string $aData = '' - ): string - { + string $plainText, + string $nonce, + string $aData = "" + ): string { return implode([ $this->crypt($plainText, $nonce, $aData), $this->cipher->getTag(), @@ -59,18 +59,19 @@ public function encrypt( * {@inheritdoc} */ public function decrypt( - string $cipherText, string $nonce, string $aData = '' - ): string - { + string $cipherText, + string $nonce, + string $aData = "" + ): string { $length = strlen($cipherText); if ($length < self::TAG_LENGTH) { - throw new \LengthException('Invalid GCM cipher text.'); + throw new \LengthException("Invalid GCM cipher text."); } - $this->cipher->setTag( - substr($cipherText, $length - self::TAG_LENGTH) - ); + $this->cipher->setTag(substr($cipherText, $length - self::TAG_LENGTH)); return $this->crypt( - substr($cipherText, 0, $length - self::TAG_LENGTH), $nonce, $aData + substr($cipherText, 0, $length - self::TAG_LENGTH), + $nonce, + $aData ); } @@ -83,9 +84,10 @@ public function getNonce(string $iv, string $chunkIndex): string } private function crypt( - string $text, string $nonce, string $aData = '' - ): string - { + string $text, + string $nonce, + string $aData = "" + ): string { $this->cipher->setNonce($nonce); $this->cipher->setAAD($aData); return $this->cipher->encrypt($text); diff --git a/src/Cryptor/Aead/OCB.php b/src/Cryptor/Aead/OCB.php index f4a7ec1c..4208ed9f 100644 --- a/src/Cryptor/Aead/OCB.php +++ b/src/Cryptor/Aead/OCB.php @@ -25,16 +25,16 @@ */ final class OCB implements AeadCipher { - const ZERO_CHAR = "\x00"; - const ONE_CHAR = "\x01"; - const ZERO_BLOCK = "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0"; + const ZERO_CHAR = "\x00"; + const ONE_CHAR = "\x01"; + const ZERO_BLOCK = "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0"; - const BLOCK_LENGTH = 16; - const IV_LENGTH = 15; - const TAG_LENGTH = 16; + const BLOCK_LENGTH = 16; + const IV_LENGTH = 15; + const TAG_LENGTH = 16; - const MASK_ASTERISK = 'x'; - const MASK_DOLLAR = '$'; + const MASK_ASTERISK = "x"; + const MASK_DOLLAR = '$'; private readonly EcbCipher $encipher; @@ -53,12 +53,11 @@ final class OCB implements AeadCipher */ public function __construct( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ) - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ) { if ($symmetric->blockSize() !== self::BLOCK_LENGTH) { throw new \InvalidArgumentException( - 'Cipher must have a block size of ' . self::BLOCK_LENGTH . '.' + "Cipher must have a block size of " . self::BLOCK_LENGTH . "." ); } $this->encipher = $symmetric->ecbCipherEngine(); @@ -80,9 +79,10 @@ public function __construct( * {@inheritdoc} */ public function encrypt( - string $plainText, string $nonce, string $aData = '' - ): string - { + string $plainText, + string $nonce, + string $aData = "" + ): string { return $this->crypt($this->encipher, $plainText, $nonce, $aData); } @@ -90,12 +90,13 @@ public function encrypt( * {@inheritdoc} */ public function decrypt( - string $cipherText, string $nonce, string $aData = '' - ): string - { + string $cipherText, + string $nonce, + string $aData = "" + ): string { $length = strlen($cipherText); if ($length < self::TAG_LENGTH) { - throw new \LengthException('Invalid OCB cipher text.'); + throw new \LengthException("Invalid OCB cipher text."); } $tag = substr($cipherText, $length - self::TAG_LENGTH); @@ -107,7 +108,7 @@ public function decrypt( if (strcmp($tag, substr($crypted, $length - self::TAG_LENGTH)) === 0) { return substr($crypted, 0, $length - self::TAG_LENGTH); } - throw new \RuntimeException('Authentication tag mismatch!'); + throw new \RuntimeException("Authentication tag mismatch!"); } /** @@ -128,9 +129,11 @@ public function getNonce(string $iv, string $chunkIndex): string * @return string The ciphertext or plaintext output, with tag appended in both cases. */ private function crypt( - EcbCipher $cipher, string $text, string $nonce, string $aData - ): string - { + EcbCipher $cipher, + string $text, + string $nonce, + string $aData + ): string { $length = strlen($text); // Consider P as a sequence of 128-bit blocks $m = floor($length / self::BLOCK_LENGTH) | 0; @@ -160,10 +163,13 @@ private function crypt( self::xor(substr($kTop, 0, 8), substr($kTop, 1, 9)), ]); // Offset_0 = Stretch[1+bottom..128+bottom] - $offset = substr(self::shiftRight( - substr($stretched, 0 + ($bottom >> 3), 17 + ($bottom >> 3)), - 8 - ($bottom & 7), - ), 1); + $offset = substr( + self::shiftRight( + substr($stretched, 0 + ($bottom >> 3), 17 + ($bottom >> 3)), + 8 - ($bottom & 7) + ), + 1 + ); // Checksum_0 = zeros(128) $checksum = self::ZERO_BLOCK; @@ -179,23 +185,20 @@ private function crypt( // P_i = Offset_i xor DECIPHER(K, C_i xor Offset_i) if ($cipher === $this->encipher) { $encrypted = self::xor( - $cipher->encryptBlock(self::xor($offset, $text)), $offset + $cipher->encryptBlock(self::xor($offset, $text)), + $offset ); - } - else { + } else { $encrypted = self::xor( - $cipher->decryptBlock(self::xor($offset, $text)), $offset + $cipher->decryptBlock(self::xor($offset, $text)), + $offset ); } - $ct = substr_replace( - $ct, - $encrypted, - $pos, - strlen($encrypted), - ); + $ct = substr_replace($ct, $encrypted, $pos, strlen($encrypted)); // Checksum_i = Checksum_{i-1} xor P_i $checksum = self::xor( - $checksum, $cipher === $this->encipher ? $text : substr($ct, $pos) + $checksum, + $cipher === $this->encipher ? $text : substr($ct, $pos) ); $text = substr($text, self::BLOCK_LENGTH); @@ -211,21 +214,18 @@ private function crypt( $padding = $this->encipher->encryptBlock($offset); // C_* = P_* xor Pad[1..bitlen(P_*)] $paddedText = self::xor($text, $padding); - $ct = substr_replace( - $ct, - $paddedText, - $pos, - strlen($paddedText), - ); + $ct = substr_replace($ct, $paddedText, $pos, strlen($paddedText)); // Checksum_* = Checksum_m xor (P_* || 1 || new Uint8Array(127-bitlen(P_*))) - $input = $cipher === $this->encipher ? - $text : substr($ct, $pos, strlen($ct) - self::TAG_LENGTH); + $input = + $cipher === $this->encipher + ? $text + : substr($ct, $pos, strlen($ct) - self::TAG_LENGTH); $xorInput = substr_replace( self::ZERO_BLOCK, $input, 0, - strlen($input), + strlen($input) ); $xorInput[$length] = "\x80"; $checksum = self::xor($checksum, $xorInput); @@ -236,7 +236,7 @@ private function crypt( $this->encipher->encryptBlock( self::xor( self::xor($checksum, $offset), - $this->mask[self::MASK_DOLLAR], + $this->mask[self::MASK_DOLLAR] ) ), self::hash($aData) @@ -249,11 +249,13 @@ private function crypt( private function extendKeyVariables(string $text, string $aData): void { - $newMaxNtz = self::nbits( - floor(max(strlen($text), strlen($aData)) / self::BLOCK_LENGTH) | 0 - ) - 1; + $newMaxNtz = + self::nbits( + floor(max(strlen($text), strlen($aData)) / self::BLOCK_LENGTH) | + 0 + ) - 1; for ($i = $this->maxNtz + 1; $i <= $newMaxNtz; $i++) { - $this->mask[$i] = self::double($this->mask[$i - 1]); + $this->mask[$i] = self::double($this->mask[$i - 1]); } $this->maxNtz = $newMaxNtz; } @@ -273,7 +275,7 @@ private function hash(string $aData): string $offset = self::xor($offset, $this->mask[self::ntz($i + 1)]); $sum = self::xor( $sum, - $this->encipher->encryptBlock(self::xor($offset, $aData)), + $this->encipher->encryptBlock(self::xor($offset, $aData)) ); $aData = substr($aData, self::BLOCK_LENGTH); } @@ -284,14 +286,15 @@ private function hash(string $aData): string $offset = self::xor($offset, $this->mask[self::MASK_ASTERISK]); $cipherInput = substr_replace( - self::ZERO_BLOCK, $aData, 0, strlen($aData) + self::ZERO_BLOCK, + $aData, + 0, + strlen($aData) ); $cipherInput[$length] = "\x80"; $cipherInput = self::xor($cipherInput, $offset); - $sum = self::xor( - $sum, $this->encipher->encryptBlock($cipherInput) - ); + $sum = self::xor($sum, $this->encipher->encryptBlock($cipherInput)); } return $sum; @@ -384,7 +387,7 @@ private static function shiftRight(string $data, int $bits): string $data[$i] = chr(ord($data[$i]) >> $bits); if ($i > 0) { $data[$i] = chr( - ord($data[$i]) | (ord($data[$i - 1]) << (8 - $bits)) + ord($data[$i]) | (ord($data[$i - 1]) << 8 - $bits) ); } } diff --git a/src/Cryptor/Asymmetric/ElGamal.php b/src/Cryptor/Asymmetric/ElGamal.php index c2820ab8..010091db 100644 --- a/src/Cryptor/Asymmetric/ElGamal.php +++ b/src/Cryptor/Asymmetric/ElGamal.php @@ -23,7 +23,7 @@ abstract class ElGamal extends AsymmetricKey /** * Algorithm Name */ - const ALGORITHM = 'ElGamal'; + const ALGORITHM = "ElGamal"; private readonly int $bitSize; @@ -38,15 +38,13 @@ abstract class ElGamal extends AsymmetricKey public function __construct( private readonly BigInteger $y, private readonly BigInteger $prime, - private readonly BigInteger $generator, - ) - { + private readonly BigInteger $generator + ) { $this->bitSize = $prime->getLength(); } /** * Create public / private key pair. - * * Return the private key, from which the publickey can be extracted * * @param int $lSize @@ -54,9 +52,9 @@ public function __construct( * @return ElGamal\PrivateKey */ public static function createKey( - int $lSize = 2048, int $nSize = 224 - ): ElGamal\PrivateKey - { + int $lSize = 2048, + int $nSize = 224 + ): ElGamal\PrivateKey { $one = new BigInteger(1); $two = new BigInteger(2); $q = BigInteger::randomPrime($nSize); diff --git a/src/Cryptor/Asymmetric/ElGamal/PrivateKey.php b/src/Cryptor/Asymmetric/ElGamal/PrivateKey.php index 70a49d6f..a294beac 100644 --- a/src/Cryptor/Asymmetric/ElGamal/PrivateKey.php +++ b/src/Cryptor/Asymmetric/ElGamal/PrivateKey.php @@ -8,9 +8,9 @@ namespace OpenPGP\Cryptor\Asymmetric\ElGamal; -use phpseclib3\Math\BigInteger; use OpenPGP\Common\Helper; use OpenPGP\Cryptor\Asymmetric\ElGamal; +use phpseclib3\Math\BigInteger; /** * ElGamal private key class @@ -34,9 +34,8 @@ public function __construct( private readonly BigInteger $x, BigInteger $y, BigInteger $prime, - BigInteger $generator, - ) - { + BigInteger $generator + ) { parent::__construct($y, $prime, $generator); } @@ -56,7 +55,9 @@ public function getX(): BigInteger public function getPublicKey(): PublicKey { return new PublicKey( - $this->getY(), $this->getPrime(), $this->getGenerator() + $this->getY(), + $this->getPrime(), + $this->getGenerator() ); } @@ -72,7 +73,7 @@ public function decrypt(string $cipherText): string $length = strlen($cipherText); if ($length > $inputSize) { throw new \RuntimeException( - 'Cipher text too large for ' . self::ALGORITHM . ' cipher.' + "Cipher text too large for " . self::ALGORITHM . " cipher." ); } @@ -81,14 +82,13 @@ public function decrypt(string $cipherText): string $gamma = Helper::bin2BigInt( substr($cipherText, 0, (int) ($length / 2)) ); - $phi = Helper::bin2BigInt( - substr($cipherText, (int) ($length / 2)) - ); - list(, $m) = $gamma->modPow( - $prime->subtract($one->add($this->getX())), $prime - )->multiply($phi)->divide($prime); + $phi = Helper::bin2BigInt(substr($cipherText, (int) ($length / 2))); + list(, $m) = $gamma + ->modPow($prime->subtract($one->add($this->getX())), $prime) + ->multiply($phi) + ->divide($prime); - $outputSize = ($this->getBitSize() - 1) >> 3; + $outputSize = $this->getBitSize() - 1 >> 3; return substr($m->toBytes(), 0, $outputSize); } @@ -102,13 +102,13 @@ public function decrypt(string $cipherText): string public function toString($type, array $options = []): string { return implode([ - pack('n', $this->getPrime()->getLength()), + pack("n", $this->getPrime()->getLength()), $this->getPrime()->toBytes(), - pack('n', $this->getGenerator()->getLength()), + pack("n", $this->getGenerator()->getLength()), $this->getGenerator()->toBytes(), - pack('n', $this->getX()->getLength()), + pack("n", $this->getX()->getLength()), $this->getX()->toBytes(), - pack('n', $this->getY()->getLength()), + pack("n", $this->getY()->getLength()), $this->getY()->toBytes(), ]); } diff --git a/src/Cryptor/Asymmetric/ElGamal/PublicKey.php b/src/Cryptor/Asymmetric/ElGamal/PublicKey.php index 23dd8486..9cdd1405 100644 --- a/src/Cryptor/Asymmetric/ElGamal/PublicKey.php +++ b/src/Cryptor/Asymmetric/ElGamal/PublicKey.php @@ -8,9 +8,9 @@ namespace OpenPGP\Cryptor\Asymmetric\ElGamal; -use phpseclib3\Math\BigInteger; use OpenPGP\Common\Helper; use OpenPGP\Cryptor\Asymmetric\ElGamal; +use phpseclib3\Math\BigInteger; /** * ElGamal public key class @@ -33,7 +33,7 @@ public function encrypt(string $plainText): string $input = Helper::bin2BigInt($plainText); if ($input->compare($prime) > 0) { throw new \InvalidArgumentException( - 'Plain text too large for ' . self::ALGORITHM . ' cipher.' + "Plain text too large for " . self::ALGORITHM . " cipher." ); } @@ -42,9 +42,9 @@ public function encrypt(string $plainText): string do { $k = BigInteger::randomRange($one, $prime->subtract($one)); $gamma = $this->getGenerator()->modPow($k, $prime); - list(, $phi) = $input->multiply( - $this->getY()->modPow($k, $prime) - )->divide($prime); + list(, $phi) = $input + ->multiply($this->getY()->modPow($k, $prime)) + ->divide($prime); } while ( $gamma->getLengthInBytes() < $byteLength || $phi->getLengthInBytes() < $byteLength @@ -66,11 +66,11 @@ public function encrypt(string $plainText): string public function toString($type, array $options = []): string { return implode([ - pack('n', $this->getPrime()->getLength()), + pack("n", $this->getPrime()->getLength()), $this->getPrime()->toBytes(), - pack('n', $this->getGenerator()->getLength()), + pack("n", $this->getGenerator()->getLength()), $this->getGenerator()->toBytes(), - pack('n', $this->getY()->getLength()), + pack("n", $this->getY()->getLength()), $this->getY()->toBytes(), ]); } diff --git a/src/Cryptor/Mac/CMac.php b/src/Cryptor/Mac/CMac.php index b7361c23..2b30d61e 100644 --- a/src/Cryptor/Mac/CMac.php +++ b/src/Cryptor/Mac/CMac.php @@ -40,9 +40,8 @@ final class CMac */ public function __construct( SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - private int $macSize = 0, - ) - { + private int $macSize = 0 + ) { $this->cipher = $symmetric->ecbCipherEngine(); $this->blockSize = $symmetric->blockSize(); $this->zeroBlock = str_repeat(self::ZERO_CHAR, $this->blockSize); @@ -68,9 +67,9 @@ public function __construct( public function generate(string $data, string $key): string { $this->cipher->setKey($key); - $keys = $this->generateKeys(); + $keys = $this->generateKeys(); $mBlocks = $this->splitData($data, $keys); - $cBlock = $this->zeroBlock; + $cBlock = $this->zeroBlock; foreach ($mBlocks as $block) { $cBlock = $this->cipher->encryptBlock($cBlock ^ $block); } @@ -125,20 +124,20 @@ protected function getRValue(int $size): string 64 => str_repeat(self::ZERO_CHAR, 7) . "\x1B", 128 => str_repeat(self::ZERO_CHAR, 15) . "\x87", default => throw new \LengthException( - 'Unsupported block size for the cipher.' + "Unsupported block size for the cipher." ), }; } private function leftShift(string $data, int $bits): string { - $mask = (Bitwise::MASK_8BITS << (8 - $bits)) & Bitwise::MASK_8BITS; - $state = 0; - $result = ''; + $mask = (Bitwise::MASK_8BITS << 8 - $bits) & Bitwise::MASK_8BITS; + $state = 0; + $result = ""; for ($i = strlen($data) - 1; $i >= 0; $i--) { - $tmp = ord($data[$i]); + $tmp = ord($data[$i]); $result .= chr(($tmp << $bits) | $state); - $state = ($tmp & $mask) >> (8 - $bits); + $state = ($tmp & $mask) >> 8 - $bits; } return strrev($result); } @@ -155,17 +154,20 @@ private function splitData(string $data, array $keys): array $data = str_split($data, $this->blockSize); $last = end($data); if ($last === false) { - $last = ''; + $last = ""; } if (strlen($last) != $this->blockSize) { //Pad the last element - $last .= "\x80" . substr( - $this->zeroBlock, 0, $this->blockSize - 1 - strlen($last) - ); - $last = $last ^ $keys[1]; - } - else { - $last = $last ^ $keys[0]; + $last .= + "\x80" . + substr( + $this->zeroBlock, + 0, + $this->blockSize - 1 - strlen($last) + ); + $last = $last ^ $keys[1]; + } else { + $last = $last ^ $keys[0]; } $data[count($data) - 1] = $last; return $data; diff --git a/src/Cryptor/Math/Bitwise.php b/src/Cryptor/Math/Bitwise.php index b8df103c..a5b27c50 100644 --- a/src/Cryptor/Math/Bitwise.php +++ b/src/Cryptor/Math/Bitwise.php @@ -17,7 +17,7 @@ */ final class Bitwise { - const MASK_8BITS = 0xff; + const MASK_8BITS = 0xff; const MASK_16BITS = 0xffff; const MASK_32BITS = 0xffffffff; @@ -33,12 +33,12 @@ public static function leftRotate32(int $x, int $s): int public static function rightRotate(int $x, int $s): int { - return ($x >> $s) | ($x << (32 - $s)); + return ($x >> $s) | ($x << 32 - $s); } public static function leftRotate(int $x, int $s): int { - return ($x << $s) | ($x >> (32 - $s)); + return ($x << $s) | ($x >> 32 - $s); } public static function leftShift32(int $x, int $s): int diff --git a/src/Cryptor/Symmetric/CAST5.php b/src/Cryptor/Symmetric/CAST5.php index 0db450e5..a7332a03 100644 --- a/src/Cryptor/Symmetric/CAST5.php +++ b/src/Cryptor/Symmetric/CAST5.php @@ -8,10 +8,10 @@ namespace OpenPGP\Cryptor\Symmetric; -use phpseclib3\Crypt\Common\BlockCipher; -use phpseclib3\Exception\BadModeException; use OpenPGP\Common\Helper; use OpenPGP\Cryptor\Math\Bitwise; +use phpseclib3\Crypt\Common\BlockCipher; +use phpseclib3\Exception\BadModeException; /** * CAST5 cipher engine class. Ported from Bouncy Castle project. diff --git a/src/Cryptor/Symmetric/Camellia.php b/src/Cryptor/Symmetric/Camellia.php index 92826e8b..a67842d2 100644 --- a/src/Cryptor/Symmetric/Camellia.php +++ b/src/Cryptor/Symmetric/Camellia.php @@ -8,10 +8,10 @@ namespace OpenPGP\Cryptor\Symmetric; -use phpseclib3\Crypt\Common\BlockCipher; -use phpseclib3\Exception\BadModeException; use OpenPGP\Common\Helper; use OpenPGP\Cryptor\Math\Bitwise; +use phpseclib3\Crypt\Common\BlockCipher; +use phpseclib3\Exception\BadModeException; /** * Camellia cipher engine class. Ported from Bouncy Castle project. @@ -29,204 +29,1066 @@ class Camellia extends BlockCipher * @var array */ private static array $sigma = [ - 0xa09e667f, 0x3bcc908b, 0xb67ae858, 0x4caa73b2, 0xc6ef372f, 0xe94f82be, - 0x54ff53a5, 0xf1d36f1c, 0x10e527fa, 0xde682d1d, 0xb05688c2, 0xb3e6c1fd, + 0xa09e667f, + 0x3bcc908b, + 0xb67ae858, + 0x4caa73b2, + 0xc6ef372f, + 0xe94f82be, + 0x54ff53a5, + 0xf1d36f1c, + 0x10e527fa, + 0xde682d1d, + 0xb05688c2, + 0xb3e6c1fd, ]; /** * @var array */ private static array $sbox1_1110 = [ - 0x70707000, 0x82828200, 0x2c2c2c00, 0xececec00, 0xb3b3b300, 0x27272700, - 0xc0c0c000, 0xe5e5e500, 0xe4e4e400, 0x85858500, 0x57575700, 0x35353500, - 0xeaeaea00, 0x0c0c0c00, 0xaeaeae00, 0x41414100, 0x23232300, 0xefefef00, - 0x6b6b6b00, 0x93939300, 0x45454500, 0x19191900, 0xa5a5a500, 0x21212100, - 0xededed00, 0x0e0e0e00, 0x4f4f4f00, 0x4e4e4e00, 0x1d1d1d00, 0x65656500, - 0x92929200, 0xbdbdbd00, 0x86868600, 0xb8b8b800, 0xafafaf00, 0x8f8f8f00, - 0x7c7c7c00, 0xebebeb00, 0x1f1f1f00, 0xcecece00, 0x3e3e3e00, 0x30303000, - 0xdcdcdc00, 0x5f5f5f00, 0x5e5e5e00, 0xc5c5c500, 0x0b0b0b00, 0x1a1a1a00, - 0xa6a6a600, 0xe1e1e100, 0x39393900, 0xcacaca00, 0xd5d5d500, 0x47474700, - 0x5d5d5d00, 0x3d3d3d00, 0xd9d9d900, 0x01010100, 0x5a5a5a00, 0xd6d6d600, - 0x51515100, 0x56565600, 0x6c6c6c00, 0x4d4d4d00, 0x8b8b8b00, 0x0d0d0d00, - 0x9a9a9a00, 0x66666600, 0xfbfbfb00, 0xcccccc00, 0xb0b0b000, 0x2d2d2d00, - 0x74747400, 0x12121200, 0x2b2b2b00, 0x20202000, 0xf0f0f000, 0xb1b1b100, - 0x84848400, 0x99999900, 0xdfdfdf00, 0x4c4c4c00, 0xcbcbcb00, 0xc2c2c200, - 0x34343400, 0x7e7e7e00, 0x76767600, 0x05050500, 0x6d6d6d00, 0xb7b7b700, - 0xa9a9a900, 0x31313100, 0xd1d1d100, 0x17171700, 0x04040400, 0xd7d7d700, - 0x14141400, 0x58585800, 0x3a3a3a00, 0x61616100, 0xdedede00, 0x1b1b1b00, - 0x11111100, 0x1c1c1c00, 0x32323200, 0x0f0f0f00, 0x9c9c9c00, 0x16161600, - 0x53535300, 0x18181800, 0xf2f2f200, 0x22222200, 0xfefefe00, 0x44444400, - 0xcfcfcf00, 0xb2b2b200, 0xc3c3c300, 0xb5b5b500, 0x7a7a7a00, 0x91919100, - 0x24242400, 0x08080800, 0xe8e8e800, 0xa8a8a800, 0x60606000, 0xfcfcfc00, - 0x69696900, 0x50505000, 0xaaaaaa00, 0xd0d0d000, 0xa0a0a000, 0x7d7d7d00, - 0xa1a1a100, 0x89898900, 0x62626200, 0x97979700, 0x54545400, 0x5b5b5b00, - 0x1e1e1e00, 0x95959500, 0xe0e0e000, 0xffffff00, 0x64646400, 0xd2d2d200, - 0x10101000, 0xc4c4c400, 0x00000000, 0x48484800, 0xa3a3a300, 0xf7f7f700, - 0x75757500, 0xdbdbdb00, 0x8a8a8a00, 0x03030300, 0xe6e6e600, 0xdadada00, - 0x09090900, 0x3f3f3f00, 0xdddddd00, 0x94949400, 0x87878700, 0x5c5c5c00, - 0x83838300, 0x02020200, 0xcdcdcd00, 0x4a4a4a00, 0x90909000, 0x33333300, - 0x73737300, 0x67676700, 0xf6f6f600, 0xf3f3f300, 0x9d9d9d00, 0x7f7f7f00, - 0xbfbfbf00, 0xe2e2e200, 0x52525200, 0x9b9b9b00, 0xd8d8d800, 0x26262600, - 0xc8c8c800, 0x37373700, 0xc6c6c600, 0x3b3b3b00, 0x81818100, 0x96969600, - 0x6f6f6f00, 0x4b4b4b00, 0x13131300, 0xbebebe00, 0x63636300, 0x2e2e2e00, - 0xe9e9e900, 0x79797900, 0xa7a7a700, 0x8c8c8c00, 0x9f9f9f00, 0x6e6e6e00, - 0xbcbcbc00, 0x8e8e8e00, 0x29292900, 0xf5f5f500, 0xf9f9f900, 0xb6b6b600, - 0x2f2f2f00, 0xfdfdfd00, 0xb4b4b400, 0x59595900, 0x78787800, 0x98989800, - 0x06060600, 0x6a6a6a00, 0xe7e7e700, 0x46464600, 0x71717100, 0xbababa00, - 0xd4d4d400, 0x25252500, 0xababab00, 0x42424200, 0x88888800, 0xa2a2a200, - 0x8d8d8d00, 0xfafafa00, 0x72727200, 0x07070700, 0xb9b9b900, 0x55555500, - 0xf8f8f800, 0xeeeeee00, 0xacacac00, 0x0a0a0a00, 0x36363600, 0x49494900, - 0x2a2a2a00, 0x68686800, 0x3c3c3c00, 0x38383800, 0xf1f1f100, 0xa4a4a400, - 0x40404000, 0x28282800, 0xd3d3d300, 0x7b7b7b00, 0xbbbbbb00, 0xc9c9c900, - 0x43434300, 0xc1c1c100, 0x15151500, 0xe3e3e300, 0xadadad00, 0xf4f4f400, - 0x77777700, 0xc7c7c700, 0x80808000, 0x9e9e9e00, + 0x70707000, + 0x82828200, + 0x2c2c2c00, + 0xececec00, + 0xb3b3b300, + 0x27272700, + 0xc0c0c000, + 0xe5e5e500, + 0xe4e4e400, + 0x85858500, + 0x57575700, + 0x35353500, + 0xeaeaea00, + 0x0c0c0c00, + 0xaeaeae00, + 0x41414100, + 0x23232300, + 0xefefef00, + 0x6b6b6b00, + 0x93939300, + 0x45454500, + 0x19191900, + 0xa5a5a500, + 0x21212100, + 0xededed00, + 0x0e0e0e00, + 0x4f4f4f00, + 0x4e4e4e00, + 0x1d1d1d00, + 0x65656500, + 0x92929200, + 0xbdbdbd00, + 0x86868600, + 0xb8b8b800, + 0xafafaf00, + 0x8f8f8f00, + 0x7c7c7c00, + 0xebebeb00, + 0x1f1f1f00, + 0xcecece00, + 0x3e3e3e00, + 0x30303000, + 0xdcdcdc00, + 0x5f5f5f00, + 0x5e5e5e00, + 0xc5c5c500, + 0x0b0b0b00, + 0x1a1a1a00, + 0xa6a6a600, + 0xe1e1e100, + 0x39393900, + 0xcacaca00, + 0xd5d5d500, + 0x47474700, + 0x5d5d5d00, + 0x3d3d3d00, + 0xd9d9d900, + 0x01010100, + 0x5a5a5a00, + 0xd6d6d600, + 0x51515100, + 0x56565600, + 0x6c6c6c00, + 0x4d4d4d00, + 0x8b8b8b00, + 0x0d0d0d00, + 0x9a9a9a00, + 0x66666600, + 0xfbfbfb00, + 0xcccccc00, + 0xb0b0b000, + 0x2d2d2d00, + 0x74747400, + 0x12121200, + 0x2b2b2b00, + 0x20202000, + 0xf0f0f000, + 0xb1b1b100, + 0x84848400, + 0x99999900, + 0xdfdfdf00, + 0x4c4c4c00, + 0xcbcbcb00, + 0xc2c2c200, + 0x34343400, + 0x7e7e7e00, + 0x76767600, + 0x05050500, + 0x6d6d6d00, + 0xb7b7b700, + 0xa9a9a900, + 0x31313100, + 0xd1d1d100, + 0x17171700, + 0x04040400, + 0xd7d7d700, + 0x14141400, + 0x58585800, + 0x3a3a3a00, + 0x61616100, + 0xdedede00, + 0x1b1b1b00, + 0x11111100, + 0x1c1c1c00, + 0x32323200, + 0x0f0f0f00, + 0x9c9c9c00, + 0x16161600, + 0x53535300, + 0x18181800, + 0xf2f2f200, + 0x22222200, + 0xfefefe00, + 0x44444400, + 0xcfcfcf00, + 0xb2b2b200, + 0xc3c3c300, + 0xb5b5b500, + 0x7a7a7a00, + 0x91919100, + 0x24242400, + 0x08080800, + 0xe8e8e800, + 0xa8a8a800, + 0x60606000, + 0xfcfcfc00, + 0x69696900, + 0x50505000, + 0xaaaaaa00, + 0xd0d0d000, + 0xa0a0a000, + 0x7d7d7d00, + 0xa1a1a100, + 0x89898900, + 0x62626200, + 0x97979700, + 0x54545400, + 0x5b5b5b00, + 0x1e1e1e00, + 0x95959500, + 0xe0e0e000, + 0xffffff00, + 0x64646400, + 0xd2d2d200, + 0x10101000, + 0xc4c4c400, + 0x00000000, + 0x48484800, + 0xa3a3a300, + 0xf7f7f700, + 0x75757500, + 0xdbdbdb00, + 0x8a8a8a00, + 0x03030300, + 0xe6e6e600, + 0xdadada00, + 0x09090900, + 0x3f3f3f00, + 0xdddddd00, + 0x94949400, + 0x87878700, + 0x5c5c5c00, + 0x83838300, + 0x02020200, + 0xcdcdcd00, + 0x4a4a4a00, + 0x90909000, + 0x33333300, + 0x73737300, + 0x67676700, + 0xf6f6f600, + 0xf3f3f300, + 0x9d9d9d00, + 0x7f7f7f00, + 0xbfbfbf00, + 0xe2e2e200, + 0x52525200, + 0x9b9b9b00, + 0xd8d8d800, + 0x26262600, + 0xc8c8c800, + 0x37373700, + 0xc6c6c600, + 0x3b3b3b00, + 0x81818100, + 0x96969600, + 0x6f6f6f00, + 0x4b4b4b00, + 0x13131300, + 0xbebebe00, + 0x63636300, + 0x2e2e2e00, + 0xe9e9e900, + 0x79797900, + 0xa7a7a700, + 0x8c8c8c00, + 0x9f9f9f00, + 0x6e6e6e00, + 0xbcbcbc00, + 0x8e8e8e00, + 0x29292900, + 0xf5f5f500, + 0xf9f9f900, + 0xb6b6b600, + 0x2f2f2f00, + 0xfdfdfd00, + 0xb4b4b400, + 0x59595900, + 0x78787800, + 0x98989800, + 0x06060600, + 0x6a6a6a00, + 0xe7e7e700, + 0x46464600, + 0x71717100, + 0xbababa00, + 0xd4d4d400, + 0x25252500, + 0xababab00, + 0x42424200, + 0x88888800, + 0xa2a2a200, + 0x8d8d8d00, + 0xfafafa00, + 0x72727200, + 0x07070700, + 0xb9b9b900, + 0x55555500, + 0xf8f8f800, + 0xeeeeee00, + 0xacacac00, + 0x0a0a0a00, + 0x36363600, + 0x49494900, + 0x2a2a2a00, + 0x68686800, + 0x3c3c3c00, + 0x38383800, + 0xf1f1f100, + 0xa4a4a400, + 0x40404000, + 0x28282800, + 0xd3d3d300, + 0x7b7b7b00, + 0xbbbbbb00, + 0xc9c9c900, + 0x43434300, + 0xc1c1c100, + 0x15151500, + 0xe3e3e300, + 0xadadad00, + 0xf4f4f400, + 0x77777700, + 0xc7c7c700, + 0x80808000, + 0x9e9e9e00, ]; /** * @var array */ private static array $sbox4_4404 = [ - 0x70700070, 0x2c2c002c, 0xb3b300b3, 0xc0c000c0, 0xe4e400e4, 0x57570057, - 0xeaea00ea, 0xaeae00ae, 0x23230023, 0x6b6b006b, 0x45450045, 0xa5a500a5, - 0xeded00ed, 0x4f4f004f, 0x1d1d001d, 0x92920092, 0x86860086, 0xafaf00af, - 0x7c7c007c, 0x1f1f001f, 0x3e3e003e, 0xdcdc00dc, 0x5e5e005e, 0x0b0b000b, - 0xa6a600a6, 0x39390039, 0xd5d500d5, 0x5d5d005d, 0xd9d900d9, 0x5a5a005a, - 0x51510051, 0x6c6c006c, 0x8b8b008b, 0x9a9a009a, 0xfbfb00fb, 0xb0b000b0, - 0x74740074, 0x2b2b002b, 0xf0f000f0, 0x84840084, 0xdfdf00df, 0xcbcb00cb, - 0x34340034, 0x76760076, 0x6d6d006d, 0xa9a900a9, 0xd1d100d1, 0x04040004, - 0x14140014, 0x3a3a003a, 0xdede00de, 0x11110011, 0x32320032, 0x9c9c009c, - 0x53530053, 0xf2f200f2, 0xfefe00fe, 0xcfcf00cf, 0xc3c300c3, 0x7a7a007a, - 0x24240024, 0xe8e800e8, 0x60600060, 0x69690069, 0xaaaa00aa, 0xa0a000a0, - 0xa1a100a1, 0x62620062, 0x54540054, 0x1e1e001e, 0xe0e000e0, 0x64640064, - 0x10100010, 0x00000000, 0xa3a300a3, 0x75750075, 0x8a8a008a, 0xe6e600e6, - 0x09090009, 0xdddd00dd, 0x87870087, 0x83830083, 0xcdcd00cd, 0x90900090, - 0x73730073, 0xf6f600f6, 0x9d9d009d, 0xbfbf00bf, 0x52520052, 0xd8d800d8, - 0xc8c800c8, 0xc6c600c6, 0x81810081, 0x6f6f006f, 0x13130013, 0x63630063, - 0xe9e900e9, 0xa7a700a7, 0x9f9f009f, 0xbcbc00bc, 0x29290029, 0xf9f900f9, - 0x2f2f002f, 0xb4b400b4, 0x78780078, 0x06060006, 0xe7e700e7, 0x71710071, - 0xd4d400d4, 0xabab00ab, 0x88880088, 0x8d8d008d, 0x72720072, 0xb9b900b9, - 0xf8f800f8, 0xacac00ac, 0x36360036, 0x2a2a002a, 0x3c3c003c, 0xf1f100f1, - 0x40400040, 0xd3d300d3, 0xbbbb00bb, 0x43430043, 0x15150015, 0xadad00ad, - 0x77770077, 0x80800080, 0x82820082, 0xecec00ec, 0x27270027, 0xe5e500e5, - 0x85850085, 0x35350035, 0x0c0c000c, 0x41410041, 0xefef00ef, 0x93930093, - 0x19190019, 0x21210021, 0x0e0e000e, 0x4e4e004e, 0x65650065, 0xbdbd00bd, - 0xb8b800b8, 0x8f8f008f, 0xebeb00eb, 0xcece00ce, 0x30300030, 0x5f5f005f, - 0xc5c500c5, 0x1a1a001a, 0xe1e100e1, 0xcaca00ca, 0x47470047, 0x3d3d003d, - 0x01010001, 0xd6d600d6, 0x56560056, 0x4d4d004d, 0x0d0d000d, 0x66660066, - 0xcccc00cc, 0x2d2d002d, 0x12120012, 0x20200020, 0xb1b100b1, 0x99990099, - 0x4c4c004c, 0xc2c200c2, 0x7e7e007e, 0x05050005, 0xb7b700b7, 0x31310031, - 0x17170017, 0xd7d700d7, 0x58580058, 0x61610061, 0x1b1b001b, 0x1c1c001c, - 0x0f0f000f, 0x16160016, 0x18180018, 0x22220022, 0x44440044, 0xb2b200b2, - 0xb5b500b5, 0x91910091, 0x08080008, 0xa8a800a8, 0xfcfc00fc, 0x50500050, - 0xd0d000d0, 0x7d7d007d, 0x89890089, 0x97970097, 0x5b5b005b, 0x95950095, - 0xffff00ff, 0xd2d200d2, 0xc4c400c4, 0x48480048, 0xf7f700f7, 0xdbdb00db, - 0x03030003, 0xdada00da, 0x3f3f003f, 0x94940094, 0x5c5c005c, 0x02020002, - 0x4a4a004a, 0x33330033, 0x67670067, 0xf3f300f3, 0x7f7f007f, 0xe2e200e2, - 0x9b9b009b, 0x26260026, 0x37370037, 0x3b3b003b, 0x96960096, 0x4b4b004b, - 0xbebe00be, 0x2e2e002e, 0x79790079, 0x8c8c008c, 0x6e6e006e, 0x8e8e008e, - 0xf5f500f5, 0xb6b600b6, 0xfdfd00fd, 0x59590059, 0x98980098, 0x6a6a006a, - 0x46460046, 0xbaba00ba, 0x25250025, 0x42420042, 0xa2a200a2, 0xfafa00fa, - 0x07070007, 0x55550055, 0xeeee00ee, 0x0a0a000a, 0x49490049, 0x68680068, - 0x38380038, 0xa4a400a4, 0x28280028, 0x7b7b007b, 0xc9c900c9, 0xc1c100c1, - 0xe3e300e3, 0xf4f400f4, 0xc7c700c7, 0x9e9e009e, + 0x70700070, + 0x2c2c002c, + 0xb3b300b3, + 0xc0c000c0, + 0xe4e400e4, + 0x57570057, + 0xeaea00ea, + 0xaeae00ae, + 0x23230023, + 0x6b6b006b, + 0x45450045, + 0xa5a500a5, + 0xeded00ed, + 0x4f4f004f, + 0x1d1d001d, + 0x92920092, + 0x86860086, + 0xafaf00af, + 0x7c7c007c, + 0x1f1f001f, + 0x3e3e003e, + 0xdcdc00dc, + 0x5e5e005e, + 0x0b0b000b, + 0xa6a600a6, + 0x39390039, + 0xd5d500d5, + 0x5d5d005d, + 0xd9d900d9, + 0x5a5a005a, + 0x51510051, + 0x6c6c006c, + 0x8b8b008b, + 0x9a9a009a, + 0xfbfb00fb, + 0xb0b000b0, + 0x74740074, + 0x2b2b002b, + 0xf0f000f0, + 0x84840084, + 0xdfdf00df, + 0xcbcb00cb, + 0x34340034, + 0x76760076, + 0x6d6d006d, + 0xa9a900a9, + 0xd1d100d1, + 0x04040004, + 0x14140014, + 0x3a3a003a, + 0xdede00de, + 0x11110011, + 0x32320032, + 0x9c9c009c, + 0x53530053, + 0xf2f200f2, + 0xfefe00fe, + 0xcfcf00cf, + 0xc3c300c3, + 0x7a7a007a, + 0x24240024, + 0xe8e800e8, + 0x60600060, + 0x69690069, + 0xaaaa00aa, + 0xa0a000a0, + 0xa1a100a1, + 0x62620062, + 0x54540054, + 0x1e1e001e, + 0xe0e000e0, + 0x64640064, + 0x10100010, + 0x00000000, + 0xa3a300a3, + 0x75750075, + 0x8a8a008a, + 0xe6e600e6, + 0x09090009, + 0xdddd00dd, + 0x87870087, + 0x83830083, + 0xcdcd00cd, + 0x90900090, + 0x73730073, + 0xf6f600f6, + 0x9d9d009d, + 0xbfbf00bf, + 0x52520052, + 0xd8d800d8, + 0xc8c800c8, + 0xc6c600c6, + 0x81810081, + 0x6f6f006f, + 0x13130013, + 0x63630063, + 0xe9e900e9, + 0xa7a700a7, + 0x9f9f009f, + 0xbcbc00bc, + 0x29290029, + 0xf9f900f9, + 0x2f2f002f, + 0xb4b400b4, + 0x78780078, + 0x06060006, + 0xe7e700e7, + 0x71710071, + 0xd4d400d4, + 0xabab00ab, + 0x88880088, + 0x8d8d008d, + 0x72720072, + 0xb9b900b9, + 0xf8f800f8, + 0xacac00ac, + 0x36360036, + 0x2a2a002a, + 0x3c3c003c, + 0xf1f100f1, + 0x40400040, + 0xd3d300d3, + 0xbbbb00bb, + 0x43430043, + 0x15150015, + 0xadad00ad, + 0x77770077, + 0x80800080, + 0x82820082, + 0xecec00ec, + 0x27270027, + 0xe5e500e5, + 0x85850085, + 0x35350035, + 0x0c0c000c, + 0x41410041, + 0xefef00ef, + 0x93930093, + 0x19190019, + 0x21210021, + 0x0e0e000e, + 0x4e4e004e, + 0x65650065, + 0xbdbd00bd, + 0xb8b800b8, + 0x8f8f008f, + 0xebeb00eb, + 0xcece00ce, + 0x30300030, + 0x5f5f005f, + 0xc5c500c5, + 0x1a1a001a, + 0xe1e100e1, + 0xcaca00ca, + 0x47470047, + 0x3d3d003d, + 0x01010001, + 0xd6d600d6, + 0x56560056, + 0x4d4d004d, + 0x0d0d000d, + 0x66660066, + 0xcccc00cc, + 0x2d2d002d, + 0x12120012, + 0x20200020, + 0xb1b100b1, + 0x99990099, + 0x4c4c004c, + 0xc2c200c2, + 0x7e7e007e, + 0x05050005, + 0xb7b700b7, + 0x31310031, + 0x17170017, + 0xd7d700d7, + 0x58580058, + 0x61610061, + 0x1b1b001b, + 0x1c1c001c, + 0x0f0f000f, + 0x16160016, + 0x18180018, + 0x22220022, + 0x44440044, + 0xb2b200b2, + 0xb5b500b5, + 0x91910091, + 0x08080008, + 0xa8a800a8, + 0xfcfc00fc, + 0x50500050, + 0xd0d000d0, + 0x7d7d007d, + 0x89890089, + 0x97970097, + 0x5b5b005b, + 0x95950095, + 0xffff00ff, + 0xd2d200d2, + 0xc4c400c4, + 0x48480048, + 0xf7f700f7, + 0xdbdb00db, + 0x03030003, + 0xdada00da, + 0x3f3f003f, + 0x94940094, + 0x5c5c005c, + 0x02020002, + 0x4a4a004a, + 0x33330033, + 0x67670067, + 0xf3f300f3, + 0x7f7f007f, + 0xe2e200e2, + 0x9b9b009b, + 0x26260026, + 0x37370037, + 0x3b3b003b, + 0x96960096, + 0x4b4b004b, + 0xbebe00be, + 0x2e2e002e, + 0x79790079, + 0x8c8c008c, + 0x6e6e006e, + 0x8e8e008e, + 0xf5f500f5, + 0xb6b600b6, + 0xfdfd00fd, + 0x59590059, + 0x98980098, + 0x6a6a006a, + 0x46460046, + 0xbaba00ba, + 0x25250025, + 0x42420042, + 0xa2a200a2, + 0xfafa00fa, + 0x07070007, + 0x55550055, + 0xeeee00ee, + 0x0a0a000a, + 0x49490049, + 0x68680068, + 0x38380038, + 0xa4a400a4, + 0x28280028, + 0x7b7b007b, + 0xc9c900c9, + 0xc1c100c1, + 0xe3e300e3, + 0xf4f400f4, + 0xc7c700c7, + 0x9e9e009e, ]; /** * @var array */ private static array $sbox2_0222 = [ - 0x00e0e0e0, 0x00050505, 0x00585858, 0x00d9d9d9, 0x00676767, 0x004e4e4e, - 0x00818181, 0x00cbcbcb, 0x00c9c9c9, 0x000b0b0b, 0x00aeaeae, 0x006a6a6a, - 0x00d5d5d5, 0x00181818, 0x005d5d5d, 0x00828282, 0x00464646, 0x00dfdfdf, - 0x00d6d6d6, 0x00272727, 0x008a8a8a, 0x00323232, 0x004b4b4b, 0x00424242, - 0x00dbdbdb, 0x001c1c1c, 0x009e9e9e, 0x009c9c9c, 0x003a3a3a, 0x00cacaca, - 0x00252525, 0x007b7b7b, 0x000d0d0d, 0x00717171, 0x005f5f5f, 0x001f1f1f, - 0x00f8f8f8, 0x00d7d7d7, 0x003e3e3e, 0x009d9d9d, 0x007c7c7c, 0x00606060, - 0x00b9b9b9, 0x00bebebe, 0x00bcbcbc, 0x008b8b8b, 0x00161616, 0x00343434, - 0x004d4d4d, 0x00c3c3c3, 0x00727272, 0x00959595, 0x00ababab, 0x008e8e8e, - 0x00bababa, 0x007a7a7a, 0x00b3b3b3, 0x00020202, 0x00b4b4b4, 0x00adadad, - 0x00a2a2a2, 0x00acacac, 0x00d8d8d8, 0x009a9a9a, 0x00171717, 0x001a1a1a, - 0x00353535, 0x00cccccc, 0x00f7f7f7, 0x00999999, 0x00616161, 0x005a5a5a, - 0x00e8e8e8, 0x00242424, 0x00565656, 0x00404040, 0x00e1e1e1, 0x00636363, - 0x00090909, 0x00333333, 0x00bfbfbf, 0x00989898, 0x00979797, 0x00858585, - 0x00686868, 0x00fcfcfc, 0x00ececec, 0x000a0a0a, 0x00dadada, 0x006f6f6f, - 0x00535353, 0x00626262, 0x00a3a3a3, 0x002e2e2e, 0x00080808, 0x00afafaf, - 0x00282828, 0x00b0b0b0, 0x00747474, 0x00c2c2c2, 0x00bdbdbd, 0x00363636, - 0x00222222, 0x00383838, 0x00646464, 0x001e1e1e, 0x00393939, 0x002c2c2c, - 0x00a6a6a6, 0x00303030, 0x00e5e5e5, 0x00444444, 0x00fdfdfd, 0x00888888, - 0x009f9f9f, 0x00656565, 0x00878787, 0x006b6b6b, 0x00f4f4f4, 0x00232323, - 0x00484848, 0x00101010, 0x00d1d1d1, 0x00515151, 0x00c0c0c0, 0x00f9f9f9, - 0x00d2d2d2, 0x00a0a0a0, 0x00555555, 0x00a1a1a1, 0x00414141, 0x00fafafa, - 0x00434343, 0x00131313, 0x00c4c4c4, 0x002f2f2f, 0x00a8a8a8, 0x00b6b6b6, - 0x003c3c3c, 0x002b2b2b, 0x00c1c1c1, 0x00ffffff, 0x00c8c8c8, 0x00a5a5a5, - 0x00202020, 0x00898989, 0x00000000, 0x00909090, 0x00474747, 0x00efefef, - 0x00eaeaea, 0x00b7b7b7, 0x00151515, 0x00060606, 0x00cdcdcd, 0x00b5b5b5, - 0x00121212, 0x007e7e7e, 0x00bbbbbb, 0x00292929, 0x000f0f0f, 0x00b8b8b8, - 0x00070707, 0x00040404, 0x009b9b9b, 0x00949494, 0x00212121, 0x00666666, - 0x00e6e6e6, 0x00cecece, 0x00ededed, 0x00e7e7e7, 0x003b3b3b, 0x00fefefe, - 0x007f7f7f, 0x00c5c5c5, 0x00a4a4a4, 0x00373737, 0x00b1b1b1, 0x004c4c4c, - 0x00919191, 0x006e6e6e, 0x008d8d8d, 0x00767676, 0x00030303, 0x002d2d2d, - 0x00dedede, 0x00969696, 0x00262626, 0x007d7d7d, 0x00c6c6c6, 0x005c5c5c, - 0x00d3d3d3, 0x00f2f2f2, 0x004f4f4f, 0x00191919, 0x003f3f3f, 0x00dcdcdc, - 0x00797979, 0x001d1d1d, 0x00525252, 0x00ebebeb, 0x00f3f3f3, 0x006d6d6d, - 0x005e5e5e, 0x00fbfbfb, 0x00696969, 0x00b2b2b2, 0x00f0f0f0, 0x00313131, - 0x000c0c0c, 0x00d4d4d4, 0x00cfcfcf, 0x008c8c8c, 0x00e2e2e2, 0x00757575, - 0x00a9a9a9, 0x004a4a4a, 0x00575757, 0x00848484, 0x00111111, 0x00454545, - 0x001b1b1b, 0x00f5f5f5, 0x00e4e4e4, 0x000e0e0e, 0x00737373, 0x00aaaaaa, - 0x00f1f1f1, 0x00dddddd, 0x00595959, 0x00141414, 0x006c6c6c, 0x00929292, - 0x00545454, 0x00d0d0d0, 0x00787878, 0x00707070, 0x00e3e3e3, 0x00494949, - 0x00808080, 0x00505050, 0x00a7a7a7, 0x00f6f6f6, 0x00777777, 0x00939393, - 0x00868686, 0x00838383, 0x002a2a2a, 0x00c7c7c7, 0x005b5b5b, 0x00e9e9e9, - 0x00eeeeee, 0x008f8f8f, 0x00010101, 0x003d3d3d, + 0x00e0e0e0, + 0x00050505, + 0x00585858, + 0x00d9d9d9, + 0x00676767, + 0x004e4e4e, + 0x00818181, + 0x00cbcbcb, + 0x00c9c9c9, + 0x000b0b0b, + 0x00aeaeae, + 0x006a6a6a, + 0x00d5d5d5, + 0x00181818, + 0x005d5d5d, + 0x00828282, + 0x00464646, + 0x00dfdfdf, + 0x00d6d6d6, + 0x00272727, + 0x008a8a8a, + 0x00323232, + 0x004b4b4b, + 0x00424242, + 0x00dbdbdb, + 0x001c1c1c, + 0x009e9e9e, + 0x009c9c9c, + 0x003a3a3a, + 0x00cacaca, + 0x00252525, + 0x007b7b7b, + 0x000d0d0d, + 0x00717171, + 0x005f5f5f, + 0x001f1f1f, + 0x00f8f8f8, + 0x00d7d7d7, + 0x003e3e3e, + 0x009d9d9d, + 0x007c7c7c, + 0x00606060, + 0x00b9b9b9, + 0x00bebebe, + 0x00bcbcbc, + 0x008b8b8b, + 0x00161616, + 0x00343434, + 0x004d4d4d, + 0x00c3c3c3, + 0x00727272, + 0x00959595, + 0x00ababab, + 0x008e8e8e, + 0x00bababa, + 0x007a7a7a, + 0x00b3b3b3, + 0x00020202, + 0x00b4b4b4, + 0x00adadad, + 0x00a2a2a2, + 0x00acacac, + 0x00d8d8d8, + 0x009a9a9a, + 0x00171717, + 0x001a1a1a, + 0x00353535, + 0x00cccccc, + 0x00f7f7f7, + 0x00999999, + 0x00616161, + 0x005a5a5a, + 0x00e8e8e8, + 0x00242424, + 0x00565656, + 0x00404040, + 0x00e1e1e1, + 0x00636363, + 0x00090909, + 0x00333333, + 0x00bfbfbf, + 0x00989898, + 0x00979797, + 0x00858585, + 0x00686868, + 0x00fcfcfc, + 0x00ececec, + 0x000a0a0a, + 0x00dadada, + 0x006f6f6f, + 0x00535353, + 0x00626262, + 0x00a3a3a3, + 0x002e2e2e, + 0x00080808, + 0x00afafaf, + 0x00282828, + 0x00b0b0b0, + 0x00747474, + 0x00c2c2c2, + 0x00bdbdbd, + 0x00363636, + 0x00222222, + 0x00383838, + 0x00646464, + 0x001e1e1e, + 0x00393939, + 0x002c2c2c, + 0x00a6a6a6, + 0x00303030, + 0x00e5e5e5, + 0x00444444, + 0x00fdfdfd, + 0x00888888, + 0x009f9f9f, + 0x00656565, + 0x00878787, + 0x006b6b6b, + 0x00f4f4f4, + 0x00232323, + 0x00484848, + 0x00101010, + 0x00d1d1d1, + 0x00515151, + 0x00c0c0c0, + 0x00f9f9f9, + 0x00d2d2d2, + 0x00a0a0a0, + 0x00555555, + 0x00a1a1a1, + 0x00414141, + 0x00fafafa, + 0x00434343, + 0x00131313, + 0x00c4c4c4, + 0x002f2f2f, + 0x00a8a8a8, + 0x00b6b6b6, + 0x003c3c3c, + 0x002b2b2b, + 0x00c1c1c1, + 0x00ffffff, + 0x00c8c8c8, + 0x00a5a5a5, + 0x00202020, + 0x00898989, + 0x00000000, + 0x00909090, + 0x00474747, + 0x00efefef, + 0x00eaeaea, + 0x00b7b7b7, + 0x00151515, + 0x00060606, + 0x00cdcdcd, + 0x00b5b5b5, + 0x00121212, + 0x007e7e7e, + 0x00bbbbbb, + 0x00292929, + 0x000f0f0f, + 0x00b8b8b8, + 0x00070707, + 0x00040404, + 0x009b9b9b, + 0x00949494, + 0x00212121, + 0x00666666, + 0x00e6e6e6, + 0x00cecece, + 0x00ededed, + 0x00e7e7e7, + 0x003b3b3b, + 0x00fefefe, + 0x007f7f7f, + 0x00c5c5c5, + 0x00a4a4a4, + 0x00373737, + 0x00b1b1b1, + 0x004c4c4c, + 0x00919191, + 0x006e6e6e, + 0x008d8d8d, + 0x00767676, + 0x00030303, + 0x002d2d2d, + 0x00dedede, + 0x00969696, + 0x00262626, + 0x007d7d7d, + 0x00c6c6c6, + 0x005c5c5c, + 0x00d3d3d3, + 0x00f2f2f2, + 0x004f4f4f, + 0x00191919, + 0x003f3f3f, + 0x00dcdcdc, + 0x00797979, + 0x001d1d1d, + 0x00525252, + 0x00ebebeb, + 0x00f3f3f3, + 0x006d6d6d, + 0x005e5e5e, + 0x00fbfbfb, + 0x00696969, + 0x00b2b2b2, + 0x00f0f0f0, + 0x00313131, + 0x000c0c0c, + 0x00d4d4d4, + 0x00cfcfcf, + 0x008c8c8c, + 0x00e2e2e2, + 0x00757575, + 0x00a9a9a9, + 0x004a4a4a, + 0x00575757, + 0x00848484, + 0x00111111, + 0x00454545, + 0x001b1b1b, + 0x00f5f5f5, + 0x00e4e4e4, + 0x000e0e0e, + 0x00737373, + 0x00aaaaaa, + 0x00f1f1f1, + 0x00dddddd, + 0x00595959, + 0x00141414, + 0x006c6c6c, + 0x00929292, + 0x00545454, + 0x00d0d0d0, + 0x00787878, + 0x00707070, + 0x00e3e3e3, + 0x00494949, + 0x00808080, + 0x00505050, + 0x00a7a7a7, + 0x00f6f6f6, + 0x00777777, + 0x00939393, + 0x00868686, + 0x00838383, + 0x002a2a2a, + 0x00c7c7c7, + 0x005b5b5b, + 0x00e9e9e9, + 0x00eeeeee, + 0x008f8f8f, + 0x00010101, + 0x003d3d3d, ]; /** * @var array */ private static array $sbox3_3033 = [ - 0x38003838, 0x41004141, 0x16001616, 0x76007676, 0xd900d9d9, 0x93009393, - 0x60006060, 0xf200f2f2, 0x72007272, 0xc200c2c2, 0xab00abab, 0x9a009a9a, - 0x75007575, 0x06000606, 0x57005757, 0xa000a0a0, 0x91009191, 0xf700f7f7, - 0xb500b5b5, 0xc900c9c9, 0xa200a2a2, 0x8c008c8c, 0xd200d2d2, 0x90009090, - 0xf600f6f6, 0x07000707, 0xa700a7a7, 0x27002727, 0x8e008e8e, 0xb200b2b2, - 0x49004949, 0xde00dede, 0x43004343, 0x5c005c5c, 0xd700d7d7, 0xc700c7c7, - 0x3e003e3e, 0xf500f5f5, 0x8f008f8f, 0x67006767, 0x1f001f1f, 0x18001818, - 0x6e006e6e, 0xaf00afaf, 0x2f002f2f, 0xe200e2e2, 0x85008585, 0x0d000d0d, - 0x53005353, 0xf000f0f0, 0x9c009c9c, 0x65006565, 0xea00eaea, 0xa300a3a3, - 0xae00aeae, 0x9e009e9e, 0xec00ecec, 0x80008080, 0x2d002d2d, 0x6b006b6b, - 0xa800a8a8, 0x2b002b2b, 0x36003636, 0xa600a6a6, 0xc500c5c5, 0x86008686, - 0x4d004d4d, 0x33003333, 0xfd00fdfd, 0x66006666, 0x58005858, 0x96009696, - 0x3a003a3a, 0x09000909, 0x95009595, 0x10001010, 0x78007878, 0xd800d8d8, - 0x42004242, 0xcc00cccc, 0xef00efef, 0x26002626, 0xe500e5e5, 0x61006161, - 0x1a001a1a, 0x3f003f3f, 0x3b003b3b, 0x82008282, 0xb600b6b6, 0xdb00dbdb, - 0xd400d4d4, 0x98009898, 0xe800e8e8, 0x8b008b8b, 0x02000202, 0xeb00ebeb, - 0x0a000a0a, 0x2c002c2c, 0x1d001d1d, 0xb000b0b0, 0x6f006f6f, 0x8d008d8d, - 0x88008888, 0x0e000e0e, 0x19001919, 0x87008787, 0x4e004e4e, 0x0b000b0b, - 0xa900a9a9, 0x0c000c0c, 0x79007979, 0x11001111, 0x7f007f7f, 0x22002222, - 0xe700e7e7, 0x59005959, 0xe100e1e1, 0xda00dada, 0x3d003d3d, 0xc800c8c8, - 0x12001212, 0x04000404, 0x74007474, 0x54005454, 0x30003030, 0x7e007e7e, - 0xb400b4b4, 0x28002828, 0x55005555, 0x68006868, 0x50005050, 0xbe00bebe, - 0xd000d0d0, 0xc400c4c4, 0x31003131, 0xcb00cbcb, 0x2a002a2a, 0xad00adad, - 0x0f000f0f, 0xca00caca, 0x70007070, 0xff00ffff, 0x32003232, 0x69006969, - 0x08000808, 0x62006262, 0x00000000, 0x24002424, 0xd100d1d1, 0xfb00fbfb, - 0xba00baba, 0xed00eded, 0x45004545, 0x81008181, 0x73007373, 0x6d006d6d, - 0x84008484, 0x9f009f9f, 0xee00eeee, 0x4a004a4a, 0xc300c3c3, 0x2e002e2e, - 0xc100c1c1, 0x01000101, 0xe600e6e6, 0x25002525, 0x48004848, 0x99009999, - 0xb900b9b9, 0xb300b3b3, 0x7b007b7b, 0xf900f9f9, 0xce00cece, 0xbf00bfbf, - 0xdf00dfdf, 0x71007171, 0x29002929, 0xcd00cdcd, 0x6c006c6c, 0x13001313, - 0x64006464, 0x9b009b9b, 0x63006363, 0x9d009d9d, 0xc000c0c0, 0x4b004b4b, - 0xb700b7b7, 0xa500a5a5, 0x89008989, 0x5f005f5f, 0xb100b1b1, 0x17001717, - 0xf400f4f4, 0xbc00bcbc, 0xd300d3d3, 0x46004646, 0xcf00cfcf, 0x37003737, - 0x5e005e5e, 0x47004747, 0x94009494, 0xfa00fafa, 0xfc00fcfc, 0x5b005b5b, - 0x97009797, 0xfe00fefe, 0x5a005a5a, 0xac00acac, 0x3c003c3c, 0x4c004c4c, - 0x03000303, 0x35003535, 0xf300f3f3, 0x23002323, 0xb800b8b8, 0x5d005d5d, - 0x6a006a6a, 0x92009292, 0xd500d5d5, 0x21002121, 0x44004444, 0x51005151, - 0xc600c6c6, 0x7d007d7d, 0x39003939, 0x83008383, 0xdc00dcdc, 0xaa00aaaa, - 0x7c007c7c, 0x77007777, 0x56005656, 0x05000505, 0x1b001b1b, 0xa400a4a4, - 0x15001515, 0x34003434, 0x1e001e1e, 0x1c001c1c, 0xf800f8f8, 0x52005252, - 0x20002020, 0x14001414, 0xe900e9e9, 0xbd00bdbd, 0xdd00dddd, 0xe400e4e4, - 0xa100a1a1, 0xe000e0e0, 0x8a008a8a, 0xf100f1f1, 0xd600d6d6, 0x7a007a7a, - 0xbb00bbbb, 0xe300e3e3, 0x40004040, 0x4f004f4f, + 0x38003838, + 0x41004141, + 0x16001616, + 0x76007676, + 0xd900d9d9, + 0x93009393, + 0x60006060, + 0xf200f2f2, + 0x72007272, + 0xc200c2c2, + 0xab00abab, + 0x9a009a9a, + 0x75007575, + 0x06000606, + 0x57005757, + 0xa000a0a0, + 0x91009191, + 0xf700f7f7, + 0xb500b5b5, + 0xc900c9c9, + 0xa200a2a2, + 0x8c008c8c, + 0xd200d2d2, + 0x90009090, + 0xf600f6f6, + 0x07000707, + 0xa700a7a7, + 0x27002727, + 0x8e008e8e, + 0xb200b2b2, + 0x49004949, + 0xde00dede, + 0x43004343, + 0x5c005c5c, + 0xd700d7d7, + 0xc700c7c7, + 0x3e003e3e, + 0xf500f5f5, + 0x8f008f8f, + 0x67006767, + 0x1f001f1f, + 0x18001818, + 0x6e006e6e, + 0xaf00afaf, + 0x2f002f2f, + 0xe200e2e2, + 0x85008585, + 0x0d000d0d, + 0x53005353, + 0xf000f0f0, + 0x9c009c9c, + 0x65006565, + 0xea00eaea, + 0xa300a3a3, + 0xae00aeae, + 0x9e009e9e, + 0xec00ecec, + 0x80008080, + 0x2d002d2d, + 0x6b006b6b, + 0xa800a8a8, + 0x2b002b2b, + 0x36003636, + 0xa600a6a6, + 0xc500c5c5, + 0x86008686, + 0x4d004d4d, + 0x33003333, + 0xfd00fdfd, + 0x66006666, + 0x58005858, + 0x96009696, + 0x3a003a3a, + 0x09000909, + 0x95009595, + 0x10001010, + 0x78007878, + 0xd800d8d8, + 0x42004242, + 0xcc00cccc, + 0xef00efef, + 0x26002626, + 0xe500e5e5, + 0x61006161, + 0x1a001a1a, + 0x3f003f3f, + 0x3b003b3b, + 0x82008282, + 0xb600b6b6, + 0xdb00dbdb, + 0xd400d4d4, + 0x98009898, + 0xe800e8e8, + 0x8b008b8b, + 0x02000202, + 0xeb00ebeb, + 0x0a000a0a, + 0x2c002c2c, + 0x1d001d1d, + 0xb000b0b0, + 0x6f006f6f, + 0x8d008d8d, + 0x88008888, + 0x0e000e0e, + 0x19001919, + 0x87008787, + 0x4e004e4e, + 0x0b000b0b, + 0xa900a9a9, + 0x0c000c0c, + 0x79007979, + 0x11001111, + 0x7f007f7f, + 0x22002222, + 0xe700e7e7, + 0x59005959, + 0xe100e1e1, + 0xda00dada, + 0x3d003d3d, + 0xc800c8c8, + 0x12001212, + 0x04000404, + 0x74007474, + 0x54005454, + 0x30003030, + 0x7e007e7e, + 0xb400b4b4, + 0x28002828, + 0x55005555, + 0x68006868, + 0x50005050, + 0xbe00bebe, + 0xd000d0d0, + 0xc400c4c4, + 0x31003131, + 0xcb00cbcb, + 0x2a002a2a, + 0xad00adad, + 0x0f000f0f, + 0xca00caca, + 0x70007070, + 0xff00ffff, + 0x32003232, + 0x69006969, + 0x08000808, + 0x62006262, + 0x00000000, + 0x24002424, + 0xd100d1d1, + 0xfb00fbfb, + 0xba00baba, + 0xed00eded, + 0x45004545, + 0x81008181, + 0x73007373, + 0x6d006d6d, + 0x84008484, + 0x9f009f9f, + 0xee00eeee, + 0x4a004a4a, + 0xc300c3c3, + 0x2e002e2e, + 0xc100c1c1, + 0x01000101, + 0xe600e6e6, + 0x25002525, + 0x48004848, + 0x99009999, + 0xb900b9b9, + 0xb300b3b3, + 0x7b007b7b, + 0xf900f9f9, + 0xce00cece, + 0xbf00bfbf, + 0xdf00dfdf, + 0x71007171, + 0x29002929, + 0xcd00cdcd, + 0x6c006c6c, + 0x13001313, + 0x64006464, + 0x9b009b9b, + 0x63006363, + 0x9d009d9d, + 0xc000c0c0, + 0x4b004b4b, + 0xb700b7b7, + 0xa500a5a5, + 0x89008989, + 0x5f005f5f, + 0xb100b1b1, + 0x17001717, + 0xf400f4f4, + 0xbc00bcbc, + 0xd300d3d3, + 0x46004646, + 0xcf00cfcf, + 0x37003737, + 0x5e005e5e, + 0x47004747, + 0x94009494, + 0xfa00fafa, + 0xfc00fcfc, + 0x5b005b5b, + 0x97009797, + 0xfe00fefe, + 0x5a005a5a, + 0xac00acac, + 0x3c003c3c, + 0x4c004c4c, + 0x03000303, + 0x35003535, + 0xf300f3f3, + 0x23002323, + 0xb800b8b8, + 0x5d005d5d, + 0x6a006a6a, + 0x92009292, + 0xd500d5d5, + 0x21002121, + 0x44004444, + 0x51005151, + 0xc600c6c6, + 0x7d007d7d, + 0x39003939, + 0x83008383, + 0xdc00dcdc, + 0xaa00aaaa, + 0x7c007c7c, + 0x77007777, + 0x56005656, + 0x05000505, + 0x1b001b1b, + 0xa400a4a4, + 0x15001515, + 0x34003434, + 0x1e001e1e, + 0x1c001c1c, + 0xf800f8f8, + 0x52005252, + 0x20002020, + 0x14001414, + 0xe900e9e9, + 0xbd00bdbd, + 0xdd00dddd, + 0xe400e4e4, + 0xa100a1a1, + 0xe000e0e0, + 0x8a008a8a, + 0xf100f1f1, + 0xd600d6d6, + 0x7a007a7a, + 0xbb00bbbb, + 0xe300e3e3, + 0x40004040, + 0x4f004f4f, ]; /** @@ -255,7 +1117,7 @@ class Camellia extends BlockCipher */ private array $state; - private bool $keyIs128 = false; + private bool $keyIs128 = false; /** * Constructor @@ -268,7 +1130,7 @@ public function __construct(string $mode) parent::__construct($mode); if ($this->mode === self::MODE_STREAM) { throw new BadModeException( - 'Block ciphers cannot be ran in stream mode.' + "Block ciphers cannot be ran in stream mode." ); } $this->block_size = self::BLOCK_SIZE; @@ -301,11 +1163,16 @@ protected function isValidEngineHelper($engine): bool if ($this->block_size != self::BLOCK_SIZE) { return false; } - $this->cipher_name_openssl_ecb = 'camellia-' . $this->getKeyLength() . '-ecb'; - $this->cipher_name_openssl = 'camellia-' . $this->getKeyLength() . '-' . $this->openssl_translate_mode(); + $this->cipher_name_openssl_ecb = + "camellia-" . $this->getKeyLength() . "-ecb"; + $this->cipher_name_openssl = + "camellia-" . + $this->getKeyLength() . + "-" . + $this->openssl_translate_mode(); break; } - return parent::isValidEngineHelper($engine); + return parent::isValidEngineHelper($engine); } /** @@ -344,12 +1211,17 @@ protected function encryptBlock($input): string $this->subkey[16] = $t[0]; $this->subkey[17] = $t[1]; [$ka, $this->subkey] = self::roldq(15, $ka, 0, $this->subkey, 20); - [$ka, $this->subkey] = self::roldqo32(34, $ka, 0, $this->subkey, 28); + [$ka, $this->subkey] = self::roldqo32( + 34, + $ka, + 0, + $this->subkey, + 28 + ); [$ka, $this->kw] = self::roldq(17, $ka, 0, $this->kw, 4); return $this->processBlock128($input); - } - else { + } else { $kb = self::computeKB($k, $ka); [$k, $this->subkey] = self::roldqo32(45, $k, 0, $this->subkey, 16); @@ -369,7 +1241,13 @@ protected function encryptBlock($input): string $this->ke[9] = $ka[2]; $this->ke[10] = $ka[3]; $this->ke[11] = $ka[0]; - [$ka, $this->subkey] = self::roldqo32(49, $ka, 0, $this->subkey, 40); + [$ka, $this->subkey] = self::roldqo32( + 49, + $ka, + 0, + $this->subkey, + 40 + ); /* KB dependant keys */ $this->subkey[0] = $kb[0]; @@ -414,46 +1292,111 @@ protected function decryptBlock($input): string $this->subkey[35] = $ka[1]; $this->subkey[32] = $ka[2]; $this->subkey[33] = $ka[3]; - [$ka, $this->subkey] = self::decroldq(15, $ka, 0, $this->subkey, 24); + [$ka, $this->subkey] = self::decroldq( + 15, + $ka, + 0, + $this->subkey, + 24 + ); [$ka, $this->ke] = self::decroldq(15, $ka, 0, $this->ke, 4); [$ka, $t] = self::decroldq(15, $ka, 0, $t, 0); $this->subkey[18] = $t[2]; $this->subkey[19] = $t[3]; - [$ka, $this->subkey] = self::decroldq(15, $ka, 0, $this->subkey, 12); - [$ka, $this->subkey] = self::decroldqo32(34, $ka, 0, $this->subkey, 4); + [$ka, $this->subkey] = self::decroldq( + 15, + $ka, + 0, + $this->subkey, + 12 + ); + [$ka, $this->subkey] = self::decroldqo32( + 34, + $ka, + 0, + $this->subkey, + 4 + ); [$ka, $this->kw] = self::roldq(17, $ka, 0, $this->kw, 0); return $this->processBlock128($input); - } - else { + } else { $kb = self::computeKB($k, $ka); - [$k, $this->subkey] = self::decroldqo32(45, $k, 0, $this->subkey, 28); + [$k, $this->subkey] = self::decroldqo32( + 45, + $k, + 0, + $this->subkey, + 28 + ); [$k, $this->ke] = self::decroldq(15, $k, 0, $this->ke, 4); [$k, $this->subkey] = self::decroldq(17, $k, 0, $this->subkey, 12); - [$k, $this->subkey] = self::decroldqo32(34, $k, 0, $this->subkey, 0); + [$k, $this->subkey] = self::decroldqo32( + 34, + $k, + 0, + $this->subkey, + 0 + ); /* KR dependant keys */ [$k, $this->subkey] = self::decroldq(15, $k, 4, $this->subkey, 40); [$k, $this->ke] = self::decroldq(15, $k, 4, $this->ke, 8); [$k, $this->subkey] = self::decroldq(30, $k, 4, $this->subkey, 20); - [$k, $this->subkey] = self::decroldqo32(34, $k, 4, $this->subkey, 8); + [$k, $this->subkey] = self::decroldqo32( + 34, + $k, + 4, + $this->subkey, + 8 + ); /* KA dependant keys */ - [$ka, $this->subkey] = self::decroldq(15, $ka, 0, $this->subkey, 36); - [$ka, $this->subkey] = self::decroldq(30, $ka, 0, $this->subkey, 24); + [$ka, $this->subkey] = self::decroldq( + 15, + $ka, + 0, + $this->subkey, + 36 + ); + [$ka, $this->subkey] = self::decroldq( + 30, + $ka, + 0, + $this->subkey, + 24 + ); /* 32bit rotation */ $this->ke[2] = $ka[1]; $this->ke[3] = $ka[2]; $this->ke[0] = $ka[3]; $this->ke[1] = $ka[0]; - [$ka, $this->subkey] = self::decroldqo32(49, $ka, 0, $this->subkey, 4); + [$ka, $this->subkey] = self::decroldqo32( + 49, + $ka, + 0, + $this->subkey, + 4 + ); /* KB dependant keys */ $this->subkey[46] = $kb[0]; $this->subkey[47] = $kb[1]; $this->subkey[44] = $kb[2]; $this->subkey[45] = $kb[3]; - [$kb, $this->subkey] = self::decroldq(30, $kb, 0, $this->subkey, 32); - [$kb, $this->subkey] = self::decroldq(30, $kb, 0, $this->subkey, 16); + [$kb, $this->subkey] = self::decroldq( + 30, + $kb, + 0, + $this->subkey, + 32 + ); + [$kb, $this->subkey] = self::decroldq( + 30, + $kb, + 0, + $this->subkey, + 16 + ); [$kb, $this->kw] = self::roldqo32(51, $kb, 0, $this->kw, 0); return $this->processBlock192or256($input); @@ -470,7 +1413,7 @@ protected function setupKey(): void 16 => true, 24, 32 => false, default => throw new \LengthException( - 'Key sizes are only 16/24/32 bytes.' + "Key sizes are only 16/24/32 bytes." ), }; } @@ -566,13 +1509,24 @@ private static function computeKB(array $k, array $ka): array * @return array */ private static function roldq( - int $rot, array $ki, int $ioff, array $ko, int $ooff - ): array - { - $ko[0 + $ooff] = Bitwise::leftShift32($ki[0 + $ioff], $rot) | Bitwise::rightShift32($ki[1 + $ioff], 32 - $rot); - $ko[1 + $ooff] = Bitwise::leftShift32($ki[1 + $ioff], $rot) | Bitwise::rightShift32($ki[2 + $ioff], 32 - $rot); - $ko[2 + $ooff] = Bitwise::leftShift32($ki[2 + $ioff], $rot) | Bitwise::rightShift32($ki[3 + $ioff], 32 - $rot); - $ko[3 + $ooff] = Bitwise::leftShift32($ki[3 + $ioff], $rot) | Bitwise::rightShift32($ki[0 + $ioff], 32 - $rot); + int $rot, + array $ki, + int $ioff, + array $ko, + int $ooff + ): array { + $ko[0 + $ooff] = + Bitwise::leftShift32($ki[0 + $ioff], $rot) | + Bitwise::rightShift32($ki[1 + $ioff], 32 - $rot); + $ko[1 + $ooff] = + Bitwise::leftShift32($ki[1 + $ioff], $rot) | + Bitwise::rightShift32($ki[2 + $ioff], 32 - $rot); + $ko[2 + $ooff] = + Bitwise::leftShift32($ki[2 + $ioff], $rot) | + Bitwise::rightShift32($ki[3 + $ioff], 32 - $rot); + $ko[3 + $ooff] = + Bitwise::leftShift32($ki[3 + $ioff], $rot) | + Bitwise::rightShift32($ki[0 + $ioff], 32 - $rot); $ki[0 + $ioff] = $ko[0 + $ooff]; $ki[1 + $ioff] = $ko[1 + $ooff]; $ki[2 + $ioff] = $ko[2 + $ooff]; @@ -589,13 +1543,24 @@ private static function roldq( * @return array */ private static function decroldq( - int $rot, array $ki, int $ioff, array $ko, int $ooff) - : array - { - $ko[2 + $ooff] = Bitwise::leftShift32($ki[0 + $ioff], $rot) | Bitwise::rightShift32($ki[1 + $ioff], 32 - $rot); - $ko[3 + $ooff] = Bitwise::leftShift32($ki[1 + $ioff], $rot) | Bitwise::rightShift32($ki[2 + $ioff], 32 - $rot); - $ko[0 + $ooff] = Bitwise::leftShift32($ki[2 + $ioff], $rot) | Bitwise::rightShift32($ki[3 + $ioff], 32 - $rot); - $ko[1 + $ooff] = Bitwise::leftShift32($ki[3 + $ioff], $rot) | Bitwise::rightShift32($ki[0 + $ioff], 32 - $rot); + int $rot, + array $ki, + int $ioff, + array $ko, + int $ooff + ): array { + $ko[2 + $ooff] = + Bitwise::leftShift32($ki[0 + $ioff], $rot) | + Bitwise::rightShift32($ki[1 + $ioff], 32 - $rot); + $ko[3 + $ooff] = + Bitwise::leftShift32($ki[1 + $ioff], $rot) | + Bitwise::rightShift32($ki[2 + $ioff], 32 - $rot); + $ko[0 + $ooff] = + Bitwise::leftShift32($ki[2 + $ioff], $rot) | + Bitwise::rightShift32($ki[3 + $ioff], 32 - $rot); + $ko[1 + $ooff] = + Bitwise::leftShift32($ki[3 + $ioff], $rot) | + Bitwise::rightShift32($ki[0 + $ioff], 32 - $rot); $ki[0 + $ioff] = $ko[2 + $ooff]; $ki[1 + $ioff] = $ko[3 + $ooff]; $ki[2 + $ioff] = $ko[0 + $ooff]; @@ -612,13 +1577,24 @@ private static function decroldq( * @return array */ private static function roldqo32( - int $rot, array $ki, int $ioff, array $ko, int $ooff - ): array - { - $ko[0 + $ooff] = Bitwise::leftShift32($ki[1 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[2 + $ioff], 64 - $rot); - $ko[1 + $ooff] = Bitwise::leftShift32($ki[2 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[3 + $ioff], 64 - $rot); - $ko[2 + $ooff] = Bitwise::leftShift32($ki[3 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[0 + $ioff], 64 - $rot); - $ko[3 + $ooff] = Bitwise::leftShift32($ki[0 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[1 + $ioff], 64 - $rot); + int $rot, + array $ki, + int $ioff, + array $ko, + int $ooff + ): array { + $ko[0 + $ooff] = + Bitwise::leftShift32($ki[1 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[2 + $ioff], 64 - $rot); + $ko[1 + $ooff] = + Bitwise::leftShift32($ki[2 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[3 + $ioff], 64 - $rot); + $ko[2 + $ooff] = + Bitwise::leftShift32($ki[3 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[0 + $ioff], 64 - $rot); + $ko[3 + $ooff] = + Bitwise::leftShift32($ki[0 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[1 + $ioff], 64 - $rot); $ki[0 + $ioff] = $ko[0 + $ooff]; $ki[1 + $ioff] = $ko[1 + $ooff]; $ki[2 + $ioff] = $ko[2 + $ooff]; @@ -635,13 +1611,24 @@ private static function roldqo32( * @return array */ private static function decroldqo32( - int $rot, array $ki, int $ioff, array $ko, int $ooff - ): array - { - $ko[2 + $ooff] = Bitwise::leftShift32($ki[1 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[2 + $ioff], 64 - $rot); - $ko[3 + $ooff] = Bitwise::leftShift32($ki[2 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[3 + $ioff], 64 - $rot); - $ko[0 + $ooff] = Bitwise::leftShift32($ki[3 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[0 + $ioff], 64 - $rot); - $ko[1 + $ooff] = Bitwise::leftShift32($ki[0 + $ioff], $rot - 32) | Bitwise::rightShift32($ki[1 + $ioff], 64 - $rot); + int $rot, + array $ki, + int $ioff, + array $ko, + int $ooff + ): array { + $ko[2 + $ooff] = + Bitwise::leftShift32($ki[1 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[2 + $ioff], 64 - $rot); + $ko[3 + $ooff] = + Bitwise::leftShift32($ki[2 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[3 + $ioff], 64 - $rot); + $ko[0 + $ooff] = + Bitwise::leftShift32($ki[3 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[0 + $ioff], 64 - $rot); + $ko[1 + $ooff] = + Bitwise::leftShift32($ki[0 + $ioff], $rot - 32) | + Bitwise::rightShift32($ki[1 + $ioff], 64 - $rot); $ki[0 + $ioff] = $ko[2 + $ooff]; $ki[1 + $ioff] = $ko[3 + $ooff]; $ki[2 + $ioff] = $ko[0 + $ooff]; @@ -658,7 +1645,7 @@ private static function decroldqo32( private static function int2Bytes(int $word, array $dst, int $offset): array { for ($i = 0; $i < 4; $i++) { - $dst[(3 - $i) + $offset] = $word & Bitwise::MASK_8BITS; + $dst[3 - $i + $offset] = $word & Bitwise::MASK_8BITS; $word >>= 8; } return $dst; @@ -670,8 +1657,11 @@ private static function int2Bytes(int $word, array $dst, int $offset): array * @param int $offset * @return array */ - private static function camelliaF2(array $s, array $skey, int $offset): array - { + private static function camelliaF2( + array $s, + array $skey, + int $offset + ): array { $t1 = $s[0] ^ $skey[0 + $offset]; $u = self::$sbox4_4404[$t1 & Bitwise::MASK_8BITS]; $u ^= self::$sbox3_3033[($t1 >> 8) & Bitwise::MASK_8BITS]; @@ -709,8 +1699,11 @@ private static function camelliaF2(array $s, array $skey, int $offset): array * @param int $offset * @return array */ - private static function camelliaFLs(array $s, array $fkey, int $offset): array - { + private static function camelliaFLs( + array $s, + array $fkey, + int $offset + ): array { $s[1] ^= Bitwise::leftRotate32($s[0] & $fkey[0 + $offset], 1); $s[0] ^= $fkey[1 + $offset] | $s[1]; @@ -723,7 +1716,7 @@ private static function camelliaFLs(array $s, array $fkey, int $offset): array private function processBlock128(string $input, int $offset = 0): string { for ($i = 0; $i < 4; $i++) { - $this->state[$i] = Helper::bytesToLong($input, $offset + ($i * 4)); + $this->state[$i] = Helper::bytesToLong($input, $offset + $i * 4); $this->state[$i] ^= $this->kw[$i]; } @@ -750,13 +1743,15 @@ private function processBlock128(string $input, int $offset = 0): string $out = self::int2Bytes($this->state[0], $out, 8); $out = self::int2Bytes($this->state[1], $out, 12); - return implode(array_map(static fn (int $byte) => chr($byte), $out)); + return implode(array_map(static fn(int $byte) => chr($byte), $out)); } - private function processBlock192or256(string $input, int $offset = 0): string - { + private function processBlock192or256( + string $input, + int $offset = 0 + ): string { for ($i = 0; $i < 4; $i++) { - $this->state[$i] = Helper::bytesToLong($input, $offset + ($i * 4)); + $this->state[$i] = Helper::bytesToLong($input, $offset + $i * 4); $this->state[$i] ^= $this->kw[$i]; } @@ -787,6 +1782,6 @@ private function processBlock192or256(string $input, int $offset = 0): string $out = self::int2Bytes($this->state[0], $out, 8); $out = self::int2Bytes($this->state[1], $out, 12); - return implode(array_map(static fn (int $byte) => chr($byte), $out)); + return implode(array_map(static fn(int $byte) => chr($byte), $out)); } } diff --git a/src/Cryptor/Symmetric/EcbCipherTrait.php b/src/Cryptor/Symmetric/EcbCipherTrait.php index 7f562c37..e5c38c6c 100644 --- a/src/Cryptor/Symmetric/EcbCipherTrait.php +++ b/src/Cryptor/Symmetric/EcbCipherTrait.php @@ -22,9 +22,10 @@ trait EcbCipherTrait * * @return self */ - public function __construct() { - parent::__construct('ecb'); - $this->setPreferredEngine('PHP'); + public function __construct() + { + parent::__construct("ecb"); + $this->setPreferredEngine("PHP"); } /** diff --git a/src/Cryptor/Symmetric/IDEA.php b/src/Cryptor/Symmetric/IDEA.php index 1f109005..6f5bad74 100644 --- a/src/Cryptor/Symmetric/IDEA.php +++ b/src/Cryptor/Symmetric/IDEA.php @@ -8,9 +8,9 @@ namespace OpenPGP\Cryptor\Symmetric; +use OpenPGP\Common\Helper; use phpseclib3\Crypt\Common\BlockCipher; use phpseclib3\Exception\BadModeException; -use OpenPGP\Common\Helper; /** * IDEA cipher engine class. Ported from Bouncy Castle project. @@ -34,7 +34,7 @@ class IDEA extends BlockCipher const BASE = 0x10001; const BLOCK_SIZE = 8; - const KEY_SIZE = 52; + const KEY_SIZE = 52; /** * Constructor @@ -47,7 +47,7 @@ public function __construct(string $mode) parent::__construct($mode); if ($this->mode == self::MODE_STREAM) { throw new BadModeException( - 'Block ciphers cannot be ran in stream mode.' + "Block ciphers cannot be ran in stream mode." ); } $this->block_size = self::BLOCK_SIZE; @@ -59,7 +59,8 @@ public function __construct(string $mode) protected function encryptBlock($input): string { return self::ideaFunc( - self::generateWorkingKey(true, $this->key), $input + self::generateWorkingKey(true, $this->key), + $input ); } @@ -69,7 +70,8 @@ protected function encryptBlock($input): string protected function decryptBlock($input): string { return self::ideaFunc( - self::generateWorkingKey(false, $this->key), $input + self::generateWorkingKey(false, $this->key), + $input ); } @@ -81,28 +83,25 @@ protected function setupKey(): void } private static function wordToBytes( - int $word, string $bytes, int $offset = 0 - ): string - { - $replace = pack('n', $word); - return substr_replace( - $bytes, $replace, $offset, strlen($replace) - ); + int $word, + string $bytes, + int $offset = 0 + ): string { + $replace = pack("n", $word); + return substr_replace($bytes, $replace, $offset, strlen($replace)); } private static function mul(int $x, int $y): int { if ($x == 0) { - $x = (self::BASE - $y); - } - elseif ($y == 0) { - $x = (self::BASE - $x); - } - else { + $x = self::BASE - $y; + } elseif ($y == 0) { + $x = self::BASE - $x; + } else { $p = $x * $y; $y = $p & self::MASK; $x = $p >> 16; - $x = $y - $x + (($y < $x) ? 1 : 0); + $x = $y - $x + ($y < $x ? 1 : 0); } return $x & self::MASK; } @@ -112,9 +111,7 @@ private static function mul(int $x, int $y): int * @param string $input * @return string */ - private static function ideaFunc( - array $workingKey, string $input - ): string + private static function ideaFunc(array $workingKey, string $input): string { $keyOff = 0; $x0 = Helper::bytesToShort($input, 0); @@ -147,16 +144,16 @@ private static function ideaFunc( $output = str_repeat("\x00", self::BLOCK_SIZE); $output = self::wordToBytes( - self::mul($x0, $workingKey[$keyOff++]), $output, 0 - ); - $output = self::wordToBytes( - $x2 + $workingKey[$keyOff++], $output, 2 - ); - $output = self::wordToBytes( - $x1 + $workingKey[$keyOff++], $output, 4 + self::mul($x0, $workingKey[$keyOff++]), + $output, + 0 ); + $output = self::wordToBytes($x2 + $workingKey[$keyOff++], $output, 2); + $output = self::wordToBytes($x1 + $workingKey[$keyOff++], $output, 4); $output = self::wordToBytes( - self::mul($x3, $workingKey[$keyOff]), $output, 6 + self::mul($x3, $workingKey[$keyOff]), + $output, + 6 ); return $output; @@ -185,13 +182,17 @@ private static function expandKey(string $inKey): array for ($i = 8; $i < self::KEY_SIZE; $i++) { if (($i & 7) < 6) { - $key[$i] = (($key[$i - 7] & 127) << 9 | $key[$i - 6] >> 7) & self::MASK; - } - elseif (($i & 7) == 6) { - $key[$i] = (($key[$i - 7] & 127) << 9 | $key[$i - 14] >> 7) & self::MASK; - } - else { - $key[$i] = (($key[$i - 15] & 127) << 9 | $key[$i - 14] >> 7) & self::MASK; + $key[$i] = + ((($key[$i - 7] & 127) << 9) | ($key[$i - 6] >> 7)) & + self::MASK; + } elseif (($i & 7) == 6) { + $key[$i] = + ((($key[$i - 7] & 127) << 9) | ($key[$i - 14] >> 7)) & + self::MASK; + } else { + $key[$i] = + ((($key[$i - 15] & 127) << 9) | ($key[$i - 14] >> 7)) & + self::MASK; } } return $key; @@ -212,17 +213,17 @@ private static function mulInv(int $x): int } $t0 = 1; $t1 = intval(self::BASE / $x); - $y = intval(self::BASE % $x); + $y = intval(self::BASE % $x); while ($y != 1) { $q = intval($x / $y); $x = intval($x % $y); - $t0 = ($t0 + ($t1 * $q)) & self::MASK; + $t0 = ($t0 + $t1 * $q) & self::MASK; if ($x === 1) { return $t0; } $q = intval($y / $x); $y = intval($y % $x); - $t1 = ($t1 + ($t0 * $q)) & self::MASK; + $t1 = ($t1 + $t0 * $q) & self::MASK; } return (1 - $t1) & self::MASK; } @@ -301,13 +302,12 @@ private static function invertKey(array $inKey): array * @return array */ private static function generateWorkingKey( - bool $forEncryption, string $key - ): array - { + bool $forEncryption, + string $key + ): array { if ($forEncryption) { return self::expandKey($key); - } - else { + } else { return self::invertKey(self::expandKey($key)); } } diff --git a/src/Enum/AeadAlgorithm.php b/src/Enum/AeadAlgorithm.php index 379bf4a3..fe7ac2bd 100644 --- a/src/Enum/AeadAlgorithm.php +++ b/src/Enum/AeadAlgorithm.php @@ -8,12 +8,7 @@ namespace OpenPGP\Enum; -use OpenPGP\Cryptor\Aead\{ - AeadCipher, - EAX, - GCM, - OCB, -}; +use OpenPGP\Cryptor\Aead\{AeadCipher, EAX, GCM, OCB}; /** * Aead algorithm enum @@ -46,7 +41,7 @@ enum AeadAlgorithm: int */ public function blockLength(): int { - return match($this) { + return match ($this) { self::Eax, self::Ocb, self::Gcm => 16, }; } @@ -58,7 +53,7 @@ public function blockLength(): int */ public function ivLength(): int { - return match($this) { + return match ($this) { self::Eax => 16, self::Ocb => 15, self::Gcm => 12, @@ -72,7 +67,7 @@ public function ivLength(): int */ public function tagLength(): int { - return match($this) { + return match ($this) { self::Eax, self::Ocb, self::Gcm => 16, }; } @@ -87,9 +82,8 @@ public function tagLength(): int public function cipherEngine( string $key, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 - ): AeadCipher - { - return match($this) { + ): AeadCipher { + return match ($this) { self::Eax => new EAX($key, $symmetric), self::Ocb => new OCB($key, $symmetric), self::Gcm => new GCM($key, $symmetric), diff --git a/src/Enum/ArmorType.php b/src/Enum/ArmorType.php index 0fef7771..352b7f2f 100644 --- a/src/Enum/ArmorType.php +++ b/src/Enum/ArmorType.php @@ -68,16 +68,18 @@ public static function fromBegin(string $text): self { preg_match(self::BEGIN_PATTERN, $text, $matches); if (empty($matches)) { - throw new \UnexpectedValueException('Unknown ASCII armor type'); + throw new \UnexpectedValueException("Unknown ASCII armor type"); } return match (1) { - preg_match('/MESSAGE, PART \d+\/\d+/', $matches[0]) => self::MultipartSection, - preg_match('/MESSAGE, PART \d+/', $matches[0]) => self::MultipartLast, - preg_match('/SIGNED MESSAGE/', $matches[0]) => self::SignedMessage, - preg_match('/MESSAGE/', $matches[0]) => self::Message, - preg_match('/PUBLIC KEY BLOCK/', $matches[0]) => self::PublicKey, - preg_match('/PRIVATE KEY BLOCK/', $matches[0]) => self::PrivateKey, - preg_match('/SIGNATURE/', $matches[0]) => self::Signature, + preg_match("/MESSAGE, PART \d+\/\d+/", $matches[0]) + => self::MultipartSection, + preg_match("/MESSAGE, PART \d+/", $matches[0]) + => self::MultipartLast, + preg_match("/SIGNED MESSAGE/", $matches[0]) => self::SignedMessage, + preg_match("/MESSAGE/", $matches[0]) => self::Message, + preg_match("/PUBLIC KEY BLOCK/", $matches[0]) => self::PublicKey, + preg_match("/PRIVATE KEY BLOCK/", $matches[0]) => self::PrivateKey, + preg_match("/SIGNATURE/", $matches[0]) => self::Signature, default => self::Message, }; } diff --git a/src/Enum/CurveOid.php b/src/Enum/CurveOid.php index bf7bc796..bc5742ff 100644 --- a/src/Enum/CurveOid.php +++ b/src/Enum/CurveOid.php @@ -17,7 +17,7 @@ brainpoolP384r1, brainpoolP512r1, Ed25519, - Curve25519, + Curve25519 }; use phpseclib3\File\ASN1; @@ -30,21 +30,21 @@ */ enum CurveOid: string { - case Secp256r1 = '1.2.840.10045.3.1.7'; + case Secp256r1 = "1.2.840.10045.3.1.7"; - case Secp384r1 = '1.3.132.0.34'; + case Secp384r1 = "1.3.132.0.34"; - case Secp521r1 = '1.3.132.0.35'; + case Secp521r1 = "1.3.132.0.35"; - case BrainpoolP256r1 = '1.3.36.3.3.2.8.1.1.7'; + case BrainpoolP256r1 = "1.3.36.3.3.2.8.1.1.7"; - case BrainpoolP384r1 = '1.3.36.3.3.2.8.1.1.11'; + case BrainpoolP384r1 = "1.3.36.3.3.2.8.1.1.11"; - case BrainpoolP512r1 = '1.3.36.3.3.2.8.1.1.13'; + case BrainpoolP512r1 = "1.3.36.3.3.2.8.1.1.13"; - case Ed25519 = '1.3.6.1.4.1.11591.15.1'; + case Ed25519 = "1.3.6.1.4.1.11591.15.1"; - case Curve25519 = '1.3.6.1.4.1.3029.1.5.1'; + case Curve25519 = "1.3.6.1.4.1.3029.1.5.1"; public static function fromOid(string $oid): self { @@ -58,9 +58,9 @@ public static function fromOid(string $oid): self */ public function getCurve(): BaseCurve { - return match($this) { + return match ($this) { self::Secp256r1 => new secp256r1(), - self::Secp384r1 => new secp384r1, + self::Secp384r1 => new secp384r1(), self::Secp521r1 => new secp521r1(), self::BrainpoolP256r1 => new brainpoolP256r1(), self::BrainpoolP384r1 => new brainpoolP384r1(), @@ -77,14 +77,12 @@ public function getCurve(): BaseCurve */ public function hashAlgorithm(): HashAlgorithm { - return match($this) { + return match ($this) { self::Secp256r1, self::BrainpoolP256r1, self::Curve25519 => HashAlgorithm::Sha256, - self::Secp384r1, - self::BrainpoolP384r1 - => HashAlgorithm::Sha384, + self::Secp384r1, self::BrainpoolP384r1 => HashAlgorithm::Sha384, self::Secp521r1, self::BrainpoolP512r1, self::Ed25519 @@ -99,7 +97,7 @@ public function hashAlgorithm(): HashAlgorithm */ public function symmetricAlgorithm(): SymmetricAlgorithm { - return match($this) { + return match ($this) { self::Secp256r1, self::Secp384r1, self::Ed25519, diff --git a/src/Enum/EdDSACurve.php b/src/Enum/EdDSACurve.php index bd7b9f28..2136381b 100644 --- a/src/Enum/EdDSACurve.php +++ b/src/Enum/EdDSACurve.php @@ -9,10 +9,7 @@ namespace OpenPGP\Enum; use phpseclib3\Crypt\EC\BaseCurves\TwistedEdwards; -use phpseclib3\Crypt\EC\Curves\{ - Ed25519, - Ed448, -}; +use phpseclib3\Crypt\EC\Curves\{Ed25519, Ed448}; /** * Ed DSA Curve Enum @@ -34,9 +31,9 @@ enum EdDSACurve */ public function getCurve(): TwistedEdwards { - return match($this) { + return match ($this) { self::Ed25519 => new Ed25519(), - self::Ed448 => new Ed448(), + self::Ed448 => new Ed448(), }; } @@ -49,7 +46,7 @@ public function payloadSize(): int { return match ($this) { self::Ed25519 => Ed25519::SIZE, - self::Ed448 => Ed448::SIZE, + self::Ed448 => Ed448::SIZE, }; } @@ -62,7 +59,7 @@ public function hashAlgorithm(): HashAlgorithm { return match ($this) { self::Ed25519 => HashAlgorithm::Sha256, - self::Ed448 => HashAlgorithm::Sha512, + self::Ed448 => HashAlgorithm::Sha512, }; } } diff --git a/src/Enum/HashAlgorithm.php b/src/Enum/HashAlgorithm.php index 52fe8342..4adbf7e0 100644 --- a/src/Enum/HashAlgorithm.php +++ b/src/Enum/HashAlgorithm.php @@ -44,7 +44,7 @@ enum HashAlgorithm: int */ public function digestSize(): int { - return match($this) { + return match ($this) { self::Unknown => 0, self::Md5 => 16, self::Sha1, self::Ripemd160 => 20, @@ -62,7 +62,7 @@ public function digestSize(): int */ public function saltSize(): int { - return match($this) { + return match ($this) { self::Unknown, self::Md5, self::Sha1, self::Ripemd160 => 0, self::Sha224, self::Sha256, self::Sha3_256 => 16, self::Sha384 => 24, @@ -80,7 +80,9 @@ public function saltSize(): int public function hash(string $message, bool $binary = true): string { return hash( - strtolower(str_replace('_', '-', $this->name)), $message, $binary + strtolower(str_replace("_", "-", $this->name)), + $message, + $binary ); } } diff --git a/src/Enum/KeyAlgorithm.php b/src/Enum/KeyAlgorithm.php index 50a61ee7..de2a64db 100644 --- a/src/Enum/KeyAlgorithm.php +++ b/src/Enum/KeyAlgorithm.php @@ -114,7 +114,8 @@ public function forSigning(): bool self::DiffieHellman, self::Aedh, self::X25519, - self::X448 => false, + self::X448 + => false, default => true, }; } @@ -133,7 +134,8 @@ public function forEncryption(): bool self::EdDsaLegacy, self::AeDsa, self::Ed25519, - self::Ed448 => false, + self::Ed448 + => false, default => true, }; } diff --git a/src/Enum/KeyType.php b/src/Enum/KeyType.php index 50008d32..c495b95d 100644 --- a/src/Enum/KeyType.php +++ b/src/Enum/KeyType.php @@ -15,7 +15,8 @@ * @category Enum * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -enum KeyType { +enum KeyType +{ case Rsa; case Ecc; diff --git a/src/Enum/MontgomeryCurve.php b/src/Enum/MontgomeryCurve.php index 1bd01b8d..dee93ccb 100644 --- a/src/Enum/MontgomeryCurve.php +++ b/src/Enum/MontgomeryCurve.php @@ -9,10 +9,7 @@ namespace OpenPGP\Enum; use phpseclib3\Crypt\EC\BaseCurves\Montgomery; -use phpseclib3\Crypt\EC\Curves\{ - Curve25519, - Curve448, -}; +use phpseclib3\Crypt\EC\Curves\{Curve25519, Curve448}; /** * Montgomery Curve Enum @@ -34,9 +31,9 @@ enum MontgomeryCurve */ public function getCurve(): Montgomery { - return match($this) { + return match ($this) { self::Curve25519 => new Curve25519(), - self::Curve448 => new Curve448(), + self::Curve448 => new Curve448(), }; } @@ -49,7 +46,7 @@ public function payloadSize(): int { return match ($this) { self::Curve25519 => 32, - self::Curve448 => 56, + self::Curve448 => 56, }; } @@ -62,7 +59,7 @@ public function kekSize(): KekSize { return match ($this) { self::Curve25519 => KekSize::Normal, - self::Curve448 => KekSize::High, + self::Curve448 => KekSize::High, }; } @@ -74,8 +71,8 @@ public function kekSize(): KekSize public function hashAlgorithm(): string { return match ($this) { - self::Curve25519 => 'sha256', - self::Curve448 => 'sha512', + self::Curve25519 => "sha256", + self::Curve448 => "sha512", }; } @@ -88,7 +85,7 @@ public function symmetricAlgorithm(): SymmetricAlgorithm { return match ($this) { self::Curve25519 => SymmetricAlgorithm::Aes128, - self::Curve448 => SymmetricAlgorithm::Aes256, + self::Curve448 => SymmetricAlgorithm::Aes256, }; } @@ -99,9 +96,9 @@ public function symmetricAlgorithm(): SymmetricAlgorithm */ public function hkdfInfo(): string { - return match($this) { - self::Curve25519 => 'OpenPGP X25519', - self::Curve448 => 'OpenPGP X448', + return match ($this) { + self::Curve25519 => "OpenPGP X25519", + self::Curve448 => "OpenPGP X448", }; } } diff --git a/src/Enum/S2kType.php b/src/Enum/S2kType.php index dfb526c2..b33d6368 100644 --- a/src/Enum/S2kType.php +++ b/src/Enum/S2kType.php @@ -44,7 +44,7 @@ enum S2kType: int public function dataLength(): int { - return match($this) { + return match ($this) { self::Simple => 2, self::Salted => 10, self::Iterated => 11, diff --git a/src/Enum/SupportFeature.php b/src/Enum/SupportFeature.php index c78a4daa..c90aeacc 100644 --- a/src/Enum/SupportFeature.php +++ b/src/Enum/SupportFeature.php @@ -25,7 +25,7 @@ enum SupportFeature: int case Version1SEIPD = 1; /** - * AEAD Encrypted Data packet (packet 20). + * AEAD Encrypted Data packet (packet 20). * Version 5 Symmetric Encrypted Session Key packet. */ case AeadEncrypted = 2; diff --git a/src/Enum/SymmetricAlgorithm.php b/src/Enum/SymmetricAlgorithm.php index 7ab24337..926c979d 100644 --- a/src/Enum/SymmetricAlgorithm.php +++ b/src/Enum/SymmetricAlgorithm.php @@ -90,7 +90,7 @@ enum SymmetricAlgorithm: int */ public function keySize(): int { - return match($this) { + return match ($this) { self::Plaintext => 0, self::Aes128, self::Blowfish, @@ -98,14 +98,8 @@ public function keySize(): int self::Cast5, self::Idea => 128, - self::Aes192, - self::Camellia192, - self::TripleDes - => 192, - self::Aes256, - self::Camellia256, - self::Twofish - => 256, + self::Aes192, self::Camellia192, self::TripleDes => 192, + self::Aes256, self::Camellia256, self::Twofish => 256, }; } @@ -116,7 +110,7 @@ public function keySize(): int */ public function keySizeInByte(): int { - return ($this->keySize() + 7) >> 3; + return $this->keySize() + 7 >> 3; } /** @@ -126,13 +120,9 @@ public function keySizeInByte(): int */ public function blockSize(): int { - return match($this) { + return match ($this) { self::Plaintext => 0, - self::Blowfish, - self::Idea, - self::TripleDes, - self::Cast5 - => 8, + self::Blowfish, self::Idea, self::TripleDes, self::Cast5 => 8, self::Aes128, self::Aes192, self::Aes256, @@ -150,9 +140,9 @@ public function blockSize(): int * @param string $mode - The cipher mode * @return BlockCipher */ - public function cipherEngine(string $mode = 'cfb'): BlockCipher + public function cipherEngine(string $mode = "cfb"): BlockCipher { - return match($this) { + return match ($this) { self::Plaintext => throw new \RuntimeException( 'Symmetric algorithm "Plaintext" is unsupported.' ), @@ -160,10 +150,11 @@ public function cipherEngine(string $mode = 'cfb'): BlockCipher self::TripleDes => new Crypt\TripleDES($mode), self::Cast5 => new Symmetric\CAST5($mode), self::Blowfish => new Crypt\Blowfish($mode), - self::Aes128, self::Aes192, self::Aes256 - => new Crypt\AES($mode), + self::Aes128, self::Aes192, self::Aes256 => new Crypt\AES($mode), self::Twofish => new Crypt\Twofish($mode), - self::Camellia128, self::Camellia192, self::Camellia256 + self::Camellia128, + self::Camellia192, + self::Camellia256 => new Symmetric\Camellia($mode), }; } @@ -175,33 +166,47 @@ public function cipherEngine(string $mode = 'cfb'): BlockCipher */ public function ecbCipherEngine(): Symmetric\EcbCipher { - return match($this) { + return match ($this) { self::Plaintext => throw new \InvalidArgumentException( 'Symmetric algorithm "Plaintext" is unsupported.' ), - self::Idea => new class extends Symmetric\IDEA implements Symmetric\EcbCipher { + self::Idea => new class extends Symmetric\IDEA implements + Symmetric\EcbCipher + { + use Symmetric\EcbCipherTrait; + }, + self::TripleDes => new class extends Crypt\TripleDES implements + Symmetric\EcbCipher + { + use Symmetric\EcbCipherTrait; + }, + self::Cast5 => new class extends Symmetric\CAST5 implements + Symmetric\EcbCipher + { use Symmetric\EcbCipherTrait; }, - self::TripleDes => new class extends Crypt\TripleDES implements Symmetric\EcbCipher { + self::Blowfish => new class extends Crypt\Blowfish implements + Symmetric\EcbCipher + { use Symmetric\EcbCipherTrait; }, - self::Cast5 => new class extends Symmetric\CAST5 implements Symmetric\EcbCipher { + self::Aes128, self::Aes192, self::Aes256 => new class + extends Crypt\AES + implements Symmetric\EcbCipher + { use Symmetric\EcbCipherTrait; }, - self::Blowfish => new class extends Crypt\Blowfish implements Symmetric\EcbCipher { + self::Twofish => new class extends Crypt\Twofish implements + Symmetric\EcbCipher + { use Symmetric\EcbCipherTrait; }, - self::Aes128, self::Aes192, self::Aes256 - => new class extends Crypt\AES implements Symmetric\EcbCipher { - use Symmetric\EcbCipherTrait; - }, - self::Twofish => new class extends Crypt\Twofish implements Symmetric\EcbCipher { + self::Camellia128, self::Camellia192, self::Camellia256 => new class + extends Symmetric\Camellia + implements Symmetric\EcbCipher + { use Symmetric\EcbCipherTrait; }, - self::Camellia128, self::Camellia192, self::Camellia256 - => new class extends Symmetric\Camellia implements Symmetric\EcbCipher { - use Symmetric\EcbCipherTrait; - }, }; } } diff --git a/src/Key/AbstractKey.php b/src/Key/AbstractKey.php index d73c699c..ba908c52 100644 --- a/src/Key/AbstractKey.php +++ b/src/Key/AbstractKey.php @@ -10,23 +10,14 @@ use DateTimeInterface; use OpenPGP\Common\Config; -use OpenPGP\Enum\{ - KeyAlgorithm, - PacketTag, - RevocationReasonTag, - SignatureType, -}; -use OpenPGP\Packet\{ - PacketList, - Padding, - Signature, -}; +use OpenPGP\Enum\{KeyAlgorithm, PacketTag, RevocationReasonTag, SignatureType}; +use OpenPGP\Packet\{PacketList, Padding, Signature}; use OpenPGP\Packet\Signature\{ EmbeddedSignature, Features, KeyExpirationTime, KeyFlags, - RevocationReason, + RevocationReason }; use OpenPGP\Type\{ KeyInterface, @@ -37,12 +28,9 @@ SubkeyInterface, SubkeyPacketInterface, UserIDPacketInterface, - UserInterface, -}; -use Psr\Log\{ - LoggerAwareTrait, - LoggerInterface, + UserInterface }; +use Psr\Log\{LoggerAwareTrait, LoggerInterface}; /** * Abstract OpenPGP key class @@ -98,14 +86,13 @@ protected function __construct( array $revocationSignatures = [], array $directSignatures = [], array $users = [], - array $subkeys = [], - ) - { + array $subkeys = [] + ) { $this->setRevocationSignatures($revocationSignatures) - ->setDirectSignatures($directSignatures) - ->setUsers($users) - ->setSubkeys($subkeys) - ->setLogger(Config::getLogger()); + ->setDirectSignatures($directSignatures) + ->setUsers($users) + ->setSubkeys($subkeys) + ->setLogger(Config::getLogger()); } /** @@ -116,13 +103,15 @@ public function getPacketList(): PacketListInterface $userPackets = []; foreach ($this->users as $user) { $userPackets = array_merge( - $userPackets, $user->getPacketList()->getPackets() + $userPackets, + $user->getPacketList()->getPackets() ); } $subkeyPackets = []; foreach ($this->subkeys as $subkey) { $subkeyPackets = array_merge( - $subkeyPackets, $subkey->getPacketList()->getPackets() + $subkeyPackets, + $subkey->getPacketList()->getPackets() ); } @@ -197,14 +186,11 @@ public function getLatestDirectSignature(): ?SignaturePacketInterface { if (!empty($this->directSignatures)) { $signatures = $this->directSignatures; - usort( - $signatures, - static function ($a, $b): int { - $aTime = $a->getCreationTime() ?? new \DateTime(); - $bTime = $b->getCreationTime() ?? new \DateTime(); - return $aTime->getTimestamp() - $bTime->getTimestamp(); - } - ); + usort($signatures, static function ($a, $b): int { + $aTime = $a->getCreationTime() ?? new \DateTime(); + $bTime = $b->getCreationTime() ?? new \DateTime(); + return $aTime->getTimestamp() - $bTime->getTimestamp(); + }); return array_pop($signatures); } return null; @@ -230,48 +216,52 @@ public function getSubkeys(): array * {@inheritdoc} */ public function getSigningKeyPacket( - string $keyID = '', ?DateTimeInterface $time = null - ): KeyPacketInterface - { + string $keyID = "", + ?DateTimeInterface $time = null + ): KeyPacketInterface { $subkeys = $this->subkeys; usort( $subkeys, - static fn ($a, $b): int => - (int) $b->getCreationTime()?->getTimestamp() - - (int) $a->getCreationTime()?->getTimestamp() + static fn($a, $b): int => (int) $b + ->getCreationTime() + ?->getTimestamp() - (int) $a->getCreationTime()?->getTimestamp() ); foreach ($subkeys as $subkey) { if (empty($keyID) || strcmp($keyID, $subkey->getKeyID()) === 0) { if (!$subkey->isSigningKey() || !$subkey->verify($time)) { continue; } - $signature = $subkey->getLatestBindingSignature()?->getEmbeddedSignature(); + $signature = $subkey + ->getLatestBindingSignature() + ?->getEmbeddedSignature(); if ($signature instanceof EmbeddedSignature) { // verify embedded signature - if ($signature->getSignature()->verify( - $subkey->getKeyPacket(), - implode([ - $this->getKeyPacket()->getSignBytes(), - $subkey->getKeyPacket()->getSignBytes(), - ]), - $time, - )) { + if ( + $signature + ->getSignature() + ->verify( + $subkey->getKeyPacket(), + implode([ + $this->getKeyPacket()->getSignBytes(), + $subkey->getKeyPacket()->getSignBytes(), + ]), + $time + ) + ) { return $subkey->getKeyPacket(); } - } - else { - throw new \RuntimeException( - 'Missing embedded signature.' - ); + } else { + throw new \RuntimeException("Missing embedded signature."); } } } - if (!$this->isSigningKey() || - (!empty($keyID) && strcmp($keyID, $this->getKeyID()) !== 0)) - { + if ( + !$this->isSigningKey() || + (!empty($keyID) && strcmp($keyID, $this->getKeyID()) !== 0) + ) { throw new \RuntimeException( - 'Could not find valid signing key packet.' + "Could not find valid signing key packet." ); } @@ -282,15 +272,15 @@ public function getSigningKeyPacket( * {@inheritdoc} */ public function getEncryptionKeyPacket( - string $keyID = '', ?DateTimeInterface $time = null - ): KeyPacketInterface - { + string $keyID = "", + ?DateTimeInterface $time = null + ): KeyPacketInterface { $subkeys = $this->subkeys; usort( $subkeys, - static fn ($a, $b): int => - (int) $b->getCreationTime()?->getTimestamp() - - (int) $a->getCreationTime()?->getTimestamp() + static fn($a, $b): int => (int) $b + ->getCreationTime() + ?->getTimestamp() - (int) $a->getCreationTime()?->getTimestamp() ); foreach ($subkeys as $subkey) { if (empty($keyID) || strcmp($keyID, $subkey->getKeyID()) === 0) { @@ -301,11 +291,12 @@ public function getEncryptionKeyPacket( } } - if (!$this->isEncryptionKey() || - (!empty($keyID) && strcmp($keyID, $this->getKeyID()) !== 0) + if ( + !$this->isEncryptionKey() || + (!empty($keyID) && strcmp($keyID, $this->getKeyID()) !== 0) ) { throw new \RuntimeException( - 'Could not find valid encryption key packet.' + "Could not find valid encryption key packet." ); } @@ -322,7 +313,8 @@ public function getExpirationTime(): ?DateTimeInterface $selfCertifications = []; foreach ($this->users as $user) { $selfCertifications = array_merge( - $selfCertifications, $user->getSelfCertifications() + $selfCertifications, + $user->getSelfCertifications() ); } if (!empty($selfCertifications)) { @@ -398,7 +390,7 @@ public function aeadSupported(): bool $user = $this->getPrimaryUser(); $features = $user?->getLatestSelfCertification()?->getFeatures(); } - return ($features instanceof Features) && $features->supportV2SEIPD(); + return $features instanceof Features && $features->supportV2SEIPD(); } /** @@ -407,33 +399,37 @@ public function aeadSupported(): bool public function isRevoked( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, - ): bool - { + ?DateTimeInterface $time = null + ): bool { if (!empty($this->revocationSignatures)) { $revocationKeyIDs = []; $keyID = $certificate?->getIssuerKeyID(); - $keyPacket = $verifyKey?->toPublic()->getSigningKeyPacket() ?? - $this->toPublic()->getSigningKeyPacket(); + $keyPacket = + $verifyKey?->toPublic()->getSigningKeyPacket() ?? + $this->toPublic()->getSigningKeyPacket(); foreach ($this->revocationSignatures as $signature) { - if (empty($keyID) || strcmp($keyID, $signature->getIssuerKeyID()) === 0) { - if ($signature->verify( - $keyPacket, - $this->keyPacket->getSignBytes(), - $time, - )) { + if ( + empty($keyID) || + strcmp($keyID, $signature->getIssuerKeyID()) === 0 + ) { + if ( + $signature->verify( + $keyPacket, + $this->keyPacket->getSignBytes(), + $time + ) + ) { $reason = $signature->getRevocationReason(); if ($reason instanceof RevocationReason) { $this->getLogger()->warning( - 'Primary key is revoked. Reason: {reason}', + "Primary key is revoked. Reason: {reason}", [ - 'reason' => $reason->getDescription(), - ], + "reason" => $reason->getDescription(), + ] ); - } - else { + } else { $this->getLogger()->warning( - 'Primary key is revoked.' + "Primary key is revoked." ); } return true; @@ -452,14 +448,11 @@ public function isRevoked( public function isCertified( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, - ): bool - { + ?DateTimeInterface $time = null + ): bool { $primaryUser = $this->getPrimaryUser(); if ($primaryUser instanceof UserInterface) { - return $primaryUser->isCertified( - $verifyKey, $certificate, $time - ); + return $primaryUser->isCertified($verifyKey, $certificate, $time); } return false; } @@ -468,18 +461,20 @@ public function isCertified( * {@inheritdoc} */ public function verify( - string $userID = '', ?DateTimeInterface $time = null - ): bool - { + string $userID = "", + ?DateTimeInterface $time = null + ): bool { if ($this->isRevoked(time: $time)) { return false; } foreach ($this->directSignatures as $signature) { - if (!$signature->verify( - $this->toPublic()->getKeyPacket(), - $this->keyPacket->getSignBytes(), - $time, - )) { + if ( + !$signature->verify( + $this->toPublic()->getKeyPacket(), + $this->keyPacket->getSignBytes(), + $time + ) + ) { return false; } } @@ -491,11 +486,11 @@ public function verify( } } $expirationTime = $this->getExpirationTime(); - if ($expirationTime instanceof DateTimeInterface && - $expirationTime->getTimestamp() < time()) { - $this->getLogger()->warning( - 'Primary key is expired.' - ); + if ( + $expirationTime instanceof DateTimeInterface && + $expirationTime->getTimestamp() < time() + ) { + $this->getLogger()->warning("Primary key is expired."); return false; } return true; @@ -506,11 +501,10 @@ public function verify( */ public function getPrimaryUser( ?DateTimeInterface $time = null - ): ?UserInterface - { + ): ?UserInterface { $users = array_filter( $this->getSortedPrimaryUsers(), - static fn ($user) => $user->verify($time) + static fn($user) => $user->verify($time) ); return array_pop($users); } @@ -519,11 +513,11 @@ public function getPrimaryUser( * {@inheritdoc} */ public function certifyBy( - PrivateKeyInterface $signKey, ?DateTimeInterface $time = null - ): self - { + PrivateKeyInterface $signKey, + ?DateTimeInterface $time = null + ): self { $users = []; - $certifedUserID = ''; + $certifedUserID = ""; $self = $this->clone(); $primaryUser = $self->getPrimaryUser(); if ($primaryUser instanceof UserInterface) { @@ -544,11 +538,10 @@ public function certifyBy( */ public function revokeBy( PrivateKeyInterface $signKey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return $this->clone()->setRevocationSignatures([ ...$this->getRevocationSignatures(), Signature::createKeyRevocation( @@ -556,7 +549,7 @@ public function revokeBy( $this->getKeyPacket(), $revocationReason, $reasonTag, - $time, + $time ), ]); } @@ -567,34 +560,32 @@ public function revokeBy( * @param array $signatures * @return DateTimeInterface */ - public static function getKeyExpiration(array $signatures): ?DateTimeInterface - { - usort( - $signatures, - static function ($a, $b): int { - $aTime = $a->getCreationTime() ?? new \DateTime(); - $bTime = $b->getCreationTime() ?? new \DateTime(); - return $bTime->getTimestamp() - $aTime->getTimestamp(); - } - ); + public static function getKeyExpiration( + array $signatures + ): ?DateTimeInterface { + usort($signatures, static function ($a, $b): int { + $aTime = $a->getCreationTime() ?? new \DateTime(); + $bTime = $b->getCreationTime() ?? new \DateTime(); + return $bTime->getTimestamp() - $aTime->getTimestamp(); + }); foreach ($signatures as $signature) { $keyExpirationTime = $signature->getKeyExpirationTime(); if ($keyExpirationTime instanceof KeyExpirationTime) { $expirationTime = $keyExpirationTime->getExpirationTime(); - $creationTime = $signature->getCreationTime() ?? new \DateTime(); + $creationTime = + $signature->getCreationTime() ?? new \DateTime(); $keyExpiry = $creationTime->setTimestamp( $creationTime->getTimestamp() + $expirationTime ); $signatureExpiry = $signature->getExpirationTime(); if (empty($signatureExpiry)) { return $keyExpiry; + } else { + return $keyExpiry < $signatureExpiry + ? $keyExpiry + : $signatureExpiry; } - else { - return $keyExpiry < $signatureExpiry ? - $keyExpiry : $signatureExpiry; - } - } - else { + } else { return $signature->getExpirationTime(); } } @@ -609,14 +600,14 @@ static function ($a, $b): int { */ protected function setRevocationSignatures( array $revocationSignatures - ): static - { - $this->revocationSignatures = array_values(array_filter( - $revocationSignatures, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isKeyRevocation(), - )); + ): static { + $this->revocationSignatures = array_values( + array_filter( + $revocationSignatures, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isKeyRevocation() + ) + ); return $this; } @@ -626,16 +617,15 @@ protected function setRevocationSignatures( * @param array $directSignatures * @return static */ - protected function setDirectSignatures( - array $directSignatures - ): static + protected function setDirectSignatures(array $directSignatures): static { - $this->directSignatures = array_values(array_filter( - $directSignatures, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isDirectKey(), - )); + $this->directSignatures = array_values( + array_filter( + $directSignatures, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isDirectKey() + ) + ); return $this; } @@ -649,18 +639,18 @@ protected function setUsers(array $users): static { $this->users = []; foreach ($users as $user) { - if ($user instanceof UserInterface && + if ( + $user instanceof UserInterface && $user->getMainKey() === $this ) { $this->users[] = $user; - } - elseif (is_array($user)) { + } elseif (is_array($user)) { $this->users[] = new User( $this, - $user['userIDPacket'], - $user['revocationSignatures'], - $user['selfCertifications'], - $user['otherCertifications'], + $user["userIDPacket"], + $user["revocationSignatures"], + $user["selfCertifications"], + $user["otherCertifications"] ); } } @@ -677,17 +667,17 @@ protected function setSubkeys(array $subkeys): static { $this->subkeys = []; foreach ($subkeys as $subkey) { - if ($subkey instanceof SubkeyInterface && + if ( + $subkey instanceof SubkeyInterface && $subkey->getMainKey() === $this ) { $this->subkeys[] = $subkey; - } - elseif (is_array($subkey)) { + } elseif (is_array($subkey)) { $this->subkeys[] = new Subkey( $this, - $subkey['keyPacket'], - $subkey['revocationSignatures'], - $subkey['bindingSignatures'], + $subkey["keyPacket"], + $subkey["revocationSignatures"], + $subkey["bindingSignatures"] ); } } @@ -710,7 +700,7 @@ protected function isSigningKey(): bool $user = array_pop($users); $keyFlags = $user?->getLatestSelfCertification()?->getKeyFlags(); } - if (($keyFlags instanceof KeyFlags) && !$keyFlags->isSignData()) { + if ($keyFlags instanceof KeyFlags && !$keyFlags->isSignData()) { return false; } return true; @@ -732,8 +722,12 @@ protected function isEncryptionKey(): bool $user = array_pop($users); $keyFlags = $user?->getLatestSelfCertification()?->getKeyFlags(); } - if (($keyFlags instanceof KeyFlags) && - !($keyFlags->isEncryptCommunication() || $keyFlags->isEncryptStorage()) + if ( + $keyFlags instanceof KeyFlags && + !( + $keyFlags->isEncryptCommunication() || + $keyFlags->isEncryptStorage() + ) ) { return false; } @@ -748,23 +742,21 @@ protected function isEncryptionKey(): bool protected function getSortedPrimaryUsers(): array { $users = $this->users; - usort( - $users, - static function ($a, $b) { - $aPrimary = (int) $a->isPrimary(); - $bPrimary = (int) $b->isPrimary(); - if ($aPrimary === $bPrimary) { - $aTime = $a->getLatestSelfCertification()?->getCreationTime() - ?? new \DateTime(); - $bTime = $b->getLatestSelfCertification()?->getCreationTime() - ?? new \DateTime(); - return $aTime->getTimestamp() - $bTime->getTimestamp(); - } - else { - return $aPrimary - $bPrimary; - } + usort($users, static function ($a, $b) { + $aPrimary = (int) $a->isPrimary(); + $bPrimary = (int) $b->isPrimary(); + if ($aPrimary === $bPrimary) { + $aTime = + $a->getLatestSelfCertification()?->getCreationTime() ?? + new \DateTime(); + $bTime = + $b->getLatestSelfCertification()?->getCreationTime() ?? + new \DateTime(); + return $aTime->getTimestamp() - $bTime->getTimestamp(); + } else { + return $aPrimary - $bPrimary; } - ); + }); return $users; } @@ -777,24 +769,30 @@ protected function clone(): static { $self = clone $this; - return $self->setUsers(array_map( - static fn ($user) => new User( - $self, - $user->getUserIDPacket(), - $user->getRevocationCertifications(), - $user->getSelfCertifications(), - $user->getOtherCertifications(), - ), - $this->users, - ))->setSubkeys(array_map( - static fn ($subkey) => new Subkey( - $self, - $subkey->getKeyPacket(), - $subkey->getRevocationSignatures(), - $subkey->getBindingSignatures(), - ), - $this->subkeys, - )); + return $self + ->setUsers( + array_map( + static fn($user) => new User( + $self, + $user->getUserIDPacket(), + $user->getRevocationCertifications(), + $user->getSelfCertifications(), + $user->getOtherCertifications() + ), + $this->users + ) + ) + ->setSubkeys( + array_map( + static fn($subkey) => new Subkey( + $self, + $subkey->getKeyPacket(), + $subkey->getRevocationSignatures(), + $subkey->getBindingSignatures() + ), + $this->subkeys + ) + ); } /** @@ -803,8 +801,9 @@ protected function clone(): static * @param PacketListInterface $packetList * @return array */ - protected static function packetListToKeyMap(PacketListInterface $packetList): array - { + protected static function packetListToKeyMap( + PacketListInterface $packetList + ): array { $revocationSignatures = $directSignatures = $users = $subkeys = []; $keyPacket = $primaryKeyID = null; @@ -814,7 +813,7 @@ protected static function packetListToKeyMap(PacketListInterface $packetList): a case PacketTag::SecretKey: if (!empty($keyPacket)) { throw new \RuntimeException( - 'Key block contains multiple keys.' + "Key block contains multiple keys." ); } if ($packet instanceof KeyPacketInterface) { @@ -826,9 +825,9 @@ protected static function packetListToKeyMap(PacketListInterface $packetList): a case PacketTag::SecretSubkey: if ($packet instanceof SubkeyPacketInterface) { $subkeys[] = [ - 'keyPacket' => $packet, - 'revocationSignatures' => [], - 'bindingSignatures' => [], + "keyPacket" => $packet, + "revocationSignatures" => [], + "bindingSignatures" => [], ]; } break; @@ -836,10 +835,10 @@ protected static function packetListToKeyMap(PacketListInterface $packetList): a case PacketTag::UserAttribute: if ($packet instanceof UserIDPacketInterface) { $users[] = [ - 'userIDPacket' => $packet, - 'revocationSignatures' => [], - 'selfCertifications' => [], - 'otherCertifications' => [], + "userIDPacket" => $packet, + "revocationSignatures" => [], + "selfCertifications" => [], + "otherCertifications" => [], ]; } break; @@ -852,11 +851,17 @@ protected static function packetListToKeyMap(PacketListInterface $packetList): a case SignatureType::CertPositive: $user = array_pop($users); if (!empty($user)) { - if (strcmp($packet->getIssuerKeyID(), $primaryKeyID) === 0) { - $user['selfCertifications'][] = $packet; - } - else { - $user['otherCertifications'][] = $packet; + if ( + strcmp( + $packet->getIssuerKeyID(), + $primaryKeyID + ) === 0 + ) { + $user["selfCertifications"][] = $packet; + } else { + $user[ + "otherCertifications" + ][] = $packet; } $users[] = $user; } @@ -864,24 +869,23 @@ protected static function packetListToKeyMap(PacketListInterface $packetList): a case SignatureType::CertRevocation: $user = array_pop($users); if (!empty($user)) { - $user['revocationSignatures'][] = $packet; + $user["revocationSignatures"][] = $packet; $users[] = $user; - } - else { + } else { $directSignatures[] = $packet; } break; case SignatureType::SubkeyBinding: $subkey = array_pop($subkeys); if (!empty($subkey)) { - $subkey['bindingSignatures'][] = $packet; + $subkey["bindingSignatures"][] = $packet; $subkeys[] = $subkey; } break; case SignatureType::SubkeyRevocation: $subkey = array_pop($subkeys); if (!empty($subkey)) { - $subkey['revocationSignatures'][] = $packet; + $subkey["revocationSignatures"][] = $packet; $subkeys[] = $subkey; } break; @@ -898,17 +902,15 @@ protected static function packetListToKeyMap(PacketListInterface $packetList): a } if (empty($keyPacket)) { - throw new \RuntimeException( - 'Key packet not found in packet list.' - ); + throw new \RuntimeException("Key packet not found in packet list."); } return [ - 'keyPacket' => $keyPacket, - 'revocationSignatures' => $revocationSignatures, - 'directSignatures' => $directSignatures, - 'users' => $users, - 'subkeys' => $subkeys, + "keyPacket" => $keyPacket, + "revocationSignatures" => $revocationSignatures, + "directSignatures" => $directSignatures, + "users" => $users, + "subkeys" => $subkeys, ]; } } diff --git a/src/Key/PrivateKey.php b/src/Key/PrivateKey.php index 650d58c8..64f5240f 100644 --- a/src/Key/PrivateKey.php +++ b/src/Key/PrivateKey.php @@ -9,10 +9,7 @@ namespace OpenPGP\Key; use DateTimeInterface; -use OpenPGP\Common\{ - Armor, - Config, -}; +use OpenPGP\Common\{Armor, Config}; use OpenPGP\Enum\{ AeadAlgorithm, ArmorType, @@ -20,20 +17,14 @@ KeyAlgorithm, KeyType, RevocationReasonTag, - RSAKeySize, -}; -use OpenPGP\Packet\{ - PacketList, - SecretKey, - SecretSubkey, - Signature, - UserID, + RSAKeySize }; +use OpenPGP\Packet\{PacketList, SecretKey, SecretSubkey, Signature, UserID}; use OpenPGP\Type\{ KeyInterface, PacketListInterface, PrivateKeyInterface, - SecretKeyPacketInterface, + SecretKeyPacketInterface }; /** @@ -60,15 +51,14 @@ public function __construct( array $revocationSignatures = [], array $directSignatures = [], array $users = [], - array $subkeys = [], - ) - { + array $subkeys = [] + ) { parent::__construct( $secretKeyPacket, $revocationSignatures, $directSignatures, $users, - $subkeys, + $subkeys ); } @@ -81,7 +71,9 @@ public function __construct( public static function fromArmored(string $armored): self { return self::fromBytes( - Armor::decode($armored)->assert(ArmorType::PrivateKey)->getData() + Armor::decode($armored) + ->assert(ArmorType::PrivateKey) + ->getData() ); } @@ -102,22 +94,18 @@ public static function fromBytes(string $bytes): self * @param PacketListInterface $packetList * @return self */ - public static function fromPacketList( - PacketListInterface $packetList - ): self + public static function fromPacketList(PacketListInterface $packetList): self { $keyMap = self::packetListToKeyMap($packetList); - if (!($keyMap['keyPacket'] instanceof SecretKeyPacketInterface)) { - throw new \RuntimeException( - 'Key packet is not secret key type.' - ); + if (!($keyMap["keyPacket"] instanceof SecretKeyPacketInterface)) { + throw new \RuntimeException("Key packet is not secret key type."); } return new self( - $keyMap['keyPacket'], - $keyMap['revocationSignatures'], - $keyMap['directSignatures'], - $keyMap['users'], - $keyMap['subkeys'], + $keyMap["keyPacket"], + $keyMap["revocationSignatures"], + $keyMap["directSignatures"], + $keyMap["users"], + $keyMap["subkeys"] ); } @@ -144,23 +132,24 @@ public static function generate( CurveOid $curve = CurveOid::Secp521r1, int $keyExpiry = 0, bool $signOnly = false, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { if (empty($userIDs) || empty($passphrase)) { throw new \InvalidArgumentException( - 'UserIDs and passphrase are required for key generation.', + "UserIDs and passphrase are required for key generation." ); } $subkeyCurve = $curve; switch ($type) { case KeyType::Ecc: - if ($curve === CurveOid::Ed25519 || $curve === CurveOid::Curve25519) { + if ( + $curve === CurveOid::Ed25519 || + $curve === CurveOid::Curve25519 + ) { $keyAlgorithm = KeyAlgorithm::EdDsaLegacy; $curve = CurveOid::Ed25519; $subkeyCurve = CurveOid::Curve25519; - } - else { + } else { $keyAlgorithm = KeyAlgorithm::EcDsa; } $subkeyAlgorithm = KeyAlgorithm::Ecdh; @@ -183,14 +172,16 @@ public static function generate( $keyAlgorithm, $rsaKeySize, $curve, - $time, + $time ); $v6Key = $secretKey->getVersion() === 6; - $aead = ($v6Key && Config::aeadProtect()) ? - Config::getPreferredAead() : null; + $aead = + $v6Key && Config::aeadProtect() ? Config::getPreferredAead() : null; $secretKey = $secretKey->encrypt( - $passphrase, Config::getPreferredSymmetric(), $aead + $passphrase, + Config::getPreferredSymmetric(), + $aead ); $packets = [$secretKey]; @@ -199,7 +190,7 @@ public static function generate( $packets[] = Signature::createDirectKeySignature( $secretKey, $keyExpiry, - $time, + $time ); } @@ -213,7 +204,7 @@ public static function generate( $packet, $index === 0, $keyExpiry, - $time, + $time ); $index++; } @@ -223,10 +214,8 @@ public static function generate( $subkeyAlgorithm, $rsaKeySize, $subkeyCurve, - $time, - )->encrypt( - $passphrase, Config::getPreferredSymmetric(), $aead - ); + $time + )->encrypt($passphrase, Config::getPreferredSymmetric(), $aead); // Wrap secret subkey with binding signature $packets[] = $secretSubkey; $packets[] = Signature::createSubkeyBinding( @@ -234,7 +223,7 @@ public static function generate( $secretSubkey, $keyExpiry, false, - $time, + $time ); } @@ -248,7 +237,7 @@ public function armor(): string { return Armor::encode( ArmorType::PrivateKey, - $this->getPacketList()->encode(), + $this->getPacketList()->encode() ); } @@ -261,8 +250,7 @@ public function toPublic(): KeyInterface foreach ($this->getPackets() as $packet) { if ($packet instanceof SecretKeyPacketInterface) { $packets[] = $packet->getPublicKey(); - } - else { + } else { $packets[] = $packet; } } @@ -305,20 +293,18 @@ public function getSecretKeyPacket(): SecretKeyPacketInterface * {@inheritdoc} */ public function getDecryptionKeyPackets( - string $keyID = '', ?DateTimeInterface $time = null - ): array - { + string $keyID = "", + ?DateTimeInterface $time = null + ): array { if (!$this->verify(time: $time)) { - throw new \RuntimeException( - 'Primary key is invalid.' - ); + throw new \RuntimeException("Primary key is invalid."); } $subkeys = $this->getSubkeys(); usort( $subkeys, - static fn ($a, $b): int => - (int) $b->getCreationTime()?->getTimestamp() - - (int) $a->getCreationTime()?->getTimestamp() + static fn($a, $b): int => (int) $b + ->getCreationTime() + ?->getTimestamp() - (int) $a->getCreationTime()?->getTimestamp() ); $keyPackets = []; @@ -343,17 +329,16 @@ public function getDecryptionKeyPackets( */ public function encrypt( string $passphrase, - array $subkeyPassphrases = [], - ): self - { + array $subkeyPassphrases = [] + ): self { if (empty($passphrase)) { throw new \InvalidArgumentException( - 'Passphrase is required for key encryption.' + "Passphrase is required for key encryption." ); } if (!$this->isDecrypted()) { throw new \RuntimeException( - 'Private key must be decrypted before encrypting.' + "Private key must be decrypted before encrypting." ); } @@ -364,21 +349,25 @@ public function encrypt( $privateKey = new self( $this->secretKeyPacket->encrypt( - $passphrase, Config::getPreferredSymmetric(), $aead + $passphrase, + Config::getPreferredSymmetric(), + $aead ), $this->getRevocationSignatures(), - $this->getDirectSignatures(), + $this->getDirectSignatures() + ); + $privateKey->setUsers( + array_map( + static fn($user) => new User( + $privateKey, + $user->getUserIDPacket(), + $user->getRevocationCertifications(), + $user->getSelfCertifications(), + $user->getOtherCertifications() + ), + $this->getUsers() + ) ); - $privateKey->setUsers(array_map( - static fn ($user) => new User( - $privateKey, - $user->getUserIDPacket(), - $user->getRevocationCertifications(), - $user->getSelfCertifications(), - $user->getOtherCertifications(), - ), - $this->getUsers(), - )); $subkeys = []; foreach ($this->getSubkeys() as $key => $subkey) { @@ -386,14 +375,16 @@ public function encrypt( if ($keyPacket instanceof SecretKeyPacketInterface) { $subkeyPassphrase = $subkeyPassphrases[$key] ?? $passphrase; $keyPacket = $keyPacket->encrypt( - $subkeyPassphrase, Config::getPreferredSymmetric(), $aead + $subkeyPassphrase, + Config::getPreferredSymmetric(), + $aead ); } $subkeys[] = new Subkey( $privateKey, $keyPacket, $subkey->getRevocationSignatures(), - $subkey->getBindingSignatures(), + $subkey->getBindingSignatures() ); } return $privateKey->setSubkeys($subkeys); @@ -404,30 +395,31 @@ public function encrypt( */ public function decrypt( string $passphrase, - array $subkeyPassphrases = [], - ): self - { + array $subkeyPassphrases = [] + ): self { if (empty($passphrase)) { throw new \InvalidArgumentException( - 'Passphrase is required for key decryption.' + "Passphrase is required for key decryption." ); } $secretKey = $this->secretKeyPacket->decrypt($passphrase); $privateKey = new self( $secretKey, $this->getRevocationSignatures(), - $this->getDirectSignatures(), + $this->getDirectSignatures() + ); + $privateKey->setUsers( + array_map( + static fn($user) => new User( + $privateKey, + $user->getUserIDPacket(), + $user->getRevocationCertifications(), + $user->getSelfCertifications(), + $user->getOtherCertifications() + ), + $this->getUsers() + ) ); - $privateKey->setUsers(array_map( - static fn ($user) => new User( - $privateKey, - $user->getUserIDPacket(), - $user->getRevocationCertifications(), - $user->getSelfCertifications(), - $user->getOtherCertifications(), - ), - $this->getUsers(), - )); $subkeys = []; foreach ($this->getSubkeys() as $key => $subkey) { @@ -440,7 +432,7 @@ public function decrypt( $privateKey, $keyPacket, $subkey->getRevocationSignatures(), - $subkey->getBindingSignatures(), + $subkey->getBindingSignatures() ); } return $privateKey->setSubkeys($subkeys); @@ -452,9 +444,7 @@ public function decrypt( public function addUsers(array $userIDs): self { if (empty($userIDs)) { - throw new \InvalidArgumentException( - 'User IDs are required.', - ); + throw new \InvalidArgumentException("User IDs are required."); } $self = $this->clone(); @@ -467,9 +457,9 @@ public function addUsers(array $userIDs): self selfCertifications: [ Signature::createSelfCertificate( $self->getSecretKeyPacket(), - $packet, + $packet ), - ], + ] ); } return $self->setUsers($users); @@ -485,12 +475,11 @@ public function addSubkey( CurveOid $curve = CurveOid::Secp521r1, int $keyExpiry = 0, bool $forSigning = false, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { if (empty($passphrase)) { throw new \InvalidArgumentException( - 'Passphrase is required for key generation.', + "Passphrase is required for key generation." ); } @@ -505,7 +494,7 @@ public function addSubkey( $keyAlgorithm, $rsaKeySize, $curve, - $time, + $time )->encrypt($passphrase, Config::getPreferredSymmetric(), $aead); $subkeys[] = new Subkey( $self, @@ -516,9 +505,9 @@ public function addSubkey( $secretSubkey, $keyExpiry, $forSigning, - $time, + $time ), - ], + ] ); return $self->setSubkeys($subkeys); } @@ -527,9 +516,9 @@ public function addSubkey( * {@inheritdoc} */ public function certifyKey( - KeyInterface $key, ?DateTimeInterface $time = null - ): KeyInterface - { + KeyInterface $key, + ?DateTimeInterface $time = null + ): KeyInterface { return $key->certifyBy($this, $time); } @@ -538,14 +527,11 @@ public function certifyKey( */ public function revokeKey( KeyInterface $key, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): KeyInterface - { - return $key->revokeBy( - $this, $revocationReason, $reasonTag, $time - ); + ?DateTimeInterface $time = null + ): KeyInterface { + return $key->revokeBy($this, $revocationReason, $reasonTag, $time); } /** @@ -553,18 +539,20 @@ public function revokeKey( */ public function revokeUser( string $userID, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $self = $this->clone(); $users = $self->getUsers(); foreach ($users as $key => $user) { if (strcmp($user->getUserID(), $userID) === 0) { $users[$key] = $user->revokeBy( - $self, $revocationReason, $reasonTag, $time + $self, + $revocationReason, + $reasonTag, + $time ); } } @@ -576,17 +564,19 @@ public function revokeUser( */ public function revokeSubkey( string $keyID, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $self = $this->clone(); $subkeys = $self->getSubkeys(); foreach ($subkeys as $key => $subkey) { if (strcmp($subkey->getKeyID(), $keyID) === 0) { $subkeys[$key] = $subkey->revokeBy( - $self, $revocationReason, $reasonTag, $time + $self, + $revocationReason, + $reasonTag, + $time ); } } diff --git a/src/Key/PublicKey.php b/src/Key/PublicKey.php index 63f79575..c79bf0ca 100644 --- a/src/Key/PublicKey.php +++ b/src/Key/PublicKey.php @@ -9,16 +9,13 @@ namespace OpenPGP\Key; use OpenPGP\Common\Armor; -use OpenPGP\Enum\{ - ArmorType, - PacketTag, -}; +use OpenPGP\Enum\{ArmorType, PacketTag}; use OpenPGP\Packet\PacketList; use OpenPGP\Type\{ KeyInterface, PacketListInterface, PublicKeyInterface, - PublicKeyPacketInterface, + PublicKeyPacketInterface }; /** @@ -45,15 +42,14 @@ public function __construct( array $revocationSignatures = [], array $directSignatures = [], array $users = [], - array $subkeys = [], - ) - { + array $subkeys = [] + ) { parent::__construct( $publicKeyPacket, $revocationSignatures, $directSignatures, $users, - $subkeys, + $subkeys ); } @@ -66,9 +62,9 @@ public function __construct( * @return array */ public static function readPublicKeys( - string $data, bool $armored = true - ): array - { + string $data, + bool $armored = true + ): array { if ($armored) { $armor = Armor::decode($data)->assert(ArmorType::PublicKey); $data = $armor->getData(); @@ -83,8 +79,7 @@ public static function readPublicKeys( $publicKeys[] = self::fromPacketList( $packetList->slice($indexes[$i], $length) ); - } - else { + } else { $publicKeys[] = self::fromPacketList( $packetList->slice($indexes[$i]) ); @@ -101,17 +96,18 @@ public static function readPublicKeys( */ public static function armorPublicKeys(array $keys): string { - $keyData = implode(array_map( - static fn ($key) => $key->toPublic()->getPacketList()->encode(), - array_filter( - $keys, - static fn ($key) => $key instanceof KeyInterface, + $keyData = implode( + array_map( + static fn($key) => $key->toPublic()->getPacketList()->encode(), + array_filter( + $keys, + static fn($key) => $key instanceof KeyInterface + ) ) - )); - return empty($keyData) ? '' : Armor::encode( - ArmorType::PublicKey, - $keyData, ); + return empty($keyData) + ? "" + : Armor::encode(ArmorType::PublicKey, $keyData); } /** @@ -123,7 +119,9 @@ public static function armorPublicKeys(array $keys): string public static function fromArmored(string $armored): self { return self::fromBytes( - Armor::decode($armored)->assert(ArmorType::PublicKey)->getData() + Armor::decode($armored) + ->assert(ArmorType::PublicKey) + ->getData() ); } @@ -144,22 +142,18 @@ public static function fromBytes(string $bytes): self * @param PacketListInterface $packetList * @return self */ - public static function fromPacketList( - PacketListInterface $packetList - ): self + public static function fromPacketList(PacketListInterface $packetList): self { $keyMap = self::packetListToKeyMap($packetList); - if (!($keyMap['keyPacket'] instanceof PublicKeyPacketInterface)) { - throw new \RuntimeException( - 'Key packet is not public key type.' - ); + if (!($keyMap["keyPacket"] instanceof PublicKeyPacketInterface)) { + throw new \RuntimeException("Key packet is not public key type."); } return new self( - $keyMap['keyPacket'], - $keyMap['revocationSignatures'], - $keyMap['directSignatures'], - $keyMap['users'], - $keyMap['subkeys'], + $keyMap["keyPacket"], + $keyMap["revocationSignatures"], + $keyMap["directSignatures"], + $keyMap["users"], + $keyMap["subkeys"] ); } @@ -178,7 +172,7 @@ public function armor(): string { return Armor::encode( ArmorType::PublicKey, - $this->getPacketList()->encode(), + $this->getPacketList()->encode() ); } diff --git a/src/Key/Subkey.php b/src/Key/Subkey.php index 6e16d931..1aba00e9 100644 --- a/src/Key/Subkey.php +++ b/src/Key/Subkey.php @@ -9,25 +9,16 @@ namespace OpenPGP\Key; use DateTimeInterface; -use OpenPGP\Enum\{ - KeyAlgorithm, - RevocationReasonTag, -}; -use OpenPGP\Packet\{ - PacketList, - Signature, -}; -use OpenPGP\Packet\Signature\{ - KeyFlags, - RevocationReason, -}; +use OpenPGP\Enum\{KeyAlgorithm, RevocationReasonTag}; +use OpenPGP\Packet\{PacketList, Signature}; +use OpenPGP\Packet\Signature\{KeyFlags, RevocationReason}; use OpenPGP\Type\{ KeyInterface, PacketListInterface, PrivateKeyInterface, SignaturePacketInterface, SubkeyInterface, - SubkeyPacketInterface, + SubkeyPacketInterface }; /** @@ -66,21 +57,22 @@ public function __construct( private readonly KeyInterface $mainKey, private readonly SubkeyPacketInterface $keyPacket, array $revocationSignatures = [], - array $bindingSignatures = [], - ) - { - $this->revocationSignatures = array_values(array_filter( - $revocationSignatures, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isSubkeyRevocation(), - )); - $this->bindingSignatures = array_values(array_filter( - $bindingSignatures, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isSubkeyBinding(), - )); + array $bindingSignatures = [] + ) { + $this->revocationSignatures = array_values( + array_filter( + $revocationSignatures, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isSubkeyRevocation() + ) + ); + $this->bindingSignatures = array_values( + array_filter( + $bindingSignatures, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isSubkeyBinding() + ) + ); } /** @@ -114,14 +106,11 @@ public function getLatestBindingSignature(): ?SignaturePacketInterface { if (!empty($this->bindingSignatures)) { $signatures = $this->bindingSignatures; - usort( - $signatures, - static function ($a, $b): int { - $aTime = $a->getCreationTime() ?? new \DateTime(); - $bTime = $b->getCreationTime() ?? new \DateTime(); - return $aTime->getTimestamp() - $bTime->getTimestamp(); - } - ); + usort($signatures, static function ($a, $b): int { + $aTime = $a->getCreationTime() ?? new \DateTime(); + $bTime = $b->getCreationTime() ?? new \DateTime(); + return $aTime->getTimestamp() - $bTime->getTimestamp(); + }); return array_pop($signatures); } return null; @@ -200,7 +189,7 @@ public function isSigningKey(): bool return false; } $keyFlags = $this->getLatestBindingSignature()?->getKeyFlags(); - if (($keyFlags instanceof KeyFlags) && !$keyFlags->isSignData()) { + if ($keyFlags instanceof KeyFlags && !$keyFlags->isSignData()) { return false; } return true; @@ -215,8 +204,12 @@ public function isEncryptionKey(): bool return false; } $keyFlags = $this->getLatestBindingSignature()?->getKeyFlags(); - if (($keyFlags instanceof KeyFlags) && - !($keyFlags->isEncryptCommunication() || $keyFlags->isEncryptStorage()) + if ( + $keyFlags instanceof KeyFlags && + !( + $keyFlags->isEncryptCommunication() || + $keyFlags->isEncryptStorage() + ) ) { return false; } @@ -229,37 +222,43 @@ public function isEncryptionKey(): bool public function isRevoked( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, - ): bool - { + ?DateTimeInterface $time = null + ): bool { if (!empty($this->revocationSignatures)) { $revocationKeyIDs = []; $keyID = $certificate?->getIssuerKeyID(); - $keyPacket = $verifyKey?->toPublic()->getSigningKeyPacket() ?? - $this->mainKey->toPublic()->getSigningKeyPacket(); + $keyPacket = + $verifyKey?->toPublic()->getSigningKeyPacket() ?? + $this->mainKey->toPublic()->getSigningKeyPacket(); foreach ($this->revocationSignatures as $signature) { - if (empty($keyID) || strcmp($keyID, $signature->getIssuerKeyID()) === 0) { - if ($signature->verify( - $keyPacket, - implode([ - $this->mainKey->getKeyPacket()->getSignBytes(), - $this->keyPacket->getSignBytes(), - ]), - $time, - )) { + if ( + empty($keyID) || + strcmp($keyID, $signature->getIssuerKeyID()) === 0 + ) { + if ( + $signature->verify( + $keyPacket, + implode([ + $this->mainKey->getKeyPacket()->getSignBytes(), + $this->keyPacket->getSignBytes(), + ]), + $time + ) + ) { $reason = $signature->getRevocationReason(); if ($reason instanceof RevocationReason) { - $this->mainKey->getLogger()->warning( - 'Subkey is revoked. Reason: {reason}', - [ - 'reason' => $reason->getDescription(), - ], - ); - } - else { - $this->mainKey->getLogger()->warning( - 'Subkey is revoked.' - ); + $this->mainKey + ->getLogger() + ->warning( + "Subkey is revoked. Reason: {reason}", + [ + "reason" => $reason->getDescription(), + ] + ); + } else { + $this->mainKey + ->getLogger() + ->warning("Subkey is revoked."); } return true; } @@ -281,14 +280,16 @@ public function verify(?DateTimeInterface $time = null): bool } $keyPacket = $this->mainKey->toPublic()->getSigningKeyPacket(); foreach ($this->bindingSignatures as $signature) { - if (!$signature->verify( - $keyPacket, - implode([ - $this->mainKey->getKeyPacket()->getSignBytes(), - $this->keyPacket->getSignBytes(), - ]), - $time, - )) { + if ( + !$signature->verify( + $keyPacket, + implode([ + $this->mainKey->getKeyPacket()->getSignBytes(), + $this->keyPacket->getSignBytes(), + ]), + $time + ) + ) { return false; } } @@ -300,11 +301,10 @@ public function verify(?DateTimeInterface $time = null): bool */ public function revokeBy( PrivateKeyInterface $signKey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return new self( $this->mainKey, $this->keyPacket, @@ -316,10 +316,10 @@ public function revokeBy( $this->keyPacket, $revocationReason, $reasonTag, - $time, + $time ), ], - $this->bindingSignatures, + $this->bindingSignatures ); } diff --git a/src/Key/User.php b/src/Key/User.php index 71e2ec12..02aa1fc6 100644 --- a/src/Key/User.php +++ b/src/Key/User.php @@ -10,11 +10,7 @@ use DateTimeInterface; use OpenPGP\Enum\RevocationReasonTag; -use OpenPGP\Packet\{ - PacketList, - Signature, - UserID, -}; +use OpenPGP\Packet\{PacketList, Signature, UserID}; use OpenPGP\Packet\Signature\RevocationReason; use OpenPGP\Type\{ KeyInterface, @@ -22,7 +18,7 @@ PrivateKeyInterface, SignaturePacketInterface, UserIDPacketInterface, - UserInterface, + UserInterface }; /** @@ -70,27 +66,29 @@ public function __construct( private readonly UserIDPacketInterface $userIDPacket, array $revocationSignatures = [], array $selfCertifications = [], - array $otherCertifications = [], - ) - { - $this->revocationSignatures = array_values(array_filter( - $revocationSignatures, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isCertRevocation(), - )); - $this->selfCertifications = array_values(array_filter( - $selfCertifications, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isCertification(), - )); - $this->otherCertifications = array_values(array_filter( - $otherCertifications, - static fn ($signature) => - $signature instanceof SignaturePacketInterface && - $signature->isCertification(), - )); + array $otherCertifications = [] + ) { + $this->revocationSignatures = array_values( + array_filter( + $revocationSignatures, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isCertRevocation() + ) + ); + $this->selfCertifications = array_values( + array_filter( + $selfCertifications, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isCertification() + ) + ); + $this->otherCertifications = array_values( + array_filter( + $otherCertifications, + static fn($signature) => $signature instanceof + SignaturePacketInterface && $signature->isCertification() + ) + ); } /** @@ -140,14 +138,11 @@ public function getLatestSelfCertification(): ?SignaturePacketInterface { if (!empty($this->selfCertifications)) { $signatures = $this->selfCertifications; - usort( - $signatures, - static function ($a, $b): int { - $aTime = $a->getCreationTime() ?? new \DateTime(); - $bTime = $b->getCreationTime() ?? new \DateTime(); - return $aTime->getTimestamp() - $bTime->getTimestamp(); - } - ); + usort($signatures, static function ($a, $b): int { + $aTime = $a->getCreationTime() ?? new \DateTime(); + $bTime = $b->getCreationTime() ?? new \DateTime(); + return $aTime->getTimestamp() - $bTime->getTimestamp(); + }); return array_pop($signatures); } return null; @@ -158,8 +153,9 @@ static function ($a, $b): int { */ public function getUserID(): string { - return ($this->userIDPacket instanceof UserID) ? - $this->userIDPacket->getUserID() : ''; + return $this->userIDPacket instanceof UserID + ? $this->userIDPacket->getUserID() + : ""; } /** @@ -177,37 +173,40 @@ public function isPrimary(): bool public function isRevoked( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, - ): bool - { + ?DateTimeInterface $time = null + ): bool { if (!empty($this->revocationSignatures)) { $revocationKeyIDs = []; $keyID = $certificate?->getIssuerKeyID(); - $keyPacket = $verifyKey?->toPublic()->getSigningKeyPacket() ?? - $this->mainKey->toPublic()->getSigningKeyPacket(); + $keyPacket = + $verifyKey?->toPublic()->getSigningKeyPacket() ?? + $this->mainKey->toPublic()->getSigningKeyPacket(); foreach ($this->revocationSignatures as $signature) { - if (empty($keyID) || strcmp($keyID, $signature->getIssuerKeyID()) === 0) { - if ($signature->verify( - $keyPacket, - implode([ - $this->mainKey->getKeyPacket()->getSignBytes(), - $this->userIDPacket->getSignBytes(), - ]), - $time, - )) { + if ( + empty($keyID) || + strcmp($keyID, $signature->getIssuerKeyID()) === 0 + ) { + if ( + $signature->verify( + $keyPacket, + implode([ + $this->mainKey->getKeyPacket()->getSignBytes(), + $this->userIDPacket->getSignBytes(), + ]), + $time + ) + ) { $reason = $signature->getRevocationReason(); if ($reason instanceof RevocationReason) { - $this->mainKey->getLogger()->warning( - 'User is revoked. Reason: {reason}', - [ - 'reason' => $reason->getDescription(), - ], - ); - } - else { - $this->mainKey->getLogger()->warning( - 'User is revoked.' - ); + $this->mainKey + ->getLogger() + ->warning("User is revoked. Reason: {reason}", [ + "reason" => $reason->getDescription(), + ]); + } else { + $this->mainKey + ->getLogger() + ->warning("User is revoked."); } return true; } @@ -225,25 +224,30 @@ public function isRevoked( public function isCertified( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, - ): bool - { + ?DateTimeInterface $time = null + ): bool { if ($this->isRevoked($verifyKey, time: $time)) { return false; } $keyID = $certificate?->getIssuerKeyID(); - $keyPacket = $verifyKey?->toPublic()->getSigningKeyPacket() ?? - $this->mainKey->toPublic()->getSigningKeyPacket(); + $keyPacket = + $verifyKey?->toPublic()->getSigningKeyPacket() ?? + $this->mainKey->toPublic()->getSigningKeyPacket(); foreach ($this->otherCertifications as $signature) { - if (empty($keyID) || strcmp($keyID, $signature->getIssuerKeyID()) === 0) { - if ($signature->verify( - $keyPacket, - implode([ - $this->mainKey->getKeyPacket()->getSignBytes(), - $this->userIDPacket->getSignBytes(), - ]), - $time, - )) { + if ( + empty($keyID) || + strcmp($keyID, $signature->getIssuerKeyID()) === 0 + ) { + if ( + $signature->verify( + $keyPacket, + implode([ + $this->mainKey->getKeyPacket()->getSignBytes(), + $this->userIDPacket->getSignBytes(), + ]), + $time + ) + ) { return true; } } @@ -261,14 +265,16 @@ public function verify(?DateTimeInterface $time = null): bool } $keyPacket = $this->mainKey->toPublic()->getSigningKeyPacket(); foreach ($this->selfCertifications as $signature) { - if (!$signature->verify( - $keyPacket, - implode([ - $this->mainKey->getKeyPacket()->getSignBytes(), - $this->userIDPacket->getSignBytes(), - ]), - $time, - )) { + if ( + !$signature->verify( + $keyPacket, + implode([ + $this->mainKey->getKeyPacket()->getSignBytes(), + $this->userIDPacket->getSignBytes(), + ]), + $time + ) + ) { return false; } } @@ -279,12 +285,15 @@ public function verify(?DateTimeInterface $time = null): bool * {@inheritdoc} */ public function certifyBy( - PrivateKeyInterface $signKey, ?DateTimeInterface $time = null - ): self - { - if (strcmp($signKey->getFingerprint(), - $this->mainKey->getFingerprint()) === 0) - { + PrivateKeyInterface $signKey, + ?DateTimeInterface $time = null + ): self { + if ( + strcmp( + $signKey->getFingerprint(), + $this->mainKey->getFingerprint() + ) === 0 + ) { throw new \RuntimeException( 'The user\'s own key can only be used for self-certifications.' ); @@ -300,9 +309,9 @@ public function certifyBy( $signKey->getSecretKeyPacket(), $this->mainKey->getKeyPacket(), $this->userIDPacket, - $time, + $time ), - ], + ] ); } @@ -311,11 +320,10 @@ public function certifyBy( */ public function revokeBy( PrivateKeyInterface $signKey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return new self( $this->mainKey, $this->userIDPacket, @@ -327,11 +335,11 @@ public function revokeBy( $this->userIDPacket, $revocationReason, $reasonTag, - $time, + $time ), ], $this->selfCertifications, - $this->otherCertifications, + $this->otherCertifications ); } diff --git a/src/Message/AbstractMessage.php b/src/Message/AbstractMessage.php index 8dacbff7..1c0aeb4e 100644 --- a/src/Message/AbstractMessage.php +++ b/src/Message/AbstractMessage.php @@ -8,21 +8,14 @@ namespace OpenPGP\Message; -use OpenPGP\Common\{ - Armor, - Config, -}; +use OpenPGP\Common\{Armor, Config}; use OpenPGP\Enum\ArmorType; use OpenPGP\Type\{ ArmorableInterface, PacketContainerInterface, - PacketListInterface, -}; -use Psr\Log\{ - LoggerAwareInterface, - LoggerAwareTrait, - LoggerInterface, + PacketListInterface }; +use Psr\Log\{LoggerAwareInterface, LoggerAwareTrait, LoggerInterface}; /** * OpenPGP abstract message class @@ -31,7 +24,10 @@ * @category Message * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -abstract class AbstractMessage implements ArmorableInterface, LoggerAwareInterface, PacketContainerInterface +abstract class AbstractMessage implements + ArmorableInterface, + LoggerAwareInterface, + PacketContainerInterface { use LoggerAwareTrait; @@ -43,8 +39,7 @@ abstract class AbstractMessage implements ArmorableInterface, LoggerAwareInterfa */ public function __construct( private readonly PacketListInterface $packetList - ) - { + ) { $this->setLogger(Config::getLogger()); } @@ -55,7 +50,7 @@ public function armor(): string { return Armor::encode( ArmorType::Message, - $this->getPacketList()->encode(), + $this->getPacketList()->encode() ); } diff --git a/src/Message/CleartextMessage.php b/src/Message/CleartextMessage.php index 46813e70..99f66628 100644 --- a/src/Message/CleartextMessage.php +++ b/src/Message/CleartextMessage.php @@ -10,18 +10,14 @@ use DateTimeInterface; use OpenPGP\Common\Helper; -use OpenPGP\Packet\{ - LiteralData, - PacketList, -}; +use OpenPGP\Packet\{LiteralData, PacketList}; use OpenPGP\Packet\Signature as SignaturePacket; use OpenPGP\Type\{ CleartextMessageInterface, - MessageInterface, NotationDataInterface, PrivateKeyInterface, SignatureInterface, - SignedMessageInterface, + SignedMessageInterface }; /** @@ -43,9 +39,7 @@ class CleartextMessage implements CleartextMessageInterface * @param string $text * @return self */ - public function __construct( - private readonly string $text - ) + public function __construct(private readonly string $text) { } @@ -65,9 +59,7 @@ public function getNormalizeText(): string // Remove trailing whitespace and // normalize EOL to canonical form $text = Helper::removeTrailingSpaces($this->text); - return preg_replace( - Helper::EOL_PATTERN, Helper::CRLF, $text - ) ?? $text; + return preg_replace(Helper::EOL_PATTERN, Helper::CRLF, $text) ?? $text; } /** @@ -77,16 +69,15 @@ public function sign( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): SignedMessageInterface - { + ?DateTimeInterface $time = null + ): SignedMessageInterface { return new SignedMessage( $this->getText(), $this->createSignature( $signingKeys, $recipients, $notationData, - $time, + $time ) ); } @@ -98,14 +89,13 @@ public function signDetached( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): SignatureInterface - { + ?DateTimeInterface $time = null + ): SignatureInterface { return $this->createSignature( $signingKeys, $recipients, $notationData, - $time, + $time ); } @@ -115,12 +105,9 @@ public function signDetached( public function verifyDetached( array $verificationKeys, SignatureInterface $signature, - ?DateTimeInterface $time = null, - ): array - { - return $signature->verifyCleartext( - $verificationKeys, $this, $time - ); + ?DateTimeInterface $time = null + ): array { + return $signature->verifyCleartext($verificationKeys, $this, $time); } /** @@ -135,25 +122,28 @@ private function createSignature( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): SignatureInterface - { + ?DateTimeInterface $time = null + ): SignatureInterface { $signingKeys = array_filter( $signingKeys, - static fn ($key) => $key instanceof PrivateKeyInterface + static fn($key) => $key instanceof PrivateKeyInterface ); if (empty($signingKeys)) { - throw new \InvalidArgumentException('No signing keys provided.'); + throw new \InvalidArgumentException("No signing keys provided."); } - return new Signature(new PacketList(array_map( - fn ($key) => SignaturePacket::createLiteralData( - $key->getSecretKeyPacket(), - LiteralData::fromText($this->getText()), - $recipients, - $notationData, - $time, - ), - $signingKeys, - ))); + return new Signature( + new PacketList( + array_map( + fn($key) => SignaturePacket::createLiteralData( + $key->getSecretKeyPacket(), + LiteralData::fromText($this->getText()), + $recipients, + $notationData, + $time + ), + $signingKeys + ) + ) + ); } } diff --git a/src/Message/EncryptedMessage.php b/src/Message/EncryptedMessage.php index b4cad63c..db2b38f6 100644 --- a/src/Message/EncryptedMessage.php +++ b/src/Message/EncryptedMessage.php @@ -13,7 +13,7 @@ use OpenPGP\Packet\{ PacketList, PublicKeyEncryptedSessionKey, - SymEncryptedSessionKey, + SymEncryptedSessionKey }; use OpenPGP\Type\{ EncryptedDataPacketInterface, @@ -21,7 +21,7 @@ LiteralMessageInterface, PacketListInterface, PrivateKeyInterface, - SessionKeyInterface, + SessionKeyInterface }; /** @@ -31,7 +31,8 @@ * @category Message * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class EncryptedMessage extends AbstractMessage implements EncryptedMessageInterface +class EncryptedMessage extends AbstractMessage implements + EncryptedMessageInterface { private ?SessionKeyInterface $sessionKey = null; @@ -44,7 +45,9 @@ class EncryptedMessage extends AbstractMessage implements EncryptedMessageInterf public static function fromArmored(string $armored): self { return self::fromBytes( - Armor::decode($armored)->assert(ArmorType::Message)->getData() + Armor::decode($armored) + ->assert(ArmorType::Message) + ->getData() ); } @@ -82,25 +85,27 @@ public function getSessionKey(): ?SessionKeyInterface */ public function decrypt( array $decryptionKeys = [], - array $passwords = [], - ): LiteralMessageInterface - { + array $passwords = [] + ): LiteralMessageInterface { $decryptionKeys = array_filter( $decryptionKeys, - static fn ($key) => $key instanceof PrivateKeyInterface, + static fn($key) => $key instanceof PrivateKeyInterface ); if (empty($decryptionKeys) && empty($passwords)) { throw new \InvalidArgumentException( - 'No decryption keys or passwords provided.' + "No decryption keys or passwords provided." ); } return new LiteralMessage( - $this->getEncryptedPacket()->decryptWithSessionKey( - $this->sessionKey = $this->decryptSessionKey( - $decryptionKeys, $passwords + $this->getEncryptedPacket() + ->decryptWithSessionKey( + $this->sessionKey = $this->decryptSessionKey( + $decryptionKeys, + $passwords + ) ) - )->getPacketList() + ->getPacketList() ); } @@ -112,47 +117,47 @@ public function decrypt( * @return SessionKeyInterface */ private function decryptSessionKey( - array $decryptionKeys, array $passwords - ): SessionKeyInterface - { + array $decryptionKeys, + array $passwords + ): SessionKeyInterface { $sessionKeys = []; if (!empty($passwords)) { - $this->getLogger()->warning( - 'Decrypt session keys by passwords.' - ); + $this->getLogger()->warning("Decrypt session keys by passwords."); $skeskPacketList = $this->getPacketList()->whereType( SymEncryptedSessionKey::class ); foreach ($skeskPacketList as $skesk) { foreach ($passwords as $password) { try { - $sessionKeys[] = $skesk->decrypt($password)->getSessionKey(); + $sessionKeys[] = $skesk + ->decrypt($password) + ->getSessionKey(); break; - } - catch (\Throwable $e) { + } catch (\Throwable $e) { $this->getLogger()->error($e); } } } } if (empty($sessionKeys) && !empty($decryptionKeys)) { - $this->getLogger()->warning( - 'Decrypt session keys by public keys.' - ); + $this->getLogger()->warning("Decrypt session keys by public keys."); $pkeskPacketList = $this->getPacketList()->whereType( PublicKeyEncryptedSessionKey::class ); foreach ($pkeskPacketList as $pkesk) { foreach ($decryptionKeys as $key) { $keyPacket = $key->getEncryptionKeyPacket(); - if ($pkesk->getKeyAlgorithm() === $keyPacket->getKeyAlgorithm() && + if ( + $pkesk->getKeyAlgorithm() === + $keyPacket->getKeyAlgorithm() && strcmp($pkesk->getKeyID(), $keyPacket->getKeyID()) === 0 ) { try { - $sessionKeys[] = $pkesk->decrypt($keyPacket)->getSessionKey(); + $sessionKeys[] = $pkesk + ->decrypt($keyPacket) + ->getSessionKey(); break; - } - catch (\Throwable $e) { + } catch (\Throwable $e) { $this->getLogger()->error($e); } } @@ -161,7 +166,7 @@ private function decryptSessionKey( } if (empty($sessionKeys)) { - throw new \RuntimeException('Session key decryption failed.'); + throw new \RuntimeException("Session key decryption failed."); } return array_pop($sessionKeys); @@ -175,13 +180,12 @@ private function decryptSessionKey( */ private static function assertEncryptedPacket( PacketListInterface $packetList - ): EncryptedDataPacketInterface - { - $encryptedPackets = $packetList->whereType( - EncryptedDataPacketInterface::class - )->getPackets(); + ): EncryptedDataPacketInterface { + $encryptedPackets = $packetList + ->whereType(EncryptedDataPacketInterface::class) + ->getPackets(); if (empty($encryptedPackets)) { - throw new \RuntimeException('No encrypted data packets found.'); + throw new \RuntimeException("No encrypted data packets found."); } return array_pop($encryptedPackets); } diff --git a/src/Message/LiteralMessage.php b/src/Message/LiteralMessage.php index 9ad5cf68..18c8b547 100644 --- a/src/Message/LiteralMessage.php +++ b/src/Message/LiteralMessage.php @@ -9,15 +9,12 @@ namespace OpenPGP\Message; use DateTimeInterface; -use OpenPGP\Common\{ - Armor, - Config, -}; +use OpenPGP\Common\{Armor, Config}; use OpenPGP\Enum\{ ArmorType, CompressionAlgorithm, LiteralFormat, - SymmetricAlgorithm, + SymmetricAlgorithm }; use OpenPGP\Packet\Signature as SignaturePacket; use OpenPGP\Packet\{ @@ -28,7 +25,7 @@ Padding, PublicKeyEncryptedSessionKey, SymEncryptedIntegrityProtectedData, - SymEncryptedSessionKey, + SymEncryptedSessionKey }; use OpenPGP\Packet\Key\SessionKey; use OpenPGP\Type\{ @@ -40,7 +37,7 @@ PrivateKeyInterface, SignatureInterface, SignaturePacketInterface, - SignedMessageInterface, + SignedMessageInterface }; /** @@ -50,7 +47,9 @@ * @category Message * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class LiteralMessage extends AbstractMessage implements LiteralMessageInterface, SignedMessageInterface +class LiteralMessage extends AbstractMessage implements + LiteralMessageInterface, + SignedMessageInterface { /** * Read message from armored string @@ -61,7 +60,9 @@ class LiteralMessage extends AbstractMessage implements LiteralMessageInterface, public static function fromArmored(string $armored): self { return self::fromBytes( - Armor::decode($armored)->assert(ArmorType::Message)->getData() + Armor::decode($armored) + ->assert(ArmorType::Message) + ->getData() ); } @@ -86,13 +87,19 @@ public static function fromBytes(string $bytes): self */ public static function fromLiteralData( string $literalData, - string $filename = '', - ?DateTimeInterface $time = null, - ): self - { - return new self(new PacketList([new LiteralData( - $literalData, LiteralFormat::Binary, $filename, $time - )])); + string $filename = "", + ?DateTimeInterface $time = null + ): self { + return new self( + new PacketList([ + new LiteralData( + $literalData, + LiteralFormat::Binary, + $filename, + $time + ), + ]) + ); } /** @@ -102,10 +109,10 @@ public function getLiteralData(): LiteralDataInterface { $packets = array_filter( self::unwrapCompressed($this->getPackets()), - static fn ($packet) => $packet instanceof LiteralDataInterface, + static fn($packet) => $packet instanceof LiteralDataInterface ); if (empty($packets)) { - throw new \RuntimeException('No literal data in packet list.'); + throw new \RuntimeException("No literal data in packet list."); } return array_pop($packets); } @@ -115,10 +122,15 @@ public function getLiteralData(): LiteralDataInterface */ public function getSignature(): SignatureInterface { - return new Signature(new PacketList(array_filter( - self::unwrapCompressed($this->getPackets()), - static fn ($packet) => $packet instanceof SignaturePacketInterface, - ))); + return new Signature( + new PacketList( + array_filter( + self::unwrapCompressed($this->getPackets()), + static fn($packet) => $packet instanceof + SignaturePacketInterface + ) + ) + ); } /** @@ -128,35 +140,39 @@ public function sign( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $signaturePackets = [ ...array_filter( self::unwrapCompressed($this->getPackets()), - static fn ($packet) => $packet instanceof SignaturePacketInterface, + static fn($packet) => $packet instanceof + SignaturePacketInterface ), ...$this->createSignature( - $signingKeys, $recipients, $notationData, $time + $signingKeys, + $recipients, + $notationData, + $time )->getPackets(), ]; $index = 0; - $opsPackets = array_reverse(array_map( - static function ($signature) use (&$index) { + $opsPackets = array_reverse( + array_map(static function ($signature) use (&$index) { return OnePassSignature::fromSignature( $signature, - (($index++) === 0) ? 1 : 0 + $index++ === 0 ? 1 : 0 ); - }, - $signaturePackets - )); // innermost OPS refers to the first signature packet + }, $signaturePackets) + ); // innermost OPS refers to the first signature packet - return new self(new PacketList([ - ...$opsPackets, - $this->getLiteralData(), - ...$signaturePackets, - ])); + return new self( + new PacketList([ + ...$opsPackets, + $this->getLiteralData(), + ...$signaturePackets, + ]) + ); } /** @@ -166,14 +182,13 @@ public function signDetached( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): SignatureInterface - { + ?DateTimeInterface $time = null + ): SignatureInterface { return $this->createSignature( $signingKeys, $recipients, $notationData, - $time, + $time ); } @@ -181,13 +196,13 @@ public function signDetached( * {@inheritdoc} */ public function verify( - array $verificationKeys, ?DateTimeInterface $time = null - ): array - { + array $verificationKeys, + ?DateTimeInterface $time = null + ): array { return $this->getSignature()->verify( $verificationKeys, $this->getLiteralData(), - $time, + $time ); } @@ -197,11 +212,12 @@ public function verify( public function verifyDetached( array $verificationKeys, SignatureInterface $signature, - ?DateTimeInterface $time = null, - ): array - { + ?DateTimeInterface $time = null + ): array { return $signature->verify( - $verificationKeys, $this->getLiteralData(), $time + $verificationKeys, + $this->getLiteralData(), + $time ); } @@ -211,16 +227,15 @@ public function verifyDetached( public function encrypt( array $encryptionKeys = [], array $passwords = [], - ?SymmetricAlgorithm $symmetric = null, - ): EncryptedMessageInterface - { + ?SymmetricAlgorithm $symmetric = null + ): EncryptedMessageInterface { $encryptionKeys = array_filter( $encryptionKeys, - static fn ($key) => $key instanceof KeyInterface, + static fn($key) => $key instanceof KeyInterface ); if (empty($encryptionKeys) && empty($passwords)) { throw new \InvalidArgumentException( - 'No encryption keys or passwords provided.' + "No encryption keys or passwords provided." ); } @@ -234,53 +249,69 @@ public function encrypt( $addPadding = true; } } - $aead = ($aeadSupported && Config::aeadProtect()) ? - Config::getPreferredAead() : null; + $aead = + $aeadSupported && Config::aeadProtect() + ? Config::getPreferredAead() + : null; $sessionKey = SessionKey::produceKey( $symmetric ?? Config::getPreferredSymmetric() ); - $packetList = ($addPadding || !empty($aead)) ? new PacketList([ - ...$this->getPackets(), - Padding::createPadding(random_int( - Config::PADDING_MIN, Config::PADDING_MAX) - ), - ]) : $this->getPacketList(); + $packetList = + $addPadding || !empty($aead) + ? new PacketList([ + ...$this->getPackets(), + Padding::createPadding( + random_int(Config::PADDING_MIN, Config::PADDING_MAX) + ), + ]) + : $this->getPacketList(); - return new EncryptedMessage(new PacketList([ - ...array_map( - static fn ($key) => PublicKeyEncryptedSessionKey::encryptSessionKey( - $key->toPublic()->getEncryptionKeyPacket(), + return new EncryptedMessage( + new PacketList([ + ...array_map( + static fn( + $key + ) => PublicKeyEncryptedSessionKey::encryptSessionKey( + $key->toPublic()->getEncryptionKeyPacket(), + $sessionKey + ), + $encryptionKeys + ), // pkesk packets + ...array_map( + static fn( + $password + ) => SymEncryptedSessionKey::encryptSessionKey( + $password, + $sessionKey, + $symmetric ?? Config::getPreferredSymmetric(), + $aead + ), + $passwords + ), // skesk packets + SymEncryptedIntegrityProtectedData::encryptPacketsWithSessionKey( $sessionKey, - ), - $encryptionKeys, - ), // pkesk packets - ...array_map( - static fn ($password) => SymEncryptedSessionKey::encryptSessionKey( - $password, - $sessionKey, - $symmetric ?? Config::getPreferredSymmetric(), - $aead, - ), - $passwords, - ), // skesk packets - SymEncryptedIntegrityProtectedData::encryptPacketsWithSessionKey( - $sessionKey, $packetList, $aead - ), // seipd packet - ])); + $packetList, + $aead + ), // seipd packet + ]) + ); } /** * {@inheritdoc} */ - public function compress( - ?CompressionAlgorithm $algorithm = null - ): self + public function compress(?CompressionAlgorithm $algorithm = null): self { $algorithm = $algorithm ?? Config::getPreferredCompression(); if ($algorithm !== CompressionAlgorithm::Uncompressed) { - return new self(new PacketList([ - CompressedData::fromPackets($this->getPackets(), $algorithm), - ])); + return new self( + new PacketList([ + CompressedData::fromPackets( + $this->getPackets(), + $algorithm + ), + ]) + ); } return $this; } @@ -298,26 +329,29 @@ private function createSignature( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): SignatureInterface - { + ?DateTimeInterface $time = null + ): SignatureInterface { $signingKeys = array_filter( $signingKeys, - static fn ($key) => $key instanceof PrivateKeyInterface, + static fn($key) => $key instanceof PrivateKeyInterface ); if (empty($signingKeys)) { - throw new \InvalidArgumentException('No signing keys provided.'); + throw new \InvalidArgumentException("No signing keys provided."); } - return new Signature(new PacketList(array_map( - fn ($key) => SignaturePacket::createLiteralData( - $key->getSecretKeyPacket(), - $this->getLiteralData(), - $recipients, - $notationData, - $time, - ), - $signingKeys, - ))); + return new Signature( + new PacketList( + array_map( + fn($key) => SignaturePacket::createLiteralData( + $key->getSecretKeyPacket(), + $this->getLiteralData(), + $recipients, + $notationData, + $time + ), + $signingKeys + ) + ) + ); } /** @@ -330,10 +364,9 @@ private static function unwrapCompressed(array $packets): array { $compressedPackets = array_filter( $packets, - static fn ($packet) => $packet instanceof CompressedData, + static fn($packet) => $packet instanceof CompressedData ); - return array_pop( - $compressedPackets - )?->getPacketList()->getPackets() ?? $packets; + return array_pop($compressedPackets)?->getPacketList()->getPackets() ?? + $packets; } } diff --git a/src/Message/Signature.php b/src/Message/Signature.php index 70b31231..943be6ae 100644 --- a/src/Message/Signature.php +++ b/src/Message/Signature.php @@ -9,15 +9,9 @@ namespace OpenPGP\Message; use DateTimeInterface; -use OpenPGP\Common\{ - Armor, - Config, -}; +use OpenPGP\Common\{Armor, Config}; use OpenPGP\Enum\ArmorType; -use OpenPGP\Packet\{ - LiteralData, - PacketList, -}; +use OpenPGP\Packet\{LiteralData, PacketList}; use OpenPGP\Type\{ CleartextMessageInterface, KeyInterface, @@ -25,7 +19,7 @@ LiteralDataInterface, PacketListInterface, SignatureInterface, - SignaturePacketInterface, + SignaturePacketInterface }; /** @@ -47,9 +41,7 @@ class Signature implements SignatureInterface * @param PacketListInterface $packetList * @return self */ - public function __construct( - PacketListInterface $packetList - ) + public function __construct(PacketListInterface $packetList) { $this->packetList = $packetList->whereType( SignaturePacketInterface::class @@ -65,7 +57,9 @@ public function __construct( public static function fromArmored(string $armored): self { return self::fromBytes( - Armor::decode($armored)->assert(ArmorType::Signature)->getData() + Armor::decode($armored) + ->assert(ArmorType::Signature) + ->getData() ); } @@ -86,8 +80,8 @@ public static function fromBytes(string $bytes): self public function getSigningKeyIDs(bool $toHex = false): array { return array_map( - static fn ($packet): string => $packet->getIssuerKeyID($toHex), - $this->getPackets(), + static fn($packet): string => $packet->getIssuerKeyID($toHex), + $this->getPackets() ); } @@ -97,39 +91,36 @@ public function getSigningKeyIDs(bool $toHex = false): array public function verify( array $verificationKeys, LiteralDataInterface $literalData, - ?DateTimeInterface $time = null, - ): array - { + ?DateTimeInterface $time = null + ): array { $verificationKeys = array_filter( $verificationKeys, - static fn ($key): bool => $key instanceof KeyInterface, + static fn($key): bool => $key instanceof KeyInterface ); if (empty($verificationKeys)) { - Config::getLogger()->warning('No verification keys provided.'); + Config::getLogger()->warning("No verification keys provided."); } $verifications = []; foreach ($this->packetList as $packet) { foreach ($verificationKeys as $key) { $keyPacket = null; try { - $keyPacket = $key->toPublic()->getSigningKeyPacket( - $packet->getIssuerKeyID() - ); - } - catch (\Throwable $e) { + $keyPacket = $key + ->toPublic() + ->getSigningKeyPacket($packet->getIssuerKeyID()); + } catch (\Throwable $e) { Config::getLogger()->error($e->getMessage()); } if ($keyPacket instanceof KeyPacketInterface) { $isVerified = false; - $verificationError = ''; + $verificationError = ""; try { $isVerified = $packet->verify( $keyPacket, $literalData->getSignBytes(), - $time, + $time ); - } - catch (\Throwable $e) { + } catch (\Throwable $e) { $verificationError = $e->getMessage(); Config::getLogger()->error($verificationError); } @@ -138,7 +129,7 @@ public function verify( $keyPacket->getKeyID(), $packet, $isVerified, - $verificationError, + $verificationError ); } } @@ -152,13 +143,12 @@ public function verify( public function verifyCleartext( array $verificationKeys, CleartextMessageInterface $cleartext, - ?DateTimeInterface $time = null, - ): array - { + ?DateTimeInterface $time = null + ): array { return $this->verify( $verificationKeys, LiteralData::fromText($cleartext->getText()), - $time, + $time ); } @@ -169,7 +159,7 @@ public function armor(): string { return Armor::encode( ArmorType::Signature, - $this->getPacketList()->encode(), + $this->getPacketList()->encode() ); } diff --git a/src/Message/SignedMessage.php b/src/Message/SignedMessage.php index 05cc6e34..31c43c9a 100644 --- a/src/Message/SignedMessage.php +++ b/src/Message/SignedMessage.php @@ -12,10 +12,7 @@ use OpenPGP\Common\Armor; use OpenPGP\Enum\ArmorType; use OpenPGP\Packet\PacketList; -use OpenPGP\Type\{ - SignatureInterface, - SignedMessageInterface, -}; +use OpenPGP\Type\{SignatureInterface, SignedMessageInterface}; /** * OpenPGP signed message class @@ -38,9 +35,8 @@ class SignedMessage extends CleartextMessage implements SignedMessageInterface */ public function __construct( string $text, - private readonly SignatureInterface $signature, - ) - { + private readonly SignatureInterface $signature + ) { parent::__construct($text); } @@ -55,7 +51,7 @@ public static function fromArmored(string $armored): self $armor = Armor::decode($armored)->assert(ArmorType::SignedMessage); return new self( $armor->getText(), - new Signature(PacketList::decode($armor->getData())), + new Signature(PacketList::decode($armor->getData())) ); } @@ -77,11 +73,11 @@ public function armor(): string $this->signature->getPacketList()->encode(), $this->getText(), array_map( - static fn ($packet) => strtoupper( - str_replace('_', '-', $packet->getHashAlgorithm()->name) + static fn($packet) => strtoupper( + str_replace("_", "-", $packet->getHashAlgorithm()->name) ), - $this->signature->getPackets(), - ), + $this->signature->getPackets() + ) ); } @@ -89,11 +85,13 @@ public function armor(): string * {@inheritdoc} */ public function verify( - array $verificationKeys, ?DateTimeInterface $time = null - ): array - { + array $verificationKeys, + ?DateTimeInterface $time = null + ): array { return $this->signature->verifyCleartext( - $verificationKeys, $this, $time + $verificationKeys, + $this, + $time ); } diff --git a/src/Message/Verification.php b/src/Message/Verification.php index fed49eb2..ae8c2488 100644 --- a/src/Message/Verification.php +++ b/src/Message/Verification.php @@ -8,10 +8,7 @@ namespace OpenPGP\Message; -use OpenPGP\Type\{ - SignaturePacketInterface, - VerificationInterface, -}; +use OpenPGP\Type\{SignaturePacketInterface, VerificationInterface}; use phpseclib3\Common\Functions\Strings; /** @@ -36,9 +33,8 @@ public function __construct( private readonly string $keyID, private readonly SignaturePacketInterface $signaturePacket, private readonly bool $isVerified = false, - private readonly string $verificationError = '', - ) - { + private readonly string $verificationError = "" + ) { } /** diff --git a/src/OpenPGP.php b/src/OpenPGP.php index 262d7b34..72134683 100644 --- a/src/OpenPGP.php +++ b/src/OpenPGP.php @@ -32,7 +32,7 @@ final class OpenPGP * @param \DateTimeInterface $time * @return Type\PrivateKeyInterface */ - public static function generateKey( + public static function generateKey( array $userIDs, string $passphrase, Enum\KeyType $type = Enum\KeyType::Rsa, diff --git a/src/Packet/AbstractPacket.php b/src/Packet/AbstractPacket.php index 569daeb2..35eae69e 100644 --- a/src/Packet/AbstractPacket.php +++ b/src/Packet/AbstractPacket.php @@ -8,18 +8,11 @@ namespace OpenPGP\Packet; -use OpenPGP\Common\{ - Config, - Helper, -}; +use OpenPGP\Common\{Config, Helper}; use OpenPGP\Enum\PacketTag; use OpenPGP\Type\PacketInterface; use phpseclib3\Common\Functions\Strings; -use Psr\Log\{ - LoggerAwareInterface, - LoggerAwareTrait, - LoggerInterface, -}; +use Psr\Log\{LoggerAwareInterface, LoggerAwareTrait, LoggerInterface}; /** * Abstract packet class @@ -72,8 +65,7 @@ public function encode(): string { if (in_array($this->tag, self::PARTIAL_SUPPORTING, true)) { return $this->partialEncode(); - } - else { + } else { $bytes = $this->toBytes(); return implode([ chr(0xc0 | $this->tag->value), @@ -115,10 +107,8 @@ private function partialEncode(): string $partialData = []; while (strlen($data) >= self::PARTIAL_MIN_SIZE) { - $maxSize = strlen( - substr($data, 0, self::PARTIAL_MAX_SIZE) - ); - $powerOf2 = min(log($maxSize) / M_LN2 | 0, 30); + $maxSize = strlen(substr($data, 0, self::PARTIAL_MAX_SIZE)); + $powerOf2 = min((log($maxSize) / M_LN2) | 0, 30); $chunkSize = 1 << $powerOf2; $partialData[] = implode([ @@ -126,14 +116,8 @@ private function partialEncode(): string Strings::shift($data, $chunkSize), ]); } - $partialData[] = implode([ - Helper::simpleLength(strlen($data)), - $data, - ]); + $partialData[] = implode([Helper::simpleLength(strlen($data)), $data]); - return implode([ - chr(0xc0 | $this->tag->value), - ...$partialData, - ]); + return implode([chr(0xc0 | $this->tag->value), ...$partialData]); } } diff --git a/src/Packet/AeadEncryptedData.php b/src/Packet/AeadEncryptedData.php index 28d85158..40f61e73 100644 --- a/src/Packet/AeadEncryptedData.php +++ b/src/Packet/AeadEncryptedData.php @@ -8,19 +8,12 @@ namespace OpenPGP\Packet; -use OpenPGP\Common\{ - Config, - Helper, -}; -use OpenPGP\Enum\{ - AeadAlgorithm, - PacketTag, - SymmetricAlgorithm, -}; +use OpenPGP\Common\{Config, Helper}; +use OpenPGP\Enum\{AeadAlgorithm, PacketTag, SymmetricAlgorithm}; use OpenPGP\Type\{ AeadEncryptedDataPacketInterface, - SessionKeyInterface, PacketListInterface, + SessionKeyInterface }; use phpseclib3\Common\Functions\Strings; use phpseclib3\Crypt\Random; @@ -35,7 +28,8 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class AeadEncryptedData extends AbstractPacket implements AeadEncryptedDataPacketInterface +class AeadEncryptedData extends AbstractPacket implements + AeadEncryptedDataPacketInterface { use AeadEncryptedDataTrait, EncryptedDataTrait; @@ -59,10 +53,9 @@ public function __construct( private readonly AeadAlgorithm $aead, private readonly int $chunkSize, private readonly string $iv, - private readonly string $encrypted = '', - private readonly ?PacketListInterface $packetList = null, - ) - { + private readonly string $encrypted = "", + private readonly ?PacketListInterface $packetList = null + ) { parent::__construct(PacketTag::AeadEncryptedData); $this->version = self::VERSION; } @@ -78,8 +71,8 @@ public static function fromBytes(string $bytes): self $version = ord($bytes[$offset++]); if ($version !== self::VERSION) { throw new \InvalidArgumentException( - "Version $version of the AEPD is not supported.", - ); + "Version $version of the AEPD is not supported." + ); } $symmetric = SymmetricAlgorithm::from(ord($bytes[$offset++])); @@ -89,13 +82,7 @@ public static function fromBytes(string $bytes): self $offset += $aead->ivLength(); $encrypted = substr($bytes, $offset); - return new self( - $symmetric, - $aead, - $chunkSize, - $iv, - $encrypted, - ); + return new self($symmetric, $aead, $chunkSize, $iv, $encrypted); } /** @@ -109,21 +96,15 @@ public static function fromBytes(string $bytes): self public static function encryptPackets( string $key, PacketListInterface $packetList, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ): self - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ): self { Helper::assertSymmetric($symmetric); $aead = Config::getPreferredAead(); $chunkSize = Config::getAeadChunkSize(); $iv = Random::string($aead->ivLength()); - $encryptor = new self( - $symmetric, - $aead, - $chunkSize, - $iv, - ); + $encryptor = new self($symmetric, $aead, $chunkSize, $iv); return new self( $symmetric, @@ -131,7 +112,7 @@ public static function encryptPackets( $chunkSize, $iv, $encryptor->crypt(self::AEAD_ENCRYPT, $key, $packetList->encode()), - $packetList, + $packetList ); } @@ -144,13 +125,12 @@ public static function encryptPackets( */ public static function encryptPacketsWithSessionKey( SessionKeyInterface $sessionKey, - PacketListInterface $packetList, - ): self - { + PacketListInterface $packetList + ): self { return self::encryptPackets( $sessionKey->getEncryptionKey(), $packetList, - $sessionKey->getSymmetric(), + $sessionKey->getSymmetric() ); } @@ -184,19 +164,20 @@ public function getIV(): string */ public function decrypt( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ): self - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ): self { if ($this->packetList instanceof PacketListInterface) { return $this; - } - else { + } else { $length = strlen($this->encrypted); $data = substr( - $this->encrypted, 0, $length - $this->aead->tagLength() + $this->encrypted, + 0, + $length - $this->aead->tagLength() ); $authTag = substr( - $this->encrypted, $length - $this->aead->tagLength() + $this->encrypted, + $length - $this->aead->tagLength() ); return new self( @@ -205,9 +186,9 @@ public function decrypt( $this->chunkSize, $this->iv, $this->encrypted, - PacketList::decode($this->crypt( - self::AEAD_DECRYPT, $key, $data, $authTag - )), + PacketList::decode( + $this->crypt(self::AEAD_DECRYPT, $key, $data, $authTag) + ) ); } } @@ -222,32 +203,40 @@ public function decrypt( * @return string */ private function crypt( - string $fn, string $key, string $data, string $finalChunk = '' - ): string - { + string $fn, + string $key, + string $data, + string $finalChunk = "" + ): string { $cipher = $this->aead->cipherEngine($key, $this->symmetric); $dataLength = strlen($data); $tagLength = $fn === self::AEAD_DECRYPT ? $this->aead->tagLength() : 0; // chunkSize = ((uint64_t)1 << (c + 6)) - $chunkSize = (1 << ($this->chunkSize + 6)) + $tagLength; + $chunkSize = (1 << $this->chunkSize + 6) + $tagLength; $crypted = []; $aDataBytes = substr_replace( - str_repeat(self::ZERO_CHAR, 13), $this->getAData(), 0, 5 + str_repeat(self::ZERO_CHAR, 13), + $this->getAData(), + 0, + 5 ); $ciBytes = substr($aDataBytes, 5, 8); - for ($chunkIndex = 0; $chunkIndex === 0 || strlen($data) > 0;) { + for ($chunkIndex = 0; $chunkIndex === 0 || strlen($data) > 0; ) { // Take a chunk of `data`, en/decrypt it, // and shift `data` to the next chunk. $crypted[] = $cipher->$fn( Strings::shift($data, $chunkSize), $cipher->getNonce($this->iv, $ciBytes), - $aDataBytes, + $aDataBytes ); $aDataBytes = substr_replace( - $aDataBytes, pack('N', ++$chunkIndex), 9, 4 + $aDataBytes, + pack("N", ++$chunkIndex), + 9, + 4 ); $ciBytes = substr($aDataBytes, 5, 8); } @@ -256,16 +245,23 @@ private function crypt( // chunk to get the final authentication tag or validate that final // authentication tag. $aDataTagBytes = substr_replace( - str_repeat(self::ZERO_CHAR, 21), $aDataBytes, 0, 13 + str_repeat(self::ZERO_CHAR, 21), + $aDataBytes, + 0, + 13 ); - $cryptedLength = $dataLength - $tagLength * (int) ceil($dataLength / $chunkSize); + $cryptedLength = + $dataLength - $tagLength * (int) ceil($dataLength / $chunkSize); $aDataTagBytes = substr_replace( - $aDataTagBytes, pack('N', $cryptedLength), 17, 4 + $aDataTagBytes, + pack("N", $cryptedLength), + 17, + 4 ); $crypted[] = $cipher->$fn( $finalChunk, $cipher->getNonce($this->iv, $ciBytes), - $aDataTagBytes, + $aDataTagBytes ); return implode($crypted); diff --git a/src/Packet/AeadEncryptedDataTrait.php b/src/Packet/AeadEncryptedDataTrait.php index 075684ca..0d7d72f7 100644 --- a/src/Packet/AeadEncryptedDataTrait.php +++ b/src/Packet/AeadEncryptedDataTrait.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet; -use OpenPGP\Enum\{ - AeadAlgorithm, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{AeadAlgorithm, SymmetricAlgorithm}; /** * Aead encrypted data packet trait diff --git a/src/Packet/CompressedData.php b/src/Packet/CompressedData.php index 3b2c9d7a..ce648297 100644 --- a/src/Packet/CompressedData.php +++ b/src/Packet/CompressedData.php @@ -39,9 +39,8 @@ class CompressedData extends AbstractPacket public function __construct( private readonly string $compressed, private readonly PacketListInterface $packetList, - private readonly Algorithm $algorithm = Algorithm::Uncompressed, - ) - { + private readonly Algorithm $algorithm = Algorithm::Uncompressed + ) { parent::__construct(PacketTag::CompressedData); } @@ -55,7 +54,7 @@ public static function fromBytes(string $bytes): self return new self( $compressed, self::decompress($compressed, $algorithm), - $algorithm, + $algorithm ); } @@ -68,13 +67,12 @@ public static function fromBytes(string $bytes): self */ public static function fromPacketList( PacketListInterface $packetList, - Algorithm $algorithm = Algorithm::Uncompressed, - ): self - { + Algorithm $algorithm = Algorithm::Uncompressed + ): self { return new self( self::compress($packetList, $algorithm), $packetList, - $algorithm, + $algorithm ); } @@ -87,9 +85,8 @@ public static function fromPacketList( */ public static function fromPackets( array $packets, - Algorithm $algorithm = Algorithm::Uncompressed, - ) - { + Algorithm $algorithm = Algorithm::Uncompressed + ) { return self::fromPacketList(new PacketList($packets), $algorithm); } @@ -128,29 +125,32 @@ public function getAlgorithm(): Algorithm */ public function toBytes(): string { - return implode([ - chr($this->algorithm->value), - $this->compressed, - ]); + return implode([chr($this->algorithm->value), $this->compressed]); } private static function compress( - PacketListInterface $packetList, Algorithm $algorithm - ): string - { - return match($algorithm) { + PacketListInterface $packetList, + Algorithm $algorithm + ): string { + return match ($algorithm) { Algorithm::Uncompressed => $packetList->encode(), - Algorithm::Zip => \gzdeflate($packetList->encode(), self::DEFLATE_LEVEL), - Algorithm::Zlib => \gzcompress($packetList->encode(), self::DEFLATE_LEVEL), + Algorithm::Zip => \gzdeflate( + $packetList->encode(), + self::DEFLATE_LEVEL + ), + Algorithm::Zlib => \gzcompress( + $packetList->encode(), + self::DEFLATE_LEVEL + ), Algorithm::BZip2 => \bzcompress($packetList->encode()), }; } private static function decompress( - string $compressed, Algorithm $algorithm - ): PacketListInterface - { - return match($algorithm) { + string $compressed, + Algorithm $algorithm + ): PacketListInterface { + return match ($algorithm) { Algorithm::Uncompressed => PacketList::decode($compressed), Algorithm::Zip => PacketList::decode(\gzinflate($compressed)), Algorithm::Zlib => PacketList::decode(\gzuncompress($compressed)), diff --git a/src/Packet/EncryptedDataTrait.php b/src/Packet/EncryptedDataTrait.php index 348534b7..2f9f3e4a 100644 --- a/src/Packet/EncryptedDataTrait.php +++ b/src/Packet/EncryptedDataTrait.php @@ -9,10 +9,7 @@ namespace OpenPGP\Packet; use OpenPGP\Enum\SymmetricAlgorithm; -use OpenPGP\Type\{ - PacketListInterface, - SessionKeyInterface, -}; +use OpenPGP\Type\{PacketListInterface, SessionKeyInterface}; /** * Encrypted data packet trait @@ -45,14 +42,9 @@ public function getPacketList(): ?PacketListInterface public function encrypt( string $key, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 - ): self - { + ): self { if ($this->packetList instanceof PacketListInterface) { - return self::encryptPackets( - $key, - $this->packetList, - $symmetric, - ); + return self::encryptPackets($key, $this->packetList, $symmetric); } return $this; } @@ -60,26 +52,22 @@ public function encrypt( /** * {@inheritdoc} */ - public function encryptWithSessionKey( - SessionKeyInterface $sessionKey - ): self + public function encryptWithSessionKey(SessionKeyInterface $sessionKey): self { return $this->encrypt( $sessionKey->getEncryptionKey(), - $sessionKey->getSymmetric(), + $sessionKey->getSymmetric() ); } /** * {@inheritdoc} */ - public function decryptWithSessionKey( - SessionKeyInterface $sessionKey - ): self + public function decryptWithSessionKey(SessionKeyInterface $sessionKey): self { return $this->decrypt( $sessionKey->getEncryptionKey(), - $sessionKey->getSymmetric(), + $sessionKey->getSymmetric() ); } } diff --git a/src/Packet/ImageUserAttribute.php b/src/Packet/ImageUserAttribute.php index a9c21371..f43f5baa 100644 --- a/src/Packet/ImageUserAttribute.php +++ b/src/Packet/ImageUserAttribute.php @@ -26,7 +26,7 @@ class ImageUserAttribute extends UserAttributeSubpacket * @param bool $isLong * @return self */ - public function __construct(string $data = '', bool $isLong = false) + public function __construct(string $data = "", bool $isLong = false) { parent::__construct(self::JPEG, $data, $isLong); } @@ -37,16 +37,16 @@ public function __construct(string $data = '', bool $isLong = false) * @param string $imageData * @return self */ - public static function fromImageData( - string $imageData - ): self + public static function fromImageData(string $imageData): self { - return new self(implode([ - "\x10\x00\x01", - chr(self::JPEG), - str_repeat("\x00", 12), - $imageData, - ])); + return new self( + implode([ + "\x10\x00\x01", + chr(self::JPEG), + str_repeat("\x00", 12), + $imageData, + ]) + ); } /** diff --git a/src/Packet/Key/AesKeyWrapper.php b/src/Packet/Key/AesKeyWrapper.php index 62f50105..8048cb78 100644 --- a/src/Packet/Key/AesKeyWrapper.php +++ b/src/Packet/Key/AesKeyWrapper.php @@ -29,6 +29,6 @@ class AesKeyWrapper extends KeyWrapper */ public function __construct(KekSize $kekSize = KekSize::Normal) { - parent::__construct(new \phpseclib3\Crypt\AES('ecb'), $kekSize); + parent::__construct(new \phpseclib3\Crypt\AES("ecb"), $kekSize); } } diff --git a/src/Packet/Key/CamelliaKeyWrapper.php b/src/Packet/Key/CamelliaKeyWrapper.php index 10eb237a..388dbcf6 100644 --- a/src/Packet/Key/CamelliaKeyWrapper.php +++ b/src/Packet/Key/CamelliaKeyWrapper.php @@ -30,7 +30,8 @@ class CamelliaKeyWrapper extends KeyWrapper public function __construct(KekSize $kekSize = KekSize::Normal) { parent::__construct( - new \OpenPGP\Cryptor\Symmetric\Camellia('ecb'), $kekSize + new \OpenPGP\Cryptor\Symmetric\Camellia("ecb"), + $kekSize ); } } diff --git a/src/Packet/Key/DSAPublicKeyMaterial.php b/src/Packet/Key/DSAPublicKeyMaterial.php index 2ac1fdda..dc28781c 100644 --- a/src/Packet/Key/DSAPublicKeyMaterial.php +++ b/src/Packet/Key/DSAPublicKeyMaterial.php @@ -10,14 +10,8 @@ use OpenPGP\Common\Helper; use OpenPGP\Enum\HashAlgorithm; -use OpenPGP\Type\{ - KeyMaterialInterface, - PublicKeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PublicKey, -}; +use OpenPGP\Type\{KeyMaterialInterface, PublicKeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PublicKey}; use phpseclib3\Crypt\DSA; use phpseclib3\Crypt\DSA\PublicKey as DSAPublicKey; use phpseclib3\Crypt\DSA\Formats\Keys\PKCS8; @@ -52,15 +46,16 @@ public function __construct( private readonly BigInteger $order, private readonly BigInteger $generator, private readonly BigInteger $exponent, - ?DSAPublicKey $publicKey = null, - ) - { - $this->publicKey = $publicKey ?? DSA::loadPublicKey([ - 'y' => $exponent, - 'p' => $prime, - 'q' => $order, - 'g' => $generator, - ]); + ?DSAPublicKey $publicKey = null + ) { + $this->publicKey = + $publicKey ?? + DSA::loadPublicKey([ + "y" => $exponent, + "p" => $prime, + "q" => $order, + "g" => $generator, + ]); } /** @@ -82,12 +77,7 @@ public static function fromBytes(string $bytes): self $offset += $generator->getLengthInBytes() + 2; $exponent = Helper::readMPI(substr($bytes, $offset)); - return new self( - $prime, - $order, - $generator, - $exponent, - ); + return new self($prime, $order, $generator, $exponent); } /** @@ -167,7 +157,7 @@ public function getAsymmetricKey(): AsymmetricKey */ public function getParameters(): array { - return PKCS8::load($this->publicKey->toString('PKCS8')); + return PKCS8::load($this->publicKey->toString("PKCS8")); } /** @@ -184,13 +174,13 @@ public function isValid(): bool public function toBytes(): string { return implode([ - pack('n', $this->prime->getLength()), + pack("n", $this->prime->getLength()), $this->prime->toBytes(), - pack('n', $this->order->getLength()), + pack("n", $this->order->getLength()), $this->order->toBytes(), - pack('n', $this->generator->getLength()), + pack("n", $this->generator->getLength()), $this->generator->toBytes(), - pack('n', $this->exponent->getLength()), + pack("n", $this->exponent->getLength()), $this->exponent->toBytes(), ]); } @@ -202,15 +192,12 @@ public function verify( HashAlgorithm $hash, string $message, string $signature - ): bool - { + ): bool { $r = Helper::readMPI($signature); - $s = Helper::readMPI( - substr($signature, $r->getLengthInBytes() + 2) - ); + $s = Helper::readMPI(substr($signature, $r->getLengthInBytes() + 2)); return $this->publicKey - ->withSignatureFormat('Raw') + ->withSignatureFormat("Raw") ->withHash(strtolower($hash->name)) - ->verify($message, ['r' => $r, 's' => $s]); + ->verify($message, ["r" => $r, "s" => $s]); } } diff --git a/src/Packet/Key/DSASecretKeyMaterial.php b/src/Packet/Key/DSASecretKeyMaterial.php index 8c9dac6a..ca5ee909 100644 --- a/src/Packet/Key/DSASecretKeyMaterial.php +++ b/src/Packet/Key/DSASecretKeyMaterial.php @@ -10,15 +10,8 @@ use OpenPGP\Common\Helper; use OpenPGP\Enum\HashAlgorithm; -use OpenPGP\Type\{ - KeyMaterialInterface, - SecretKeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PrivateKey, - PublicKey, -}; +use OpenPGP\Type\{KeyMaterialInterface, SecretKeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PrivateKey, PublicKey}; use phpseclib3\Crypt\DSA; use phpseclib3\Crypt\DSA\PrivateKey as DSAPrivateKey; use phpseclib3\Crypt\DSA\Formats\Keys\PKCS8; @@ -49,13 +42,14 @@ class DSASecretKeyMaterial implements SecretKeyMaterialInterface public function __construct( private readonly BigInteger $exponent, private readonly KeyMaterialInterface $publicMaterial, - ?DSAPrivateKey $privateKey = null, - ) - { - $this->privateKey = $privateKey ?? DSA::loadPrivateKey([ - 'x' => $exponent, - ...$publicMaterial->getParameters(), - ]); + ?DSAPrivateKey $privateKey = null + ) { + $this->privateKey = + $privateKey ?? + DSA::loadPrivateKey([ + "x" => $exponent, + ...$publicMaterial->getParameters(), + ]); } /** @@ -66,9 +60,9 @@ public function __construct( * @return self */ public static function fromBytes( - string $bytes, KeyMaterialInterface $publicMaterial - ): self - { + string $bytes, + KeyMaterialInterface $publicMaterial + ): self { return new self(Helper::readMPI($bytes), $publicMaterial); } @@ -79,22 +73,20 @@ public static function fromBytes( * @param int $nSize * @return self */ - public static function generate( - int $lSize = 2048, int $nSize = 224 - ): self + public static function generate(int $lSize = 2048, int $nSize = 224): self { $privateKey = DSA::createKey($lSize, $nSize); - $params = PKCS8::load($privateKey->toString('PKCS8')); + $params = PKCS8::load($privateKey->toString("PKCS8")); return new self( - $params['x'], + $params["x"], new DSAPublicKeyMaterial( - $params['p'], - $params['q'], - $params['g'], - $params['g']->powMod($params['x'], $params['p']), - $privateKey->getPublicKey(), + $params["p"], + $params["q"], + $params["g"], + $params["g"]->powMod($params["x"], $params["p"]), + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); } @@ -153,7 +145,7 @@ public function getKeyLength(): int */ public function getParameters(): array { - return PKCS8::load($this->privateKey->toString('PKCS8')); + return PKCS8::load($this->privateKey->toString("PKCS8")); } /** @@ -172,8 +164,10 @@ public function isValid(): bool $exponent = $this->publicMaterial->getExponent(); // Check that 1 < g < p - if ($generator->compare($one) <= 0 || - $generator->compare($prime) >= 0) { + if ( + $generator->compare($one) <= 0 || + $generator->compare($prime) >= 0 + ) { return false; } @@ -215,7 +209,7 @@ public function isValid(): bool public function toBytes(): string { return implode([ - pack('n', $this->exponent->getLength()), + pack("n", $this->exponent->getLength()), $this->exponent->toBytes(), ]); } @@ -226,14 +220,14 @@ public function toBytes(): string public function sign(HashAlgorithm $hash, string $message): string { $signature = $this->privateKey - ->withSignatureFormat('Raw') + ->withSignatureFormat("Raw") ->withHash(strtolower($hash->name)) ->sign($message); return implode([ - pack('n', $signature['r']->getLength()), - $signature['r']->toBytes(), - pack('n', $signature['s']->getLength()), - $signature['s']->toBytes(), + pack("n", $signature["r"]->getLength()), + $signature["r"]->toBytes(), + pack("n", $signature["s"]->getLength()), + $signature["s"]->toBytes(), ]); } } diff --git a/src/Packet/Key/ECDHPublicKeyMaterial.php b/src/Packet/Key/ECDHPublicKeyMaterial.php index 0cb57391..494cc8cd 100644 --- a/src/Packet/Key/ECDHPublicKeyMaterial.php +++ b/src/Packet/Key/ECDHPublicKeyMaterial.php @@ -9,10 +9,7 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Common\Helper; -use OpenPGP\Enum\{ - HashAlgorithm, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{HashAlgorithm, SymmetricAlgorithm}; use phpseclib3\Crypt\EC\PublicKey; use phpseclib3\Math\BigInteger; @@ -44,9 +41,8 @@ public function __construct( private readonly HashAlgorithm $kdfHash, private readonly SymmetricAlgorithm $kdfSymmetric, private readonly int $reserved = self::DEFAULT_RESERVED, - ?PublicKey $publicKey = null, - ) - { + ?PublicKey $publicKey = null + ) { parent::__construct($oid, $q, $publicKey); } @@ -72,7 +68,7 @@ public static function fromBytes(string $bytes): self $q, HashAlgorithm::from(ord($kdfBytes[2])), SymmetricAlgorithm::from(ord($kdfBytes[3])), - ord($kdfBytes[1]), + ord($kdfBytes[1]) ); } diff --git a/src/Packet/Key/ECDHSecretKeyMaterial.php b/src/Packet/Key/ECDHSecretKeyMaterial.php index e90e9522..343bb88d 100644 --- a/src/Packet/Key/ECDHSecretKeyMaterial.php +++ b/src/Packet/Key/ECDHSecretKeyMaterial.php @@ -25,7 +25,7 @@ */ class ECDHSecretKeyMaterial extends ECSecretKeyMaterial { - const CURVE25519_KEY_LENGTH = 32; + const CURVE25519_KEY_LENGTH = 32; /** * Read key material from bytes @@ -35,12 +35,10 @@ class ECDHSecretKeyMaterial extends ECSecretKeyMaterial * @return self */ public static function fromBytes( - string $bytes, KeyMaterialInterface $publicMaterial - ): self - { - return new self( - Helper::readMPI($bytes), $publicMaterial - ); + string $bytes, + KeyMaterialInterface $publicMaterial + ): self { + return new self(Helper::readMPI($bytes), $publicMaterial); } /** @@ -60,22 +58,22 @@ public static function generate(CurveOid $curveOid): self /// The lowest three bits must be 0 $secretKey[31] = $secretKey[31] & "\xf8"; $d = Helper::bin2BigInt($secretKey); - } while ($d->getLengthInBytes() !== self::CURVE25519_KEY_LENGTH); + } while ( + $d->getLengthInBytes() !== self::CURVE25519_KEY_LENGTH + ); $privateKey = EC::loadPrivateKeyFormat( - 'MontgomeryPrivate', strrev($secretKey) + "MontgomeryPrivate", + strrev($secretKey) ); $q = Helper::bin2BigInt( "\x40" . $privateKey->getEncodedCoordinates() ); - } - else { + } else { $privateKey = EC::createKey($curveOid->name); - $params = PKCS8::load($privateKey->toString('PKCS8')); - $d = $params['dA']; - $q = Helper::bin2BigInt( - $privateKey->getEncodedCoordinates() - ); + $params = PKCS8::load($privateKey->toString("PKCS8")); + $d = $params["dA"]; + $q = Helper::bin2BigInt($privateKey->getEncodedCoordinates()); } return new self( $d, @@ -85,12 +83,11 @@ public static function generate(CurveOid $curveOid): self $curveOid->hashAlgorithm(), $curveOid->symmetricAlgorithm(), ECDHPublicKeyMaterial::DEFAULT_RESERVED, - $privateKey->getPublicKey(), + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); - } - else { + } else { throw new \InvalidArgumentException( "Curve {$curveOid->name} is not supported for ECDH key generation." ); diff --git a/src/Packet/Key/ECDHSessionKeyCryptor.php b/src/Packet/Key/ECDHSessionKeyCryptor.php index 65c6361f..1633d227 100644 --- a/src/Packet/Key/ECDHSessionKeyCryptor.php +++ b/src/Packet/Key/ECDHSessionKeyCryptor.php @@ -12,20 +12,17 @@ use OpenPGP\Enum\{ CurveOid, HashAlgorithm, - KekSize, KeyAlgorithm, - SymmetricAlgorithm, + KekSize, + SymmetricAlgorithm }; use OpenPGP\Type\{ KeyPacketInterface, SecretKeyPacketInterface, SessionKeyCryptorInterface, - SessionKeyInterface, -}; -use phpseclib3\Crypt\{ - DH, - EC, + SessionKeyInterface }; +use phpseclib3\Crypt\{DH, EC}; use phpseclib3\Crypt\EC\Formats\Keys\PKCS8; use phpseclib3\File\ASN1; use phpseclib3\Math\BigInteger; @@ -39,7 +36,7 @@ */ class ECDHSessionKeyCryptor implements SessionKeyCryptorInterface { - const ANONYMOUS_SENDER = 'Anonymous Sender '; + const ANONYMOUS_SENDER = "Anonymous Sender "; const PKCS5_BLOCK_SIZE = 8; /** @@ -51,9 +48,8 @@ class ECDHSessionKeyCryptor implements SessionKeyCryptorInterface */ public function __construct( private readonly BigInteger $ephemeralKey, - private readonly string $wrappedKey, - ) - { + private readonly string $wrappedKey + ) { } /** @@ -67,10 +63,7 @@ public static function fromBytes(string $bytes): self $ephemeralKey = Helper::readMPI($bytes); $offset = $ephemeralKey->getLengthInBytes() + 2; $length = ord($bytes[$offset++]); - return new self( - $ephemeralKey, - substr($bytes, $offset, $length), - ); + return new self($ephemeralKey, substr($bytes, $offset, $length)); } /** @@ -82,34 +75,32 @@ public static function fromBytes(string $bytes): self */ public static function encryptSessionKey( SessionKeyInterface $sessionKey, - KeyPacketInterface $keyPacket, - ): self - { + KeyPacketInterface $keyPacket + ): self { $keyMaterial = $keyPacket->getKeyMaterial(); if ($keyMaterial instanceof ECDHPublicKeyMaterial) { - $privateKey = EC::createKey( - $keyMaterial->getECKey()->getCurve() - ); + $privateKey = EC::createKey($keyMaterial->getECKey()->getCurve()); $kek = self::ecdhKdf( $keyMaterial->getKdfHash(), DH::computeSecret( $privateKey, - $keyMaterial->getECKey()->getEncodedCoordinates(), - ), - self::kdfParameter( - $keyMaterial, $keyPacket->getFingerprint() + $keyMaterial->getECKey()->getEncodedCoordinates() ), - $keyMaterial->getKdfSymmetric()->keySizeInByte(), + self::kdfParameter($keyMaterial, $keyPacket->getFingerprint()), + $keyMaterial->getKdfSymmetric()->keySizeInByte() ); $keyWrapper = self::selectKeyWrapper( $keyMaterial->getKdfSymmetric() ); $wrappedKey = $keyWrapper->wrap( - $kek, self::pkcs5Encode(implode([ - $sessionKey->toBytes(), - $sessionKey->computeChecksum(), - ])) + $kek, + self::pkcs5Encode( + implode([ + $sessionKey->toBytes(), + $sessionKey->computeChecksum(), + ]) + ) ); $ephemeralKey = match ($keyMaterial->getCurveOid()) { @@ -121,13 +112,9 @@ public static function encryptSessionKey( ), }; - return new self( - $ephemeralKey, - $wrappedKey, - ); - } - else { - throw new \RuntimeException('Key material is not ECDH key.'); + return new self($ephemeralKey, $wrappedKey); + } else { + throw new \RuntimeException("Key material is not ECDH key."); } } @@ -137,7 +124,7 @@ public static function encryptSessionKey( public function toBytes(): string { return implode([ - pack('n', $this->ephemeralKey->getLength()), + pack("n", $this->ephemeralKey->getLength()), $this->ephemeralKey->toBytes(), chr(strlen($this->wrappedKey)), $this->wrappedKey, @@ -169,8 +156,7 @@ public function getWrappedKey(): string */ public function decryptSessionKey( SecretKeyPacketInterface $secretKey - ): SessionKeyInterface - { + ): SessionKeyInterface { return SessionKeyCryptor::sessionKeyFromBytes( $this->decrypt($secretKey) ); @@ -182,24 +168,25 @@ public function decryptSessionKey( * @param SecretKeyPacketInterface $secretKey * @return string */ - protected function decrypt( - SecretKeyPacketInterface $secretKey - ): string + protected function decrypt(SecretKeyPacketInterface $secretKey): string { $keyMaterial = $secretKey->getKeyMaterial(); $publicMaterial = $keyMaterial?->getPublicMaterial(); - if ($keyMaterial instanceof ECDHSecretKeyMaterial && - $publicMaterial instanceof ECDHPublicKeyMaterial) { + if ( + $keyMaterial instanceof ECDHSecretKeyMaterial && + $publicMaterial instanceof ECDHPublicKeyMaterial + ) { if ($publicMaterial->getCurveOid() === CurveOid::Curve25519) { - $format = 'MontgomeryPublic'; + $format = "MontgomeryPublic"; $key = substr($this->ephemeralKey->toBytes(), 1); - } - else { - $format = 'PKCS8'; + } else { + $format = "PKCS8"; $curve = $publicMaterial->getCurveOid()->getCurve(); $key = PKCS8::savePublicKey( - $curve, PKCS8::extractPoint( - "\x00" . $this->ephemeralKey->toBytes(), $curve + $curve, + PKCS8::extractPoint( + "\x00" . $this->ephemeralKey->toBytes(), + $curve ) ); } @@ -208,10 +195,13 @@ protected function decrypt( $publicMaterial->getKdfHash(), DH::computeSecret( $keyMaterial->getECKey(), - EC::loadFormat($format, $key)->getEncodedCoordinates(), + EC::loadFormat($format, $key)->getEncodedCoordinates() + ), + self::kdfParameter( + $publicMaterial, + $secretKey->getFingerprint() ), - self::kdfParameter($publicMaterial, $secretKey->getFingerprint()), - $publicMaterial->getKdfSymmetric()->keySizeInByte(), + $publicMaterial->getKdfSymmetric()->keySizeInByte() ); $keyWrapper = self::selectKeyWrapper( $publicMaterial->getKdfSymmetric() @@ -219,9 +209,8 @@ protected function decrypt( return self::pkcs5Decode( $keyWrapper->unwrap($kek, $this->wrappedKey) ); - } - else { - throw new \RuntimeException('Key material is not ECDH key.'); + } else { + throw new \RuntimeException("Key material is not ECDH key."); } } @@ -234,14 +223,13 @@ private static function ecdhKdf( HashAlgorithm $hash, string $sharedSecret, string $param, - int $keySize, - ): string - { - return substr($hash->hash(implode([ - pack('N', 1), - $sharedSecret, - $param, - ])), 0, $keySize); + int $keySize + ): string { + return substr( + $hash->hash(implode([pack("N", 1), $sharedSecret, $param])), + 0, + $keySize + ); } /** @@ -250,9 +238,9 @@ private static function ecdhKdf( * @return string */ private static function kdfParameter( - ECDHPublicKeyMaterial $keyMaterial, string $fingerprint - ): string - { + ECDHPublicKeyMaterial $keyMaterial, + string $fingerprint + ): string { $oid = ASN1::encodeOID($keyMaterial->getCurveOid()->value); return implode([ chr(strlen($oid)), @@ -277,7 +265,10 @@ private static function pkcs5Encode(string $message): string $length = strlen($message); $n = self::PKCS5_BLOCK_SIZE - ($length % self::PKCS5_BLOCK_SIZE); return substr_replace( - str_repeat(chr($n), $length + $n), $message, 0, $length + str_repeat(chr($n), $length + $n), + $message, + 0, + $length ); } @@ -291,25 +282,24 @@ private static function pkcs5Decode(string $message): string $len = strlen($message); $n = ord($message[$len - 1]); if ($len < $n || $n > self::PKCS5_BLOCK_SIZE) { - throw new \LengthException('Invalid padding length.'); + throw new \LengthException("Invalid padding length."); } $ps = substr($message, -$n); if (strcmp($ps, str_repeat(chr($n), $n)) !== 0) { - throw new \RuntimeException('Invalid padding string.'); + throw new \RuntimeException("Invalid padding string."); } return substr($message, 0, -$n); } private static function selectKeyWrapper( SymmetricAlgorithm $symmetric - ): KeyWrapper - { + ): KeyWrapper { $keySize = KekSize::from($symmetric->keySizeInByte()); return match ($symmetric) { SymmetricAlgorithm::Camellia128, SymmetricAlgorithm::Camellia192, SymmetricAlgorithm::Camellia256 - => new CamelliaKeyWrapper($keySize), + => new CamelliaKeyWrapper($keySize), default => new AesKeyWrapper($keySize), }; } diff --git a/src/Packet/Key/ECDSAPublicKeyMaterial.php b/src/Packet/Key/ECDSAPublicKeyMaterial.php index ea5a86db..2d139d2a 100644 --- a/src/Packet/Key/ECDSAPublicKeyMaterial.php +++ b/src/Packet/Key/ECDSAPublicKeyMaterial.php @@ -19,7 +19,8 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class ECDSAPublicKeyMaterial extends ECPublicKeyMaterial implements PublicKeyMaterialInterface +class ECDSAPublicKeyMaterial extends ECPublicKeyMaterial implements + PublicKeyMaterialInterface { /** * Read key material from bytes @@ -32,7 +33,7 @@ public static function fromBytes(string $bytes): self $length = ord($bytes[0]); return new self( substr($bytes, 1, $length), - Helper::readMPI(substr($bytes, $length + 1)), + Helper::readMPI(substr($bytes, $length + 1)) ); } @@ -42,16 +43,13 @@ public static function fromBytes(string $bytes): self public function verify( HashAlgorithm $hash, string $message, - string $signature, - ): bool - { + string $signature + ): bool { $r = Helper::readMPI($signature); - $s = Helper::readMPI( - substr($signature, $r->getLengthInBytes() + 2) - ); + $s = Helper::readMPI(substr($signature, $r->getLengthInBytes() + 2)); return $this->publicKey - ->withSignatureFormat('Raw') + ->withSignatureFormat("Raw") ->withHash(strtolower($hash->name)) - ->verify($message, ['r' => $r, 's' => $s]); + ->verify($message, ["r" => $r, "s" => $s]); } } diff --git a/src/Packet/Key/ECDSASecretKeyMaterial.php b/src/Packet/Key/ECDSASecretKeyMaterial.php index f6349085..33c2b7d4 100644 --- a/src/Packet/Key/ECDSASecretKeyMaterial.php +++ b/src/Packet/Key/ECDSASecretKeyMaterial.php @@ -9,14 +9,8 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Common\Helper; -use OpenPGP\Enum\{ - CurveOid, - HashAlgorithm, -}; -use OpenPGP\Type\{ - KeyMaterialInterface, - SecretKeyMaterialInterface, -}; +use OpenPGP\Enum\{CurveOid, HashAlgorithm}; +use OpenPGP\Type\{KeyMaterialInterface, SecretKeyMaterialInterface}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\Formats\Keys\PKCS8; use phpseclib3\File\ASN1; @@ -28,7 +22,8 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class ECDSASecretKeyMaterial extends ECSecretKeyMaterial implements SecretKeyMaterialInterface +class ECDSASecretKeyMaterial extends ECSecretKeyMaterial implements + SecretKeyMaterialInterface { /** * Read key material from bytes @@ -38,9 +33,9 @@ class ECDSASecretKeyMaterial extends ECSecretKeyMaterial implements SecretKeyMat * @return self */ public static function fromBytes( - string $bytes, KeyMaterialInterface $publicMaterial - ): self - { + string $bytes, + KeyMaterialInterface $publicMaterial + ): self { return new self(Helper::readMPI($bytes), $publicMaterial); } @@ -60,17 +55,17 @@ public static function generate(CurveOid $curveOid): self ); default: $privateKey = EC::createKey($curveOid->name); - $params = PKCS8::load($privateKey->toString('PKCS8')); + $params = PKCS8::load($privateKey->toString("PKCS8")); return new self( - $params['dA'], + $params["dA"], new ECDSAPublicKeyMaterial( ASN1::encodeOID($curveOid->value), Helper::bin2BigInt( $privateKey->getEncodedCoordinates() ), - $privateKey->getPublicKey(), + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); } } @@ -81,14 +76,14 @@ public static function generate(CurveOid $curveOid): self public function sign(HashAlgorithm $hash, string $message): string { $signature = $this->privateKey - ->withSignatureFormat('Raw') + ->withSignatureFormat("Raw") ->withHash(strtolower($hash->name)) ->sign($message); return implode([ - pack('n', $signature['r']->getLength()), - $signature['r']->toBytes(), - pack('n', $signature['s']->getLength()), - $signature['s']->toBytes(), + pack("n", $signature["r"]->getLength()), + $signature["r"]->toBytes(), + pack("n", $signature["s"]->getLength()), + $signature["s"]->toBytes(), ]); } } diff --git a/src/Packet/Key/ECPublicKeyMaterial.php b/src/Packet/Key/ECPublicKeyMaterial.php index e604c6b4..8f3d936b 100644 --- a/src/Packet/Key/ECPublicKeyMaterial.php +++ b/src/Packet/Key/ECPublicKeyMaterial.php @@ -9,14 +9,8 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Enum\CurveOid; -use OpenPGP\Type\{ - ECKeyMaterialInterface, - KeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PublicKey, -}; +use OpenPGP\Type\{ECKeyMaterialInterface, KeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PublicKey}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\PublicKey as ECPublicKey; use phpseclib3\Crypt\EC\Formats\Keys\MontgomeryPublic; @@ -30,7 +24,9 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -abstract class ECPublicKeyMaterial implements ECKeyMaterialInterface, KeyMaterialInterface +abstract class ECPublicKeyMaterial implements + ECKeyMaterialInterface, + KeyMaterialInterface { private readonly CurveOid $curveOid; @@ -50,27 +46,27 @@ abstract class ECPublicKeyMaterial implements ECKeyMaterialInterface, KeyMateria public function __construct( private readonly string $oid, private readonly BigInteger $q, - ?ECPublicKey $publicKey = null, - ) - { + ?ECPublicKey $publicKey = null + ) { $this->curveOid = CurveOid::fromOid($oid); if ($publicKey instanceof ECPublicKey) { $this->publicKey = $publicKey; - } - else { - $format = 'PKCS8'; + } else { + $format = "PKCS8"; switch ($this->curveOid) { case CurveOid::Curve25519: $key = substr($q->toBytes(), 1); - $format = 'MontgomeryPublic'; + $format = "MontgomeryPublic"; break; default: $curve = $this->curveOid->getCurve(); - $point = ($this->curveOid === CurveOid::Ed25519) ? - substr($q->toBytes(), 1) : "\x00" . $q->toBytes(); + $point = + $this->curveOid === CurveOid::Ed25519 + ? substr($q->toBytes(), 1) + : "\x00" . $q->toBytes(); $key = PKCS8::savePublicKey( $curve, - PKCS8::extractPoint($point, $curve), + PKCS8::extractPoint($point, $curve) ); break; } @@ -145,11 +141,10 @@ public function getParameters(): array { if ($this->curveOid === CurveOid::Curve25519) { return MontgomeryPublic::load( - $this->publicKey->toString('MontgomeryPublic') + $this->publicKey->toString("MontgomeryPublic") ); - } - else { - return PKCS8::load($this->publicKey->toString('PKCS8')); + } else { + return PKCS8::load($this->publicKey->toString("PKCS8")); } } @@ -169,7 +164,7 @@ public function toBytes(): string return implode([ chr(strlen($this->oid)), $this->oid, - pack('n', $this->q->getLength()), + pack("n", $this->q->getLength()), $this->q->toBytes(), ]); } diff --git a/src/Packet/Key/ECSecretKeyMaterial.php b/src/Packet/Key/ECSecretKeyMaterial.php index e6714f99..5aceeae7 100644 --- a/src/Packet/Key/ECSecretKeyMaterial.php +++ b/src/Packet/Key/ECSecretKeyMaterial.php @@ -10,25 +10,12 @@ use OpenPGP\Common\Helper; use OpenPGP\Enum\CurveOid; -use OpenPGP\Type\{ - ECKeyMaterialInterface, - KeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PrivateKey, - PublicKey, -}; +use OpenPGP\Type\{ECKeyMaterialInterface, KeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PrivateKey, PublicKey}; use phpseclib3\Crypt\EC; -use phpseclib3\Crypt\EC\Curves\{ - Curve25519, - Ed25519, -}; +use phpseclib3\Crypt\EC\Curves\{Curve25519, Ed25519}; use phpseclib3\Crypt\EC\PrivateKey as ECPrivateKey; -use phpseclib3\Crypt\EC\Formats\Keys\{ - MontgomeryPrivate, - PKCS8, -}; +use phpseclib3\Crypt\EC\Formats\Keys\{MontgomeryPrivate, PKCS8}; use phpseclib3\Math\BigInteger; /** @@ -38,7 +25,9 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -abstract class ECSecretKeyMaterial implements ECKeyMaterialInterface, KeyMaterialInterface +abstract class ECSecretKeyMaterial implements + ECKeyMaterialInterface, + KeyMaterialInterface { /** * phpseclib3 EC private key @@ -56,30 +45,27 @@ abstract class ECSecretKeyMaterial implements ECKeyMaterialInterface, KeyMateria public function __construct( private readonly BigInteger $d, private readonly KeyMaterialInterface $publicMaterial, - ?ECPrivateKey $privateKey = null, - ) - { + ?ECPrivateKey $privateKey = null + ) { if ($privateKey instanceof ECPrivateKey) { $this->privateKey = $privateKey; - } - else { - $format = 'PKCS8'; + } else { + $format = "PKCS8"; $params = $publicMaterial->getParameters(); - $curve = $params['curve']; + $curve = $params["curve"]; if ($curve instanceof Curve25519) { $key = strrev($d->toBytes()); - $format = 'MontgomeryPrivate'; - } - elseif ($curve instanceof Ed25519) { + $format = "MontgomeryPrivate"; + } elseif ($curve instanceof Ed25519) { $arr = $curve->extractSecret($d->toBytes()); $key = PKCS8::savePrivateKey( - $arr['dA'], $curve, $params['QA'], $arr['secret'] - ); - } - else { - $key = PKCS8::savePrivateKey( - $d, $curve, $params['QA'] + $arr["dA"], + $curve, + $params["QA"], + $arr["secret"] ); + } else { + $key = PKCS8::savePrivateKey($d, $curve, $params["QA"]); } $this->privateKey = EC::loadPrivateKeyFormat($format, $key); } @@ -149,14 +135,13 @@ public function getKeyLength(): int public function getParameters(): array { $params = $this->publicMaterial->getParameters(); - $curve = $params['curve']; + $curve = $params["curve"]; if ($curve instanceof Curve25519) { return MontgomeryPrivate::load( - $this->privateKey->toString('MontgomeryPrivate') + $this->privateKey->toString("MontgomeryPrivate") ); - } - else { - return PKCS8::load($this->privateKey->toString('PKCS8')); + } else { + return PKCS8::load($this->privateKey->toString("PKCS8")); } } @@ -170,17 +155,21 @@ public function isValid(): bool switch ($curveOid) { case CurveOid::Ed25519: case CurveOid::Curve25519: - return $this->publicMaterial->getQ()->equals( - Helper::bin2BigInt( - "\x40" . $this->privateKey->getEncodedCoordinates() - ) - ); + return $this->publicMaterial + ->getQ() + ->equals( + Helper::bin2BigInt( + "\x40" . + $this->privateKey->getEncodedCoordinates() + ) + ); default: $params = $this->publicMaterial->getParameters(); - $QA = $params['QA']; - $curve = $params['curve']; + $QA = $params["QA"]; + $curve = $params["curve"]; list($x, $y) = $curve->multiplyPoint( - $curve->getBasePoint(), $this->d + $curve->getBasePoint(), + $this->d ); return $x->equals($QA[0]) && $y->equals($QA[1]); } @@ -193,9 +182,6 @@ public function isValid(): bool */ public function toBytes(): string { - return implode([ - pack('n', $this->d->getLength()), - $this->d->toBytes(), - ]); + return implode([pack("n", $this->d->getLength()), $this->d->toBytes()]); } } diff --git a/src/Packet/Key/EdDSALegacyPublicKeyMaterial.php b/src/Packet/Key/EdDSALegacyPublicKeyMaterial.php index eb88890f..0e9ba16b 100644 --- a/src/Packet/Key/EdDSALegacyPublicKeyMaterial.php +++ b/src/Packet/Key/EdDSALegacyPublicKeyMaterial.php @@ -20,7 +20,8 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class EdDSALegacyPublicKeyMaterial extends ECPublicKeyMaterial implements PublicKeyMaterialInterface +class EdDSALegacyPublicKeyMaterial extends ECPublicKeyMaterial implements + PublicKeyMaterialInterface { /** * Read key material from bytes @@ -43,25 +44,21 @@ public static function fromBytes(string $bytes): self public function verify( HashAlgorithm $hash, string $message, - string $signature, - ): bool - { + string $signature + ): bool { $bitLength = Helper::bytesToShort($signature); - $r = substr( - $signature, 2, Helper::bit2ByteLength($bitLength) - ); // MPI of an EC point R + $r = substr($signature, 2, Helper::bit2ByteLength($bitLength)); // MPI of an EC point R - $bitLength = Helper::bytesToShort( - substr($signature, strlen($r) + 2) - ); + $bitLength = Helper::bytesToShort(substr($signature, strlen($r) + 2)); $s = substr( - $signature, strlen($r) + 4, - Helper::bit2ByteLength($bitLength), + $signature, + strlen($r) + 4, + Helper::bit2ByteLength($bitLength) ); // MPI of EdDSA value S return $this->getPublicKey()->verify( $hash->hash($message), - implode([$r, $s]), + implode([$r, $s]) ); } } diff --git a/src/Packet/Key/EdDSALegacySecretKeyMaterial.php b/src/Packet/Key/EdDSALegacySecretKeyMaterial.php index 76cb74cb..73dff594 100644 --- a/src/Packet/Key/EdDSALegacySecretKeyMaterial.php +++ b/src/Packet/Key/EdDSALegacySecretKeyMaterial.php @@ -9,14 +9,8 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Common\Helper; -use OpenPGP\Enum\{ - CurveOid, - HashAlgorithm, -}; -use OpenPGP\Type\{ - KeyMaterialInterface, - SecretKeyMaterialInterface, -}; +use OpenPGP\Enum\{CurveOid, HashAlgorithm}; +use OpenPGP\Type\{KeyMaterialInterface, SecretKeyMaterialInterface}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\Curves\Ed25519; use phpseclib3\Crypt\EC\Formats\Keys\PKCS8; @@ -29,7 +23,8 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class EdDSALegacySecretKeyMaterial extends ECSecretKeyMaterial implements SecretKeyMaterialInterface +class EdDSALegacySecretKeyMaterial extends ECSecretKeyMaterial implements + SecretKeyMaterialInterface { /** * Read key material from bytes @@ -39,13 +34,10 @@ class EdDSALegacySecretKeyMaterial extends ECSecretKeyMaterial implements Secret * @return self */ public static function fromBytes( - string $bytes, KeyMaterialInterface $publicMaterial - ): self - { - return new self( - Helper::readMPI($bytes), - $publicMaterial, - ); + string $bytes, + KeyMaterialInterface $publicMaterial + ): self { + return new self(Helper::readMPI($bytes), $publicMaterial); } /** @@ -58,8 +50,8 @@ public static function generate(): self $curve = CurveOid::Ed25519; do { $privateKey = EC::createKey($curve->name); - $params = PKCS8::load($privateKey->toString('PKCS8')); - $d = Helper::bin2BigInt($params['secret']); + $params = PKCS8::load($privateKey->toString("PKCS8")); + $d = Helper::bin2BigInt($params["secret"]); } while ($d->getLengthInBytes() !== Ed25519::SIZE); return new self( $d, @@ -68,9 +60,9 @@ public static function generate(): self Helper::bin2BigInt( "\x40" . $privateKey->getEncodedCoordinates() ), - $privateKey->getPublicKey(), + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); } @@ -79,14 +71,12 @@ public static function generate(): self */ public function sign(HashAlgorithm $hash, string $message): string { - $signature = $this->getPrivateKey()->sign( - $hash->hash($message) - ); + $signature = $this->getPrivateKey()->sign($hash->hash($message)); return implode([ - pack('n', Ed25519::SIZE * 8), // R bit length + pack("n", Ed25519::SIZE * 8), // R bit length substr($signature, 0, Ed25519::SIZE), // MPI of an EC point R - pack('n', Ed25519::SIZE * 8), // S bit length + pack("n", Ed25519::SIZE * 8), // S bit length substr($signature, Ed25519::SIZE), // MPI of EdDSA value S ]); } diff --git a/src/Packet/Key/EdDSAPublicKeyMaterial.php b/src/Packet/Key/EdDSAPublicKeyMaterial.php index ff8d6a9f..f5aa552c 100644 --- a/src/Packet/Key/EdDSAPublicKeyMaterial.php +++ b/src/Packet/Key/EdDSAPublicKeyMaterial.php @@ -8,19 +8,13 @@ namespace OpenPGP\Packet\Key; -use OpenPGP\Enum\{ - EdDSACurve, - HashAlgorithm, -}; +use OpenPGP\Enum\{EdDSACurve, HashAlgorithm}; use OpenPGP\Type\{ ECKeyMaterialInterface, KeyMaterialInterface, - PublicKeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PublicKey, + PublicKeyMaterialInterface }; +use phpseclib3\Crypt\Common\{AsymmetricKey, PublicKey}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\PublicKey as ECPublicKey; use phpseclib3\Crypt\EC\BaseCurves\TwistedEdwards; @@ -33,7 +27,9 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class EdDSAPublicKeyMaterial implements ECKeyMaterialInterface, PublicKeyMaterialInterface +class EdDSAPublicKeyMaterial implements + ECKeyMaterialInterface, + PublicKeyMaterialInterface { /** * phpseclib3 EC public key @@ -51,19 +47,17 @@ class EdDSAPublicKeyMaterial implements ECKeyMaterialInterface, PublicKeyMateria public function __construct( private readonly string $public, TwistedEdwards $curve, - ?ECPublicKey $publicKey = null, - ) - { + ?ECPublicKey $publicKey = null + ) { if ($publicKey instanceof ECPublicKey) { $this->publicKey = $publicKey; - } - else { + } else { $this->publicKey = EC::loadPublicKeyFormat( - 'PKCS8', + "PKCS8", PKCS8::savePublicKey( $curve, - PKCS8::extractPoint($public, $curve), - ), + PKCS8::extractPoint($public, $curve) + ) ); } } @@ -76,12 +70,12 @@ public function __construct( * @return self */ public static function fromBytes( - string $bytes, EdDSACurve $curve = EdDSACurve::Ed25519 - ): self - { + string $bytes, + EdDSACurve $curve = EdDSACurve::Ed25519 + ): self { return new self( substr($bytes, 0, $curve->payloadSize()), - $curve->getCurve(), + $curve->getCurve() ); } @@ -130,7 +124,7 @@ public function getAsymmetricKey(): AsymmetricKey */ public function getParameters(): array { - return PKCS8::load($this->publicKey->toString('PKCS8')); + return PKCS8::load($this->publicKey->toString("PKCS8")); } /** @@ -155,12 +149,8 @@ public function toBytes(): string public function verify( HashAlgorithm $hash, string $message, - string $signature, - ): bool - { - return $this->publicKey->verify( - $hash->hash($message), - $signature, - ); + string $signature + ): bool { + return $this->publicKey->verify($hash->hash($message), $signature); } } diff --git a/src/Packet/Key/EdDSASecretKeyMaterial.php b/src/Packet/Key/EdDSASecretKeyMaterial.php index c032d925..6637177b 100644 --- a/src/Packet/Key/EdDSASecretKeyMaterial.php +++ b/src/Packet/Key/EdDSASecretKeyMaterial.php @@ -8,20 +8,13 @@ namespace OpenPGP\Packet\Key; -use OpenPGP\Enum\{ - EdDSACurve, - HashAlgorithm, -}; +use OpenPGP\Enum\{EdDSACurve, HashAlgorithm}; use OpenPGP\Type\{ ECKeyMaterialInterface, KeyMaterialInterface, - SecretKeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PrivateKey, - PublicKey, + SecretKeyMaterialInterface }; +use phpseclib3\Crypt\Common\{AsymmetricKey, PrivateKey, PublicKey}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\PrivateKey as ECPrivateKey; use phpseclib3\Crypt\EC\Formats\Keys\PKCS8; @@ -33,7 +26,9 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class EdDSASecretKeyMaterial implements ECKeyMaterialInterface, SecretKeyMaterialInterface +class EdDSASecretKeyMaterial implements + ECKeyMaterialInterface, + SecretKeyMaterialInterface { /** * phpseclib3 EC private key @@ -51,21 +46,22 @@ class EdDSASecretKeyMaterial implements ECKeyMaterialInterface, SecretKeyMateria public function __construct( private readonly string $secret, private readonly KeyMaterialInterface $publicMaterial, - ?ECPrivateKey $privateKey = null, - ) - { + ?ECPrivateKey $privateKey = null + ) { if ($privateKey instanceof ECPrivateKey) { $this->privateKey = $privateKey; - } - else { + } else { $params = $publicMaterial->getParameters(); - $curve = $params['curve']; + $curve = $params["curve"]; $arr = $curve->extractSecret($secret); $this->privateKey = EC::loadPrivateKeyFormat( - 'PKCS8', + "PKCS8", PKCS8::savePrivateKey( - $arr['dA'], $curve, $params['QA'], $arr['secret'] - ), + $arr["dA"], + $curve, + $params["QA"], + $arr["secret"] + ) ); } } @@ -81,12 +77,11 @@ public function __construct( public static function fromBytes( string $bytes, KeyMaterialInterface $publicMaterial, - EdDSACurve $curve = EdDSACurve::Ed25519, - ): self - { + EdDSACurve $curve = EdDSACurve::Ed25519 + ): self { return new self( substr($bytes, 0, $curve->payloadSize()), - $publicMaterial, + $publicMaterial ); } @@ -98,22 +93,21 @@ public static function fromBytes( */ public static function generate( EdDSACurve $curve = EdDSACurve::Ed25519 - ): self - { + ): self { $size = $curve->payloadSize(); do { $privateKey = EC::createKey($curve->name); - $params = PKCS8::load($privateKey->toString('PKCS8')); - $secret = $params['secret']; + $params = PKCS8::load($privateKey->toString("PKCS8")); + $secret = $params["secret"]; } while (strlen($secret) !== $size); return new self( $secret, new EdDSAPublicKeyMaterial( $privateKey->getEncodedCoordinates(), - $params['curve'], - $privateKey->getPublicKey(), + $params["curve"], + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); } @@ -170,7 +164,7 @@ public function getKeyLength(): int */ public function getParameters(): array { - return PKCS8::load($this->privateKey->toString('PKCS8')); + return PKCS8::load($this->privateKey->toString("PKCS8")); } /** @@ -181,7 +175,7 @@ public function isValid(): bool if ($this->publicMaterial instanceof EdDSAPublicKeyMaterial) { return strcmp( $this->privateKey->getEncodedCoordinates(), - $this->publicMaterial->toBytes(), + $this->publicMaterial->toBytes() ) === 0; } return false; diff --git a/src/Packet/Key/ElGamalPublicKeyMaterial.php b/src/Packet/Key/ElGamalPublicKeyMaterial.php index 2dfdc30a..2fc51a43 100644 --- a/src/Packet/Key/ElGamalPublicKeyMaterial.php +++ b/src/Packet/Key/ElGamalPublicKeyMaterial.php @@ -41,12 +41,10 @@ public function __construct( private readonly BigInteger $prime, private readonly BigInteger $generator, private readonly BigInteger $exponent, - ?PublicKey $publicKey = null, - ) - { - $this->publicKey = $publicKey ?? new PublicKey( - $exponent, $prime, $generator - ); + ?PublicKey $publicKey = null + ) { + $this->publicKey = + $publicKey ?? new PublicKey($exponent, $prime, $generator); } /** @@ -65,11 +63,7 @@ public static function fromBytes(string $bytes): self $offset += $generator->getLengthInBytes() + 2; $exponent = Helper::readMPI(substr($bytes, $offset)); - return new self( - $prime, - $generator, - $exponent - ); + return new self($prime, $generator, $exponent); } /** @@ -140,9 +134,9 @@ public function getPublicMaterial(): KeyMaterialInterface public function getParameters(): array { return [ - 'p' => $this->prime, - 'g' => $this->generator, - 'y' => $this->exponent, + "p" => $this->prime, + "g" => $this->generator, + "y" => $this->exponent, ]; } @@ -160,11 +154,11 @@ public function isValid(): bool public function toBytes(): string { return implode([ - pack('n', $this->prime->getLength()), + pack("n", $this->prime->getLength()), $this->prime->toBytes(), - pack('n', $this->generator->getLength()), + pack("n", $this->generator->getLength()), $this->generator->toBytes(), - pack('n', $this->exponent->getLength()), + pack("n", $this->exponent->getLength()), $this->exponent->toBytes(), ]); } diff --git a/src/Packet/Key/ElGamalSecretKeyMaterial.php b/src/Packet/Key/ElGamalSecretKeyMaterial.php index e5a269db..b02b4bc5 100644 --- a/src/Packet/Key/ElGamalSecretKeyMaterial.php +++ b/src/Packet/Key/ElGamalSecretKeyMaterial.php @@ -10,10 +10,7 @@ use OpenPGP\Common\Helper; use OpenPGP\Cryptor\Asymmetric\ElGamal; -use OpenPGP\Cryptor\Asymmetric\ElGamal\{ - PrivateKey, - PublicKey, -}; +use OpenPGP\Cryptor\Asymmetric\ElGamal\{PrivateKey, PublicKey}; use OpenPGP\Type\KeyMaterialInterface; use phpseclib3\Crypt\Common\AsymmetricKey; use phpseclib3\Math\BigInteger; @@ -42,16 +39,17 @@ class ElGamalSecretKeyMaterial implements KeyMaterialInterface public function __construct( private readonly BigInteger $exponent, private readonly KeyMaterialInterface $publicMaterial, - ?PrivateKey $privateKey = null, - ) - { + ?PrivateKey $privateKey = null + ) { $parameters = $publicMaterial->getParameters(); - $this->privateKey = $privateKey ?? new PrivateKey( - $exponent, - $parameters['y'], - $parameters['p'], - $parameters['g'], - ); + $this->privateKey = + $privateKey ?? + new PrivateKey( + $exponent, + $parameters["y"], + $parameters["p"], + $parameters["g"] + ); } /** @@ -62,9 +60,9 @@ public function __construct( * @return self */ public static function fromBytes( - string $bytes, KeyMaterialInterface $publicMaterial - ): self - { + string $bytes, + KeyMaterialInterface $publicMaterial + ): self { return new self(Helper::readMPI($bytes), $publicMaterial); } @@ -75,9 +73,7 @@ public static function fromBytes( * @param int $nSize * @return self */ - public static function generate( - int $lSize = 2048, int $nSize = 224 - ): self + public static function generate(int $lSize = 2048, int $nSize = 224): self { $privateKey = ElGamal::createKey($lSize, $nSize); return new self( @@ -86,9 +82,9 @@ public static function generate( $privateKey->getPrime(), $privateKey->getGenerator(), $privateKey->getY(), - $privateKey->getPublicKey(), + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); } @@ -152,7 +148,7 @@ public function getKeyLength(): int public function getParameters(): array { return [ - 'x' => $this->exponent, + "x" => $this->exponent, ]; } @@ -170,7 +166,10 @@ public function isValid(): bool $exponent = $this->publicMaterial->getExponent(); // Check that 1 < g < p - if ($generator->compare($one) <= 0 || $generator->compare($prime) >= 0) { + if ( + $generator->compare($one) <= 0 || + $generator->compare($prime) >= 0 + ) { return false; } @@ -182,9 +181,11 @@ public function isValid(): bool // g should have order p-1 // Check that g ** (p-1) = 1 mod p - if (!$generator->modPow( - $prime->subtract($one), $prime - )->equals($one)) { + if ( + !$generator + ->modPow($prime->subtract($one), $prime) + ->equals($one) + ) { return false; } @@ -195,13 +196,12 @@ public function isValid(): bool $two->bitwise_leftShift($pSize - 1), $two->bitwise_leftShift($pSize) ); - $rqx = $prime->subtract($one) + $rqx = $prime + ->subtract($one) ->multiply($r) ->add($this->exponent); - return $exponent->equals( - $generator->modPow($rqx, $prime) - ); + return $exponent->equals($generator->modPow($rqx, $prime)); } return false; } @@ -212,7 +212,7 @@ public function isValid(): bool public function toBytes(): string { return implode([ - pack('n', $this->exponent->getLength()), + pack("n", $this->exponent->getLength()), $this->exponent->toBytes(), ]); } diff --git a/src/Packet/Key/ElGamalSessionKeyCryptor.php b/src/Packet/Key/ElGamalSessionKeyCryptor.php index 8a0f2861..8c96d358 100644 --- a/src/Packet/Key/ElGamalSessionKeyCryptor.php +++ b/src/Packet/Key/ElGamalSessionKeyCryptor.php @@ -9,10 +9,7 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Common\Helper; -use OpenPGP\Cryptor\Asymmetric\ElGamal\{ - PrivateKey, - PublicKey, -}; +use OpenPGP\Cryptor\Asymmetric\ElGamal\{PrivateKey, PublicKey}; use OpenPGP\Type\SessionKeyInterface; use phpseclib3\Crypt\Common\AsymmetricKey; use phpseclib3\Crypt\Random; @@ -38,9 +35,8 @@ class ElGamalSessionKeyCryptor extends SessionKeyCryptor */ public function __construct( private readonly BigInteger $gamma, - private readonly BigInteger $phi, - ) - { + private readonly BigInteger $phi + ) { } /** @@ -52,9 +48,7 @@ public function __construct( public static function fromBytes(string $bytes): self { $gamma = Helper::readMPI($bytes); - $phi = Helper::readMPI( - substr($bytes, $gamma->getLengthInBytes() + 2) - ); + $phi = Helper::readMPI(substr($bytes, $gamma->getLengthInBytes() + 2)); return new self($gamma, $phi); } @@ -66,23 +60,25 @@ public static function fromBytes(string $bytes): self * @return self */ public static function encryptSessionKey( - SessionKeyInterface $sessionKey, AsymmetricKey $publicKey - ): self - { + SessionKeyInterface $sessionKey, + AsymmetricKey $publicKey + ): self { if ($publicKey instanceof PublicKey) { $size = $publicKey->getPrime()->getLengthInBytes(); - $padded = self::pkcs1Encode(implode([ - $sessionKey->toBytes(), - $sessionKey->computeChecksum(), - ]), $size); + $padded = self::pkcs1Encode( + implode([ + $sessionKey->toBytes(), + $sessionKey->computeChecksum(), + ]), + $size + ); $encrypted = $publicKey->encrypt($padded); return new self( Helper::bin2BigInt(substr($encrypted, 0, $size)), - Helper::bin2BigInt(substr($encrypted, $size, $size)), + Helper::bin2BigInt(substr($encrypted, $size, $size)) ); - } - else { - throw new \RuntimeException('Public key is not ElGamal key.'); + } else { + throw new \RuntimeException("Public key is not ElGamal key."); } } @@ -92,9 +88,9 @@ public static function encryptSessionKey( public function toBytes(): string { return implode([ - pack('n', $this->gamma->getLength()), + pack("n", $this->gamma->getLength()), $this->gamma->toBytes(), - pack('n', $this->phi->getLength()), + pack("n", $this->phi->getLength()), $this->phi->toBytes(), ]); } @@ -126,14 +122,12 @@ protected function decrypt(AsymmetricKey $privateKey): string { if ($privateKey instanceof PrivateKey) { return self::pkcs1Decode( - $privateKey->decrypt(implode([ - $this->gamma->toBytes(), - $this->phi->toBytes(), - ])) + $privateKey->decrypt( + implode([$this->gamma->toBytes(), $this->phi->toBytes()]) + ) ); - } - else { - throw new \RuntimeException('Private key is not ElGamal key.'); + } else { + throw new \RuntimeException("Private key is not ElGamal key."); } } @@ -142,22 +136,23 @@ protected function decrypt(AsymmetricKey $privateKey): string * * @return string */ - private static function pkcs1Encode( - string $message, int $keyLength - ): string + private static function pkcs1Encode(string $message, int $keyLength): string { $mLength = strlen($message); // length checking if ($mLength > $keyLength - 11) { - throw new \RuntimeException('Message too long.'); + throw new \RuntimeException("Message too long."); } $ps = self::pkcs1Padding($keyLength - $mLength - 3); $encoded = str_repeat(self::ZERO_CHAR, $keyLength); $encoded[1] = "\x02"; $encoded = substr_replace($encoded, $ps, 2, strlen($ps)); $encoded = substr_replace( - $encoded, $message, $keyLength - $mLength, strlen($message) + $encoded, + $message, + $keyLength - $mLength, + strlen($message) ); return $encoded; } @@ -172,7 +167,7 @@ private static function pkcs1Decode(string $message): string $offset = 2; $separatorNotFound = 1; for ($i = $offset, $len = strlen($message); $i < $len; $i++) { - $separatorNotFound &= (ord($message[$i]) != 0) ? 1 : 0; + $separatorNotFound &= ord($message[$i]) != 0 ? 1 : 0; $offset += $separatorNotFound; } return substr($message, $offset + 1); @@ -189,7 +184,7 @@ private static function pkcs1Padding(int $length): string $result[$count++] = $bytes[$i]; } } - }; + } return $result; } } diff --git a/src/Packet/Key/KeyWrapper.php b/src/Packet/Key/KeyWrapper.php index a3774ddb..ba98e2cf 100644 --- a/src/Packet/Key/KeyWrapper.php +++ b/src/Packet/Key/KeyWrapper.php @@ -33,9 +33,8 @@ abstract class KeyWrapper */ protected function __construct( private readonly BlockCipher $cipher, - private readonly KekSize $kekSize, - ) - { + private readonly KekSize $kekSize + ) { $this->cipher->disablePadding(); } @@ -55,19 +54,14 @@ public function wrap(string $kek, string $key): string $r = $key; $n = intval(strlen($key) / 8); for ($j = 0; $j <= 5; $j++) { - for ($i = 1; $i <= $n; $i++) { - $buffer = implode([ - $a, - substr($r, ($i - 1) * 8, 8), - ]); + for ($i = 1; $i <= $n; $i++) { + $buffer = implode([$a, substr($r, ($i - 1) * 8, 8)]); $buffer = $this->cipher->encrypt($buffer); $a = substr($buffer, 0, 8); - $a[7] = chr(ord($a[7]) ^ ($n * $j + $i) & 0xff); + $a[7] = chr(ord($a[7]) ^ (($n * $j + $i) & 0xff)); - $r = substr_replace( - $r, substr($buffer, 8, 8), ($i - 1) * 8, 8 - ); + $r = substr_replace($r, substr($buffer, 8, 8), ($i - 1) * 8, 8); } } return implode([$a, $r]); @@ -90,22 +84,17 @@ public function unwrap(string $kek, string $wrappedKey): string $n = intval(strlen($wrappedKey) / 8) - 1; for ($j = 5; $j >= 0; $j--) { for ($i = $n; $i >= 1; $i--) { - $a[7] = chr(ord($a[7]) ^ ($n * $j + $i) & 0xff); - $buffer = implode([ - $a, - substr($r, ($i - 1) * 8, 8), - ]); + $a[7] = chr(ord($a[7]) ^ (($n * $j + $i) & 0xff)); + $buffer = implode([$a, substr($r, ($i - 1) * 8, 8)]); $buffer = $this->cipher->decrypt($buffer); $a = substr($buffer, 0, 8); - $r = substr_replace( - $r, substr($buffer, 8, 8), ($i - 1) * 8, 8 - ); + $r = substr_replace($r, substr($buffer, 8, 8), ($i - 1) * 8, 8); } } if (strcmp(self::IV, $a) !== 0) { - throw new \RuntimeException('Integrity check failed.'); + throw new \RuntimeException("Integrity check failed."); } return $r; @@ -120,12 +109,14 @@ private function validateKeySize(string $kek, string $key): void } if (strlen($key) < KekSize::Normal->value) { throw new \LengthException( - 'Key length must be at least ' . KekSize::Normal->value . ' octets.' + "Key length must be at least " . + KekSize::Normal->value . + " octets." ); } if (strlen($key) % 8 !== 0) { throw new \LengthException( - 'Key length must be a multiple of 64 bits.' + "Key length must be a multiple of 64 bits." ); } } diff --git a/src/Packet/Key/MontgomeryPublicKeyMaterial.php b/src/Packet/Key/MontgomeryPublicKeyMaterial.php index 0a03acf0..c67b1d97 100644 --- a/src/Packet/Key/MontgomeryPublicKeyMaterial.php +++ b/src/Packet/Key/MontgomeryPublicKeyMaterial.php @@ -8,14 +8,8 @@ namespace OpenPGP\Packet\Key; -use OpenPGP\Type\{ - ECKeyMaterialInterface, - KeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PublicKey, -}; +use OpenPGP\Type\{ECKeyMaterialInterface, KeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PublicKey}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\PublicKey as ECPublicKey; use phpseclib3\Crypt\EC\Formats\Keys\MontgomeryPublic; @@ -27,7 +21,9 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class MontgomeryPublicKeyMaterial implements ECKeyMaterialInterface, KeyMaterialInterface +class MontgomeryPublicKeyMaterial implements + ECKeyMaterialInterface, + KeyMaterialInterface { /** * phpseclib3 EC public key @@ -43,15 +39,14 @@ class MontgomeryPublicKeyMaterial implements ECKeyMaterialInterface, KeyMaterial */ public function __construct( private readonly string $public, - ?ECPublicKey $publicKey = null, - ) - { + ?ECPublicKey $publicKey = null + ) { if ($publicKey instanceof ECPublicKey) { $this->publicKey = $publicKey; - } - else { + } else { $this->publicKey = EC::loadPublicKeyFormat( - 'MontgomeryPublic', $public + "MontgomeryPublic", + $public ); } } @@ -113,7 +108,7 @@ public function getAsymmetricKey(): AsymmetricKey public function getParameters(): array { return MontgomeryPublic::load( - $this->publicKey->toString('MontgomeryPublic') + $this->publicKey->toString("MontgomeryPublic") ); } diff --git a/src/Packet/Key/MontgomerySecretKeyMaterial.php b/src/Packet/Key/MontgomerySecretKeyMaterial.php index 11375235..f0855800 100644 --- a/src/Packet/Key/MontgomerySecretKeyMaterial.php +++ b/src/Packet/Key/MontgomerySecretKeyMaterial.php @@ -9,15 +9,8 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Enum\MontgomeryCurve; -use OpenPGP\Type\{ - ECKeyMaterialInterface, - KeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PrivateKey, - PublicKey, -}; +use OpenPGP\Type\{ECKeyMaterialInterface, KeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PrivateKey, PublicKey}; use phpseclib3\Crypt\EC; use phpseclib3\Crypt\EC\PrivateKey as ECPrivateKey; use phpseclib3\Crypt\EC\Formats\Keys\MontgomeryPrivate; @@ -29,7 +22,9 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class MontgomerySecretKeyMaterial implements ECKeyMaterialInterface, KeyMaterialInterface +class MontgomerySecretKeyMaterial implements + ECKeyMaterialInterface, + KeyMaterialInterface { /** * phpseclib3 EC private key @@ -47,15 +42,14 @@ class MontgomerySecretKeyMaterial implements ECKeyMaterialInterface, KeyMaterial public function __construct( private readonly string $secret, private readonly KeyMaterialInterface $publicMaterial, - ?ECPrivateKey $privateKey = null, - ) - { + ?ECPrivateKey $privateKey = null + ) { if ($privateKey instanceof ECPrivateKey) { $this->privateKey = $privateKey; - } - else { + } else { $this->privateKey = EC::loadPrivateKeyFormat( - 'MontgomeryPrivate', $secret + "MontgomeryPrivate", + $secret ); } } @@ -70,12 +64,11 @@ public function __construct( public static function fromBytes( string $bytes, KeyMaterialInterface $publicMaterial, - MontgomeryCurve $curve = MontgomeryCurve::Curve25519, - ): self - { + MontgomeryCurve $curve = MontgomeryCurve::Curve25519 + ): self { return new self( substr($bytes, 0, $curve->payloadSize()), - $publicMaterial, + $publicMaterial ); } @@ -87,20 +80,19 @@ public static function fromBytes( */ public static function generate( MontgomeryCurve $curve = MontgomeryCurve::Curve25519 - ): self - { + ): self { $size = $curve->payloadSize(); do { $privateKey = EC::createKey($curve->name); - $secret = $privateKey->toString('MontgomeryPrivate'); + $secret = $privateKey->toString("MontgomeryPrivate"); } while (strlen($secret) !== $size); return new self( $secret, new MontgomeryPublicKeyMaterial( $privateKey->getEncodedCoordinates(), - $privateKey->getPublicKey(), + $privateKey->getPublicKey() ), - $privateKey, + $privateKey ); } @@ -158,7 +150,7 @@ public function getKeyLength(): int public function getParameters(): array { return MontgomeryPrivate::load( - $this->privateKey->toString('MontgomeryPrivate') + $this->privateKey->toString("MontgomeryPrivate") ); } @@ -170,7 +162,7 @@ public function isValid(): bool if ($this->publicMaterial instanceof MontgomeryPublicKeyMaterial) { return strcmp( $this->privateKey->getEncodedCoordinates(), - $this->publicMaterial->toBytes(), + $this->publicMaterial->toBytes() ) === 0; } return false; diff --git a/src/Packet/Key/MontgomerySessionKeyCryptor.php b/src/Packet/Key/MontgomerySessionKeyCryptor.php index f3b45963..4d42b9e3 100644 --- a/src/Packet/Key/MontgomerySessionKeyCryptor.php +++ b/src/Packet/Key/MontgomerySessionKeyCryptor.php @@ -12,12 +12,9 @@ use OpenPGP\Type\{ SecretKeyPacketInterface, SessionKeyCryptorInterface, - SessionKeyInterface, -}; -use phpseclib3\Crypt\{ - DH, - EC, + SessionKeyInterface }; +use phpseclib3\Crypt\{DH, EC}; /** * Montgomery session key cryptor class. @@ -39,9 +36,8 @@ class MontgomerySessionKeyCryptor implements SessionKeyCryptorInterface public function __construct( private readonly string $ephemeralKey, private readonly string $wrappedKey, - private readonly MontgomeryCurve $curve = MontgomeryCurve::Curve25519, - ) - { + private readonly MontgomeryCurve $curve = MontgomeryCurve::Curve25519 + ) { } /** @@ -53,17 +49,16 @@ public function __construct( */ public static function fromBytes( string $bytes, - MontgomeryCurve $curve = MontgomeryCurve::Curve25519, - ): self - { + MontgomeryCurve $curve = MontgomeryCurve::Curve25519 + ): self { return new self( substr($bytes, 0, $curve->payloadSize()), substr( $bytes, $curve->payloadSize() + 1, - ord($bytes[$curve->payloadSize()]), + ord($bytes[$curve->payloadSize()]) ), - $curve, + $curve ); } @@ -78,12 +73,11 @@ public static function fromBytes( public static function encryptSessionKey( SessionKeyInterface $sessionKey, EC $publicKey, - MontgomeryCurve $curve = MontgomeryCurve::Curve25519, - ): self - { + MontgomeryCurve $curve = MontgomeryCurve::Curve25519 + ): self { if ($sessionKey->getSymmetric() !== $curve->symmetricAlgorithm()) { throw new \InvalidArgumentException( - 'Symmetric algorithm of the session key mismatch!' + "Symmetric algorithm of the session key mismatch!" ); } $privateKey = EC::createKey($publicKey->getCurve()); @@ -96,23 +90,18 @@ public static function encryptSessionKey( $publicKey->getEncodedCoordinates(), DH::computeSecret( $privateKey, - $publicKey->getEncodedCoordinates(), + $publicKey->getEncodedCoordinates() ), ]), $curve->kekSize()->value, - $curve->hkdfInfo(), - ); - $keyWrapper = new AesKeyWrapper( - $curve->kekSize() + $curve->hkdfInfo() ); + $keyWrapper = new AesKeyWrapper($curve->kekSize()); return new self( $ephemeralKey, - $keyWrapper->wrap( - $kek, - $sessionKey->getEncryptionKey(), - ), - $curve, + $keyWrapper->wrap($kek, $sessionKey->getEncryptionKey()), + $curve ); } @@ -153,13 +142,10 @@ public function getWrappedKey(): string */ public function decryptSessionKey( SecretKeyPacketInterface $secretKey - ): SessionKeyInterface - { + ): SessionKeyInterface { return new SessionKey( - $this->decrypt( - $secretKey->getECKeyMaterial()->getECKey(), - ), - $this->curve->symmetricAlgorithm(), + $this->decrypt($secretKey->getECKeyMaterial()->getECKey()), + $this->curve->symmetricAlgorithm() ); } @@ -179,12 +165,13 @@ private function decrypt(EC $privateKey): string DH::computeSecret( $privateKey, EC::loadFormat( - 'MontgomeryPublic', $this->ephemeralKey - )->getEncodedCoordinates(), + "MontgomeryPublic", + $this->ephemeralKey + )->getEncodedCoordinates() ), ]), $this->curve->kekSize()->value, - $this->curve->hkdfInfo(), + $this->curve->hkdfInfo() ); $keyWrapper = new AesKeyWrapper($this->curve->kekSize()); return $keyWrapper->unwrap($kek, $this->wrappedKey); diff --git a/src/Packet/Key/RSAPublicKeyMaterial.php b/src/Packet/Key/RSAPublicKeyMaterial.php index 2b008e05..ecd16538 100644 --- a/src/Packet/Key/RSAPublicKeyMaterial.php +++ b/src/Packet/Key/RSAPublicKeyMaterial.php @@ -10,14 +10,8 @@ use OpenPGP\Common\Helper; use OpenPGP\Enum\HashAlgorithm; -use OpenPGP\Type\{ - KeyMaterialInterface, - PublicKeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PublicKey, -}; +use OpenPGP\Type\{KeyMaterialInterface, PublicKeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PublicKey}; use phpseclib3\Crypt\RSA; use phpseclib3\Crypt\RSA\PublicKey as RSAPublicKey; use phpseclib3\Crypt\RSA\Formats\Keys\PKCS8; @@ -48,13 +42,14 @@ class RSAPublicKeyMaterial implements PublicKeyMaterialInterface public function __construct( private readonly BigInteger $modulus, private readonly BigInteger $exponent, - ?RSAPublicKey $publicKey = null, - ) - { - $this->publicKey = $publicKey ?? RSA::loadPublicKey([ - 'modulus' => $modulus, - 'publicExponent' => $exponent, - ]); + ?RSAPublicKey $publicKey = null + ) { + $this->publicKey = + $publicKey ?? + RSA::loadPublicKey([ + "modulus" => $modulus, + "publicExponent" => $exponent, + ]); } /** @@ -68,9 +63,7 @@ public static function fromBytes(string $bytes): self $modulus = Helper::readMPI($bytes); return new self( $modulus, - Helper::readMPI( - substr($bytes, $modulus->getLengthInBytes() + 2) - ), + Helper::readMPI(substr($bytes, $modulus->getLengthInBytes() + 2)) ); } @@ -131,7 +124,7 @@ public function getPublicKey(): PublicKey */ public function getParameters(): array { - return PKCS8::load($this->publicKey->toString('PKCS8')); + return PKCS8::load($this->publicKey->toString("PKCS8")); } /** @@ -148,9 +141,9 @@ public function isValid(): bool public function toBytes(): string { return implode([ - pack('n', $this->modulus->getLength()), + pack("n", $this->modulus->getLength()), $this->modulus->toBytes(), - pack('n', $this->exponent->getLength()), + pack("n", $this->exponent->getLength()), $this->exponent->toBytes(), ]); } @@ -162,17 +155,16 @@ public function verify( HashAlgorithm $hash, string $message, string $signature - ): bool - { + ): bool { return $this->publicKey ->withHash(strtolower($hash->name)) ->withPadding(RSA::SIGNATURE_PKCS1) ->verify( $message, - substr( $signature, 2, - Helper::bit2ByteLength( - Helper::bytesToShort($signature) - ), + substr( + $signature, + 2, + Helper::bit2ByteLength(Helper::bytesToShort($signature)) ) ); } diff --git a/src/Packet/Key/RSASecretKeyMaterial.php b/src/Packet/Key/RSASecretKeyMaterial.php index 28966cc2..ed4c25f1 100644 --- a/src/Packet/Key/RSASecretKeyMaterial.php +++ b/src/Packet/Key/RSASecretKeyMaterial.php @@ -9,19 +9,9 @@ namespace OpenPGP\Packet\Key; use OpenPGP\Common\Helper; -use OpenPGP\Enum\{ - HashAlgorithm, - RSAKeySize, -}; -use OpenPGP\Type\{ - KeyMaterialInterface, - SecretKeyMaterialInterface, -}; -use phpseclib3\Crypt\Common\{ - AsymmetricKey, - PrivateKey, - PublicKey, -}; +use OpenPGP\Enum\{HashAlgorithm, RSAKeySize}; +use OpenPGP\Type\{KeyMaterialInterface, SecretKeyMaterialInterface}; +use phpseclib3\Crypt\Common\{AsymmetricKey, PrivateKey, PublicKey}; use phpseclib3\Crypt\RSA; use phpseclib3\Crypt\RSA\PrivateKey as RSAPrivateKey; use phpseclib3\Crypt\RSA\Formats\Keys\PKCS8; @@ -58,16 +48,17 @@ public function __construct( private readonly BigInteger $primeQ, private readonly BigInteger $coefficient, private readonly KeyMaterialInterface $publicMaterial, - ?RSAPrivateKey $privateKey = null, - ) - { - $this->privateKey = $privateKey ?? RSA::loadPrivateKey([ - 'privateExponent' => $exponent, - 'p' => $primeP, - 'q' => $primeQ, - 'u' => $coefficient, - ...$publicMaterial->getParameters(), - ]); + ?RSAPrivateKey $privateKey = null + ) { + $this->privateKey = + $privateKey ?? + RSA::loadPrivateKey([ + "privateExponent" => $exponent, + "p" => $primeP, + "q" => $primeQ, + "u" => $coefficient, + ...$publicMaterial->getParameters(), + ]); } /** @@ -78,9 +69,9 @@ public function __construct( * @return self */ public static function fromBytes( - string $bytes, KeyMaterialInterface $publicMaterial - ): self - { + string $bytes, + KeyMaterialInterface $publicMaterial + ): self { $exponent = Helper::readMPI($bytes); $offset = $exponent->getLengthInBytes() + 2; @@ -109,20 +100,19 @@ public static function fromBytes( */ public static function generate( RSAKeySize $keySize = RSAKeySize::Normal - ): self - { + ): self { $privateKey = RSA::createKey($keySize->value); - $params = PKCS8::load($privateKey->toString('PKCS8')); - $primeP = $params['primes'][1]; - $primeQ = $params['primes'][2]; + $params = PKCS8::load($privateKey->toString("PKCS8")); + $primeP = $params["primes"][1]; + $primeQ = $params["primes"][2]; return new self( - $params['privateExponent'], + $params["privateExponent"], $primeP, $primeQ, $primeP->modInverse($primeQ), new RSAPublicKeyMaterial( - $params['modulus'], - $params['publicExponent'], + $params["modulus"], + $params["publicExponent"], $privateKey->getPublicKey() ), $privateKey @@ -214,7 +204,7 @@ public function getKeyLength(): int */ public function getParameters(): array { - return PKCS8::load($this->privateKey->toString('PKCS8')); + return PKCS8::load($this->privateKey->toString("PKCS8")); } /** @@ -227,9 +217,11 @@ public function isValid(): bool $two = new BigInteger(2); // expect pq = n - if (!$this->primeP->multiply($this->primeQ)->equals( - $this->publicMaterial->getModulus() - )) { + if ( + !$this->primeP + ->multiply($this->primeQ) + ->equals($this->publicMaterial->getModulus()) + ) { return false; } @@ -245,11 +237,12 @@ public function isValid(): bool $this->publicMaterial->getModulus()->getLength() / 3 ); $r = BigInteger::randomRange( - $one, $two->bitwise_leftShift($nSizeOver3) - ); - $rde = $r->multiply($this->exponent)->multiply( - $this->publicMaterial->getExponent() + $one, + $two->bitwise_leftShift($nSizeOver3) ); + $rde = $r + ->multiply($this->exponent) + ->multiply($this->publicMaterial->getExponent()); list(, $p) = $rde->divide($this->primeP->subtract($one)); list(, $q) = $rde->divide($this->primeQ->subtract($one)); @@ -264,13 +257,13 @@ public function isValid(): bool public function toBytes(): string { return implode([ - pack('n', $this->exponent->getLength()), + pack("n", $this->exponent->getLength()), $this->exponent->toBytes(), - pack('n', $this->primeP->getLength()), + pack("n", $this->primeP->getLength()), $this->primeP->toBytes(), - pack('n', $this->primeQ->getLength()), + pack("n", $this->primeQ->getLength()), $this->primeQ->toBytes(), - pack('n', $this->coefficient->getLength()), + pack("n", $this->coefficient->getLength()), $this->coefficient->toBytes(), ]); } @@ -284,9 +277,6 @@ public function sign(HashAlgorithm $hash, string $message): string ->withHash(strtolower($hash->name)) ->withPadding(RSA::SIGNATURE_PKCS1) ->sign($message); - return implode([ - pack('n', strlen($signature) * 8), - $signature, - ]); + return implode([pack("n", strlen($signature) * 8), $signature]); } } diff --git a/src/Packet/Key/RSASessionKeyCryptor.php b/src/Packet/Key/RSASessionKeyCryptor.php index 8177a0f4..c13d2baa 100644 --- a/src/Packet/Key/RSASessionKeyCryptor.php +++ b/src/Packet/Key/RSASessionKeyCryptor.php @@ -12,10 +12,7 @@ use OpenPGP\Type\SessionKeyInterface; use phpseclib3\Crypt\Common\AsymmetricKey; use phpseclib3\Crypt\RSA; -use phpseclib3\Crypt\RSA\{ - PrivateKey, - PublicKey, -}; +use phpseclib3\Crypt\RSA\{PrivateKey, PublicKey}; use phpseclib3\Math\BigInteger; /** @@ -56,20 +53,23 @@ public static function fromBytes(string $bytes): self * @return self */ public static function encryptSessionKey( - SessionKeyInterface $sessionKey, AsymmetricKey $publicKey, - ): self - { + SessionKeyInterface $sessionKey, + AsymmetricKey $publicKey + ): self { if ($publicKey instanceof PublicKey) { $publicKey = $publicKey->withPadding(RSA::ENCRYPTION_PKCS1); return new self( - Helper::bin2BigInt($publicKey->encrypt(implode([ - $sessionKey->toBytes(), - $sessionKey->computeChecksum(), - ]))), + Helper::bin2BigInt( + $publicKey->encrypt( + implode([ + $sessionKey->toBytes(), + $sessionKey->computeChecksum(), + ]) + ) + ) ); - } - else { - throw new \RuntimeException('Public key is not RSA key.'); + } else { + throw new \RuntimeException("Public key is not RSA key."); } } @@ -79,7 +79,7 @@ public static function encryptSessionKey( public function toBytes(): string { return implode([ - pack('n', $this->encrypted->getLength()), + pack("n", $this->encrypted->getLength()), $this->encrypted->toBytes(), ]); } @@ -102,9 +102,8 @@ protected function decrypt(AsymmetricKey $privateKey): string if ($privateKey instanceof PrivateKey) { $privateKey = $privateKey->withPadding(RSA::ENCRYPTION_PKCS1); return $privateKey->decrypt($this->encrypted->toBytes()); - } - else { - throw new \RuntimeException('Private key is not RSA key.'); + } else { + throw new \RuntimeException("Private key is not RSA key."); } } } diff --git a/src/Packet/Key/SessionKey.php b/src/Packet/Key/SessionKey.php index 08853fb9..d71949f5 100644 --- a/src/Packet/Key/SessionKey.php +++ b/src/Packet/Key/SessionKey.php @@ -31,9 +31,8 @@ class SessionKey implements SessionKeyInterface */ public function __construct( private readonly string $encryptionKey, - private readonly Symmetric $symmetric = Symmetric::Aes128, - ) - { + private readonly Symmetric $symmetric = Symmetric::Aes128 + ) { } /** @@ -48,9 +47,7 @@ public static function fromBytes(string $bytes): self substr($bytes, 1, strlen($bytes) - 3), Symmetric::from(ord($bytes[0])) ); - return $sessionKey->checksum( - substr($bytes, strlen($bytes) - 2) - ); + return $sessionKey->checksum(substr($bytes, strlen($bytes) - 2)); } /** @@ -61,11 +58,10 @@ public static function fromBytes(string $bytes): self */ public static function produceKey( Symmetric $symmetric = Symmetric::Aes128 - ): self - { + ): self { return new self( Random::string($symmetric->keySizeInByte()), - $symmetric, + $symmetric ); } @@ -91,7 +87,7 @@ public function getSymmetric(): Symmetric public function checksum(string $checksum): self { if (strcmp($this->computeChecksum(), $checksum) !== 0) { - throw new \RuntimeException('Session key checksum mismatch!'); + throw new \RuntimeException("Session key checksum mismatch!"); } return $this; } @@ -109,9 +105,6 @@ public function computeChecksum(): string */ public function toBytes(): string { - return implode([ - chr($this->symmetric->value), - $this->encryptionKey, - ]); + return implode([chr($this->symmetric->value), $this->encryptionKey]); } } diff --git a/src/Packet/Key/SessionKeyCryptor.php b/src/Packet/Key/SessionKeyCryptor.php index 1ffb7c5c..cb228026 100644 --- a/src/Packet/Key/SessionKeyCryptor.php +++ b/src/Packet/Key/SessionKeyCryptor.php @@ -11,7 +11,7 @@ use OpenPGP\Type\{ SecretKeyPacketInterface, SessionKeyCryptorInterface, - SessionKeyInterface, + SessionKeyInterface }; use phpseclib3\Crypt\Common\AsymmetricKey; @@ -30,8 +30,9 @@ abstract class SessionKeyCryptor implements SessionKeyCryptorInterface * @param string $bytes * @return SessionKeyInterface */ - public static function sessionKeyFromBytes(string $bytes): SessionKeyInterface - { + public static function sessionKeyFromBytes( + string $bytes + ): SessionKeyInterface { return SessionKey::fromBytes($bytes); } @@ -40,11 +41,10 @@ public static function sessionKeyFromBytes(string $bytes): SessionKeyInterface */ public function decryptSessionKey( SecretKeyPacketInterface $secretKey - ): SessionKeyInterface - { - return self::sessionKeyFromBytes($this->decrypt( - $secretKey->getKeyMaterial()->getAsymmetricKey() - )); + ): SessionKeyInterface { + return self::sessionKeyFromBytes( + $this->decrypt($secretKey->getKeyMaterial()->getAsymmetricKey()) + ); } /** @@ -53,5 +53,5 @@ public function decryptSessionKey( * @param AsymmetricKey $privateKey * @return string */ - protected abstract function decrypt(AsymmetricKey $privateKey): string; + abstract protected function decrypt(AsymmetricKey $privateKey): string; } diff --git a/src/Packet/LiteralData.php b/src/Packet/LiteralData.php index d67b3918..203dba17 100644 --- a/src/Packet/LiteralData.php +++ b/src/Packet/LiteralData.php @@ -12,23 +12,22 @@ use OpenPGP\Common\Helper; use OpenPGP\Enum\LiteralFormat as Format; use OpenPGP\Enum\PacketTag; -use OpenPGP\Type\{ - ForSigningInterface, - LiteralDataInterface, -}; +use OpenPGP\Type\{ForSigningInterface, LiteralDataInterface}; /** * Implementation of the Literal Data Packet (Tag 11) * * See RFC 9580, section 5.9. - * + * * A Literal Data packet contains the body of a message; data that is not to be further interpreted. * * @package OpenPGP * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class LiteralData extends AbstractPacket implements ForSigningInterface, LiteralDataInterface +class LiteralData extends AbstractPacket implements + ForSigningInterface, + LiteralDataInterface { private readonly DateTimeInterface $time; @@ -44,10 +43,9 @@ class LiteralData extends AbstractPacket implements ForSigningInterface, Literal public function __construct( private readonly string $data, private readonly Format $format = Format::Utf8, - private readonly string $filename = '', - ?DateTimeInterface $time = null, - ) - { + private readonly string $filename = "", + ?DateTimeInterface $time = null + ) { parent::__construct(PacketTag::LiteralData); $this->time = $time ?? (new \DateTime())->setTimestamp(time()); } @@ -70,9 +68,7 @@ public static function fromBytes(string $bytes): self $offset += 4; $data = substr($bytes, $offset); - return new self( - $data, $format, $filename, $time - ); + return new self($data, $format, $filename, $time); } /** @@ -86,12 +82,9 @@ public static function fromBytes(string $bytes): self public static function fromText( string $text, Format $format = Format::Utf8, - ?DateTimeInterface $time = null, - ): self - { - return new self( - $text, $format, '', $time - ); + ?DateTimeInterface $time = null + ): self { + return new self($text, $format, "", $time); } /** @@ -135,7 +128,7 @@ public function getHeader(): string chr($this->format->value), chr(strlen($this->filename)), $this->filename, - pack('N', $this->time->getTimestamp()), + pack("N", $this->time->getTimestamp()), ]); } @@ -144,10 +137,7 @@ public function getHeader(): string */ public function toBytes(): string { - return implode([ - $this->getHeader(), - $this->getSignBytes(), - ]); + return implode([$this->getHeader(), $this->getSignBytes()]); } /** @@ -158,13 +148,11 @@ public function getSignBytes(): string if ($this->format === Format::Text || $this->format === Format::Utf8) { // Remove trailing whitespace and normalize EOL to canonical form $data = Helper::removeTrailingSpaces( - mb_convert_encoding($this->data, 'UTF-8') + mb_convert_encoding($this->data, "UTF-8") ); - return preg_replace( - Helper::EOL_PATTERN, Helper::CRLF, $data - ) ?? $data; - } - else { + return preg_replace(Helper::EOL_PATTERN, Helper::CRLF, $data) ?? + $data; + } else { return $this->data; } } diff --git a/src/Packet/Marker.php b/src/Packet/Marker.php index ee778928..293abe6f 100644 --- a/src/Packet/Marker.php +++ b/src/Packet/Marker.php @@ -19,7 +19,7 @@ */ class Marker extends AbstractPacket { - const MARKER = 'PGP'; + const MARKER = "PGP"; /** * Constructor diff --git a/src/Packet/OnePassSignature.php b/src/Packet/OnePassSignature.php index dc1f2742..f4dbea7f 100644 --- a/src/Packet/OnePassSignature.php +++ b/src/Packet/OnePassSignature.php @@ -8,12 +8,7 @@ namespace OpenPGP\Packet; -use OpenPGP\Enum\{ - HashAlgorithm, - KeyAlgorithm, - PacketTag, - SignatureType, -}; +use OpenPGP\Enum\{HashAlgorithm, KeyAlgorithm, PacketTag, SignatureType}; /** * Implementation an OpenPGP One-Pass Signature packet (Tag 4). @@ -50,13 +45,12 @@ public function __construct( private readonly string $salt, private readonly string $issuerFingerprint, private readonly string $issuerKeyID, - private readonly int $nested = 0, - ) - { + private readonly int $nested = 0 + ) { parent::__construct(PacketTag::OnePassSignature); if ($version != self::VERSION_3 && $version != self::VERSION_6) { throw new \InvalidArgumentException( - "Version $version of the one-pass signature packet is unsupported.", + "Version $version of the one-pass signature packet is unsupported." ); } } @@ -79,8 +73,8 @@ public static function fromBytes(string $bytes): self // A one-octet number describing the public-key algorithm used. $keyAlgorithm = KeyAlgorithm::from(ord($bytes[$offset++])); - $salt = ''; - $issuerFingerprint = ''; + $salt = ""; + $issuerFingerprint = ""; if ($version === self::VERSION_6) { $saltLength = ord($bytes[$offset++]); $salt = substr($bytes, $offset, $saltLength); @@ -89,8 +83,7 @@ public static function fromBytes(string $bytes): self $issuerFingerprint = substr($bytes, $offset, 32); $offset += 32; $issuerKeyID = substr($issuerFingerprint, 0, 8); - } - else { + } else { // An eight-octet number holding the Key ID of the signing key. $issuerKeyID = substr($bytes, $offset, 8); $offset += 8; @@ -111,7 +104,7 @@ public static function fromBytes(string $bytes): self $salt, $issuerFingerprint, $issuerKeyID, - $nested, + $nested ); } @@ -122,18 +115,21 @@ public static function fromBytes(string $bytes): self * @param int $nested * @return self */ - public static function fromSignature(Signature $signature, int $nested = 0): self - { + public static function fromSignature( + Signature $signature, + int $nested = 0 + ): self { return new self( - $signature->getVersion() === self::VERSION_6 ? - self::VERSION_6 : self::VERSION_3, + $signature->getVersion() === self::VERSION_6 + ? self::VERSION_6 + : self::VERSION_3, $signature->getSignatureType(), $signature->getHashAlgorithm(), $signature->getKeyAlgorithm(), $signature->getSalt(), $signature->getIssuerFingerprint(), $signature->getIssuerKeyID(), - $nested, + $nested ); } @@ -232,8 +228,7 @@ public function toBytes(): string $data[] = chr(strlen($this->salt)); $data[] = $this->salt; $data[] = $this->issuerFingerprint; - } - else { + } else { $data[] = $this->issuerKeyID; } $data[] = chr($this->nested); diff --git a/src/Packet/PacketList.php b/src/Packet/PacketList.php index 1a909040..09d3058a 100644 --- a/src/Packet/PacketList.php +++ b/src/Packet/PacketList.php @@ -9,10 +9,7 @@ namespace OpenPGP\Packet; use OpenPGP\Enum\PacketTag; -use OpenPGP\Type\{ - PacketInterface, - PacketListInterface, -}; +use OpenPGP\Type\{PacketInterface, PacketListInterface}; use phpseclib3\Common\Functions\Strings; /** @@ -39,10 +36,12 @@ class PacketList implements PacketListInterface */ public function __construct(array $packets = []) { - $this->packets = array_values(array_filter( - $packets, - static fn ($packet) => $packet instanceof PacketInterface, - )); + $this->packets = array_values( + array_filter( + $packets, + static fn($packet) => $packet instanceof PacketInterface + ) + ); } /** @@ -60,15 +59,13 @@ public static function decode(string $bytes): self $packets[] = match ($reader->getTag()) { PacketTag::PublicKeyEncryptedSessionKey => PublicKeyEncryptedSessionKey::fromBytes( - $reader->getData() - ), + $reader->getData() + ), PacketTag::Signature => Signature::fromBytes( $reader->getData() ), PacketTag::SymEncryptedSessionKey - => SymEncryptedSessionKey::fromBytes( - $reader->getData() - ), + => SymEncryptedSessionKey::fromBytes($reader->getData()), PacketTag::OnePassSignature => OnePassSignature::fromBytes( $reader->getData() ), @@ -91,12 +88,8 @@ public static function decode(string $bytes): self PacketTag::LiteralData => LiteralData::fromBytes( $reader->getData() ), - PacketTag::Trust => Trust::fromBytes( - $reader->getData() - ), - PacketTag::UserID => UserID::fromBytes( - $reader->getData() - ), + PacketTag::Trust => Trust::fromBytes($reader->getData()), + PacketTag::UserID => UserID::fromBytes($reader->getData()), PacketTag::PublicSubkey => PublicSubkey::fromBytes( $reader->getData() ), @@ -105,14 +98,12 @@ public static function decode(string $bytes): self ), PacketTag::SymEncryptedIntegrityProtectedData => SymEncryptedIntegrityProtectedData::fromBytes( - $reader->getData() - ), - PacketTag::AeadEncryptedData => AeadEncryptedData::fromBytes( $reader->getData() ), - PacketTag::Padding => Padding::fromBytes( + PacketTag::AeadEncryptedData => AeadEncryptedData::fromBytes( $reader->getData() ), + PacketTag::Padding => Padding::fromBytes($reader->getData()), default => null, }; } @@ -132,10 +123,12 @@ public function getPackets(): array */ public function encode(): string { - return implode(array_map( - static fn ($packet): string => $packet->encode(), - $this->packets - )); + return implode( + array_map( + static fn($packet): string => $packet->encode(), + $this->packets + ) + ); } /** @@ -159,10 +152,12 @@ public function count(): int */ public function whereTag(PacketTag $tag): self { - $packets = array_values(array_filter( - $this->packets, - static fn ($packet) => $packet->getTag() === $tag, - )); + $packets = array_values( + array_filter( + $this->packets, + static fn($packet) => $packet->getTag() === $tag + ) + ); return new self($packets); } @@ -171,10 +166,12 @@ public function whereTag(PacketTag $tag): self */ public function whereType(string $type): self { - $packets = array_values(array_filter( - $this->packets, - static fn ($packet) => $packet instanceof $type, - )); + $packets = array_values( + array_filter( + $this->packets, + static fn($packet) => $packet instanceof $type + ) + ); return new self($packets); } diff --git a/src/Packet/PacketReader.php b/src/Packet/PacketReader.php index 6c7b3d81..7effca48 100644 --- a/src/Packet/PacketReader.php +++ b/src/Packet/PacketReader.php @@ -30,10 +30,9 @@ class PacketReader */ public function __construct( private readonly PacketTag $tag, - private readonly string $data = '', - private readonly int $length = 0, - ) - { + private readonly string $data = "", + private readonly int $length = 0 + ) { } /** @@ -75,19 +74,20 @@ public function getLength(): int public static function read(string $bytes): self { $offset = 0; - if (strlen(substr($bytes, $offset)) < 2 || (ord($bytes[$offset]) & 0x80) === 0) { + if ( + strlen(substr($bytes, $offset)) < 2 || + (ord($bytes[$offset]) & 0x80) === 0 + ) { throw new \RuntimeException( - 'Data probably does not conform to a valid OpenPGP format.', + "Data probably does not conform to a valid OpenPGP format." ); } $header = ord($bytes[$offset++]); - $isOld = (($header & 0x40) != 0) ? false : true; - $tag = PacketTag::from( - $isOld ? ($header & 0x3f) >> 2 : $header & 0x3f - ); + $isOld = ($header & 0x40) != 0 ? false : true; + $tag = PacketTag::from($isOld ? ($header & 0x3f) >> 2 : $header & 0x3f); - $data = ''; + $data = ""; if ($isOld) { switch ($header & 0x03) { case 0: @@ -105,60 +105,69 @@ public static function read(string $bytes): self $dataLength = strlen($bytes) - $offset; } $data = substr($bytes, $offset, $dataLength); - } - else { + } else { $dataLength = ord($bytes[$offset++]); if ($dataLength < 192) { $data = substr($bytes, $offset, $dataLength); - } - elseif ($dataLength < 224) { - $dataLength = (($dataLength - 192) << 8) + (ord($bytes[$offset++])) + 192; + } elseif ($dataLength < 224) { + $dataLength = + ($dataLength - 192 << 8) + ord($bytes[$offset++]) + 192; $data = substr($bytes, $offset, $dataLength); - } - elseif ($dataLength < 255) { + } elseif ($dataLength < 255) { $partialLen = 1 << ($dataLength & 0x1f); $partialData = [substr($bytes, $offset, $partialLen)]; $partialPos = $offset + $partialLen; while (true) { $partialLen = ord($bytes[$partialPos++]); if ($partialLen < 192) { - $partialData[] = substr($bytes, $partialPos, $partialLen); + $partialData[] = substr( + $bytes, + $partialPos, + $partialLen + ); $partialPos += $partialLen; break; - } - elseif ($partialLen < 224) { - $partialLen = (($partialLen - 192) << 8) + (ord($bytes[$partialPos++])) + 192; - $partialData[] = substr($bytes, $partialPos, $partialLen); + } elseif ($partialLen < 224) { + $partialLen = + ($partialLen - 192 << 8) + + ord($bytes[$partialPos++]) + + 192; + $partialData[] = substr( + $bytes, + $partialPos, + $partialLen + ); $partialPos += $partialLen; break; - } - elseif ($partialLen < 255) { + } elseif ($partialLen < 255) { $partialLen = 1 << ($partialLen & 0x1f); - $partialData[] = substr($bytes, $partialPos, $partialLen); + $partialData[] = substr( + $bytes, + $partialPos, + $partialLen + ); $partialPos += $partialLen; - } - else { + } else { $partialLen = Helper::bytesToLong($bytes, $partialPos); $partialPos += 4; - $partialData[] = substr($bytes, $partialPos, $partialLen); + $partialData[] = substr( + $bytes, + $partialPos, + $partialLen + ); $partialPos += $partialLen; break; } } $data = implode($partialData); $dataLength = $partialPos - $offset; - } - else { + } else { $dataLength = Helper::bytesToLong($bytes, $offset); $offset += 4; $data = substr($bytes, $offset, $dataLength); } } - return new self( - $tag, - $data, - $offset + $dataLength, - ); + return new self($tag, $data, $offset + $dataLength); } } diff --git a/src/Packet/PublicKey.php b/src/Packet/PublicKey.php index 3a27b23f..ca67a547 100644 --- a/src/Packet/PublicKey.php +++ b/src/Packet/PublicKey.php @@ -9,23 +9,20 @@ namespace OpenPGP\Packet; use DateTimeInterface; -use OpenPGP\Common\{ - Config, - Helper, -}; +use OpenPGP\Common\{Config, Helper}; use OpenPGP\Enum\{ CurveOid, EdDSACurve, HashAlgorithm, KeyAlgorithm, MontgomeryCurve, - PacketTag, + PacketTag }; use OpenPGP\Type\{ ECKeyMaterialInterface, PublicKeyPacketInterface, KeyMaterialInterface, - SubkeyPacketInterface, + SubkeyPacketInterface }; use phpseclib3\Common\Functions\Strings; @@ -40,10 +37,10 @@ */ class PublicKey extends AbstractPacket implements PublicKeyPacketInterface { - const VERSION_4 = 4; - const VERSION_6 = 6; - const V4_HASH = 'sha1'; - const V6_HASH = 'sha256'; + const VERSION_4 = 4; + const VERSION_6 = 6; + const V4_HASH = "sha1"; + const V6_HASH = "sha256"; const KEY_ID_SIZE = 8; /** @@ -69,46 +66,48 @@ public function __construct( private readonly int $version, private readonly DateTimeInterface $creationTime, private readonly KeyAlgorithm $keyAlgorithm, - private readonly KeyMaterialInterface $keyMaterial, - ) - { + private readonly KeyMaterialInterface $keyMaterial + ) { parent::__construct( - $this instanceof SubkeyPacketInterface ? - PacketTag::PublicSubkey : PacketTag::PublicKey + $this instanceof SubkeyPacketInterface + ? PacketTag::PublicSubkey + : PacketTag::PublicKey ); if ($version !== self::VERSION_4 && $version !== self::VERSION_6) { throw new \InvalidArgumentException( - "Version {$version} of the key packet is unsupported.", + "Version {$version} of the key packet is unsupported." ); } $isV6 = $version === self::VERSION_6; if ($isV6) { - if (($keyMaterial instanceof Key\ECPublicKeyMaterial)) { + if ($keyMaterial instanceof Key\ECPublicKeyMaterial) { $curveOid = $keyMaterial->getCurveOid(); - if (($curveOid === CurveOid::Ed25519) || - ($curveOid === CurveOid::Curve25519) + if ( + $curveOid === CurveOid::Ed25519 || + $curveOid === CurveOid::Curve25519 ) { throw new \InvalidArgumentException( - "Legacy curve {$curveOid->name} cannot be used with v{$version} key packet.", + "Legacy curve {$curveOid->name} cannot be used with v{$version} key packet." ); } } - if (($keyAlgorithm === KeyAlgorithm::Dsa) || - ($keyAlgorithm === KeyAlgorithm::ElGamal) + if ( + $keyAlgorithm === KeyAlgorithm::Dsa || + $keyAlgorithm === KeyAlgorithm::ElGamal ) { throw new \InvalidArgumentException( - "Key algorithm {$keyAlgorithm->name} cannot be used with v{$version} key packet.", + "Key algorithm {$keyAlgorithm->name} cannot be used with v{$version} key packet." ); } } - $this->fingerprint = $isV6 ? - hash(self::V6_HASH, $this->getSignBytes(), true) : - hash(self::V4_HASH, $this->getSignBytes(), true); - $this->keyID = $isV6 ? - substr($this->fingerprint, 0, self::KEY_ID_SIZE) : - substr($this->fingerprint, 12, self::KEY_ID_SIZE); + $this->fingerprint = $isV6 + ? hash(self::V6_HASH, $this->getSignBytes(), true) + : hash(self::V4_HASH, $this->getSignBytes(), true); + $this->keyID = $isV6 + ? substr($this->fingerprint, 0, self::KEY_ID_SIZE) + : substr($this->fingerprint, 12, self::KEY_ID_SIZE); } /** @@ -137,15 +136,11 @@ public static function fromBytes(string $bytes): self // A series of values comprising the key material. $keyMaterial = self::readKeyMaterial( - substr($bytes, $offset), $keyAlgorithm + substr($bytes, $offset), + $keyAlgorithm ); - return new self( - $version, - $creationTime, - $keyAlgorithm, - $keyMaterial, - ); + return new self($version, $creationTime, $keyAlgorithm, $keyMaterial); } /** @@ -156,9 +151,11 @@ public function toBytes(): string $kmBytes = $this->keyMaterial->toBytes(); return implode([ chr($this->version), - pack('N', $this->creationTime->getTimestamp()), + pack("N", $this->creationTime->getTimestamp()), chr($this->keyAlgorithm->value), - ($this->version === self::VERSION_6) ? pack('N', strlen($kmBytes)) : '', + $this->version === self::VERSION_6 + ? pack("N", strlen($kmBytes)) + : "", $kmBytes, ]); } @@ -200,8 +197,9 @@ public function getKeyMaterial(): ?KeyMaterialInterface */ public function getECKeyMaterial(): ?ECKeyMaterialInterface { - return $this->keyMaterial instanceof ECKeyMaterialInterface ? - $this->keyMaterial : null; + return $this->keyMaterial instanceof ECKeyMaterialInterface + ? $this->keyMaterial + : null; } /** @@ -209,7 +207,9 @@ public function getECKeyMaterial(): ?ECKeyMaterialInterface */ public function getFingerprint(bool $toHex = false): string { - return $toHex ? Strings::bin2hex($this->fingerprint) : $this->fingerprint; + return $toHex + ? Strings::bin2hex($this->fingerprint) + : $this->fingerprint; } /** @@ -257,8 +257,7 @@ public function isEncryptionKey(): bool */ public function getPreferredHash( ?HashAlgorithm $preferredHash = null - ): HashAlgorithm - { + ): HashAlgorithm { return match (true) { $this->keyMaterial instanceof Key\ECPublicKeyMaterial => $this->keyMaterial->getCurveOid()->hashAlgorithm(), @@ -276,7 +275,7 @@ public function getPreferredHash( public function getSignBytes(): string { $bytes = $this->toBytes(); - $format = ($this->version === self::VERSION_6) ? 'N' : 'n'; + $format = $this->version === self::VERSION_6 ? "N" : "n"; return implode([ chr(0x95 + $this->version), pack($format, strlen($bytes)), @@ -285,37 +284,40 @@ public function getSignBytes(): string } private static function readKeyMaterial( - string $bytes, KeyAlgorithm $keyAlgorithm - ): KeyMaterialInterface - { - return match($keyAlgorithm) { + string $bytes, + KeyAlgorithm $keyAlgorithm + ): KeyMaterialInterface { + return match ($keyAlgorithm) { KeyAlgorithm::RsaEncryptSign, KeyAlgorithm::RsaEncrypt, KeyAlgorithm::RsaSign => Key\RSAPublicKeyMaterial::fromBytes($bytes), - KeyAlgorithm::ElGamal => Key\ElGamalPublicKeyMaterial::fromBytes($bytes), + KeyAlgorithm::ElGamal => Key\ElGamalPublicKeyMaterial::fromBytes( + $bytes + ), KeyAlgorithm::Dsa => Key\DSAPublicKeyMaterial::fromBytes($bytes), KeyAlgorithm::Ecdh => Key\ECDHPublicKeyMaterial::fromBytes($bytes), - KeyAlgorithm::EcDsa => Key\ECDSAPublicKeyMaterial::fromBytes($bytes), - KeyAlgorithm::EdDsaLegacy => Key\EdDSALegacyPublicKeyMaterial::fromBytes($bytes), - KeyAlgorithm::X25519 - => Key\MontgomeryPublicKeyMaterial::fromBytes( - substr($bytes, 0, MontgomeryCurve::Curve25519->payloadSize()) - ), - KeyAlgorithm::X448 - => Key\MontgomeryPublicKeyMaterial::fromBytes( - substr($bytes, 0, MontgomeryCurve::Curve448->payloadSize()) - ), - KeyAlgorithm::Ed25519 - => Key\EdDSAPublicKeyMaterial::fromBytes( - $bytes, EdDSACurve::Ed25519 - ), - KeyAlgorithm::Ed448 - => Key\EdDSAPublicKeyMaterial::fromBytes( - $bytes, EdDSACurve::Ed448 - ), + KeyAlgorithm::EcDsa => Key\ECDSAPublicKeyMaterial::fromBytes( + $bytes + ), + KeyAlgorithm::EdDsaLegacy + => Key\EdDSALegacyPublicKeyMaterial::fromBytes($bytes), + KeyAlgorithm::X25519 => Key\MontgomeryPublicKeyMaterial::fromBytes( + substr($bytes, 0, MontgomeryCurve::Curve25519->payloadSize()) + ), + KeyAlgorithm::X448 => Key\MontgomeryPublicKeyMaterial::fromBytes( + substr($bytes, 0, MontgomeryCurve::Curve448->payloadSize()) + ), + KeyAlgorithm::Ed25519 => Key\EdDSAPublicKeyMaterial::fromBytes( + $bytes, + EdDSACurve::Ed25519 + ), + KeyAlgorithm::Ed448 => Key\EdDSAPublicKeyMaterial::fromBytes( + $bytes, + EdDSACurve::Ed448 + ), default => throw new \RuntimeException( - "Key algorithm {$keyAlgorithm->name} is unsupported.", + "Key algorithm {$keyAlgorithm->name} is unsupported." ), }; } diff --git a/src/Packet/PublicKeyEncryptedSessionKey.php b/src/Packet/PublicKeyEncryptedSessionKey.php index a2936512..db99af89 100644 --- a/src/Packet/PublicKeyEncryptedSessionKey.php +++ b/src/Packet/PublicKeyEncryptedSessionKey.php @@ -8,16 +8,12 @@ namespace OpenPGP\Packet; -use OpenPGP\Enum\{ - KeyAlgorithm, - MontgomeryCurve, - PacketTag, -}; +use OpenPGP\Enum\{KeyAlgorithm, MontgomeryCurve, PacketTag}; use OpenPGP\Type\{ KeyPacketInterface, SecretKeyPacketInterface, - SessionKeyInterface, SessionKeyCryptorInterface, + SessionKeyInterface }; use phpseclib3\Common\Functions\Strings; @@ -32,8 +28,8 @@ */ class PublicKeyEncryptedSessionKey extends AbstractPacket { - const VERSION_3 = 3; - const VERSION_6 = 6; + const VERSION_3 = 3; + const VERSION_6 = 6; const KEY_ID_SIZE = 8; /** @@ -54,20 +50,20 @@ public function __construct( private readonly string $keyFingerprint, private readonly KeyAlgorithm $keyAlgorithm, private readonly SessionKeyCryptorInterface $sessionKeyCryptor, - private readonly ?SessionKeyInterface $sessionKey = null, - ) - { + private readonly ?SessionKeyInterface $sessionKey = null + ) { parent::__construct(PacketTag::PublicKeyEncryptedSessionKey); if ($version !== self::VERSION_3 && $version !== self::VERSION_6) { throw new \InvalidArgumentException( - "Version {$version} of the PKESK packet is unsupported.", + "Version {$version} of the PKESK packet is unsupported." ); } - if ($version === self::VERSION_6 && + if ( + $version === self::VERSION_6 && $keyAlgorithm === KeyAlgorithm::ElGamal ) { throw new \InvalidArgumentException( - "Key algorithm {$keyAlgorithm->name} cannot be used with v{$version} PKESK packet.", + "Key algorithm {$keyAlgorithm->name} cannot be used with v{$version} PKESK packet." ); } } @@ -85,15 +81,15 @@ public static function fromBytes(string $bytes): self $keyVersion = ord($bytes[$offset++]); $keyFingerprint = substr($bytes, $offset, $length - 1); $offset += $length - 1; - $keyID = $keyVersion === PublicKey::VERSION_6 ? - substr($keyFingerprint, 0, self::KEY_ID_SIZE) : - substr($keyFingerprint, 12, self::KEY_ID_SIZE); - } - else { + $keyID = + $keyVersion === PublicKey::VERSION_6 + ? substr($keyFingerprint, 0, self::KEY_ID_SIZE) + : substr($keyFingerprint, 12, self::KEY_ID_SIZE); + } else { $keyID = substr($bytes, $offset, self::KEY_ID_SIZE); $offset += self::KEY_ID_SIZE; $keyVersion = 0; - $keyFingerprint = ''; + $keyFingerprint = ""; } $keyAlgorithm = KeyAlgorithm::from(ord($bytes[$offset++])); @@ -103,9 +99,7 @@ public static function fromBytes(string $bytes): self $keyVersion, $keyFingerprint, $keyAlgorithm, - self::readMaterial( - substr($bytes, $offset), $keyAlgorithm - ), + self::readMaterial(substr($bytes, $offset), $keyAlgorithm) ); } @@ -118,21 +112,20 @@ public static function fromBytes(string $bytes): self */ public static function encryptSessionKey( KeyPacketInterface $keyPacket, - SessionKeyInterface $sessionKey, - ): self - { - $version = $keyPacket->getVersion() === self::VERSION_6 ? - self::VERSION_6 : self::VERSION_3; + SessionKeyInterface $sessionKey + ): self { + $version = + $keyPacket->getVersion() === self::VERSION_6 + ? self::VERSION_6 + : self::VERSION_3; return new self( $version, $keyPacket->getKeyID(), $keyPacket->getVersion(), $keyPacket->getFingerprint(), $keyPacket->getKeyAlgorithm(), - self::produceSessionKeyCryptor( - $sessionKey, $keyPacket - ), - $sessionKey, + self::produceSessionKeyCryptor($sessionKey, $keyPacket), + $sessionKey ); } @@ -141,15 +134,12 @@ public static function encryptSessionKey( */ public function toBytes(): string { - $bytes = [ - chr($this->version), - ]; + $bytes = [chr($this->version)]; if ($this->version === self::VERSION_6) { $bytes[] = chr(strlen($this->keyFingerprint) + 1); $bytes[] = chr($this->keyVersion); $bytes[] = $this->keyFingerprint; - } - else { + } else { $bytes[] = $this->keyID; } $bytes[] = chr($this->keyAlgorithm->value); @@ -196,9 +186,9 @@ public function getKeyVersion(): int */ public function getKeyFingerprint(bool $toHex = false): string { - return $toHex ? - Strings::bin2hex($this->keyFingerprint) : - $this->keyFingerprint; + return $toHex + ? Strings::bin2hex($this->keyFingerprint) + : $this->keyFingerprint; } /** @@ -241,8 +231,7 @@ public function decrypt(SecretKeyPacketInterface $secretKey): self { if ($this->sessionKey instanceof SessionKeyInterface) { return $this; - } - else { + } else { return new self( $this->version, $secretKey->getKeyID(), @@ -250,27 +239,23 @@ public function decrypt(SecretKeyPacketInterface $secretKey): self $secretKey->getFingerprint(), $secretKey->getKeyAlgorithm(), $this->sessionKeyCryptor, - $this->decryptSessionKey($secretKey), + $this->decryptSessionKey($secretKey) ); } } private function decryptSessionKey( SecretKeyPacketInterface $secretKey - ): SessionKeyInterface - { - $this->getLogger()->debug( - 'Decrypt public key encrypted session key.' - ); + ): SessionKeyInterface { + $this->getLogger()->debug("Decrypt public key encrypted session key."); return match ($this->keyAlgorithm) { KeyAlgorithm::RsaEncryptSign, KeyAlgorithm::RsaEncrypt, KeyAlgorithm::ElGamal, KeyAlgorithm::Ecdh, KeyAlgorithm::X25519, - KeyAlgorithm::X448 => $this->sessionKeyCryptor->decryptSessionKey( - $secretKey - ), + KeyAlgorithm::X448 + => $this->sessionKeyCryptor->decryptSessionKey($secretKey), default => throw new \RuntimeException( "Key algorithm {$this->keyAlgorithm->name} is unsupported." ), @@ -279,27 +264,30 @@ private function decryptSessionKey( private static function produceSessionKeyCryptor( SessionKeyInterface $sessionKey, - KeyPacketInterface $keyPacket, - ): SessionKeyCryptorInterface - { - return match($keyPacket->getKeyAlgorithm()) { - KeyAlgorithm::RsaEncryptSign, KeyAlgorithm::RsaEncrypt - => Key\RSASessionKeyCryptor::encryptSessionKey( + KeyPacketInterface $keyPacket + ): SessionKeyCryptorInterface { + return match ($keyPacket->getKeyAlgorithm()) { + KeyAlgorithm::RsaEncryptSign, + KeyAlgorithm::RsaEncrypt + => Key\RSASessionKeyCryptor::encryptSessionKey( $sessionKey, - $keyPacket->getKeyMaterial()->getAsymmetricKey(), + $keyPacket->getKeyMaterial()->getAsymmetricKey() ), KeyAlgorithm::Ecdh => Key\ECDHSessionKeyCryptor::encryptSessionKey( - $sessionKey, $keyPacket + $sessionKey, + $keyPacket ), - KeyAlgorithm::X25519 => Key\MontgomerySessionKeyCryptor::encryptSessionKey( + KeyAlgorithm::X25519 + => Key\MontgomerySessionKeyCryptor::encryptSessionKey( $sessionKey, $keyPacket->getECKeyMaterial()->getECKey(), - MontgomeryCurve::Curve25519, + MontgomeryCurve::Curve25519 ), - KeyAlgorithm::X448 => Key\MontgomerySessionKeyCryptor::encryptSessionKey( + KeyAlgorithm::X448 + => Key\MontgomerySessionKeyCryptor::encryptSessionKey( $sessionKey, $keyPacket->getECKeyMaterial()->getECKey(), - MontgomeryCurve::Curve448, + MontgomeryCurve::Curve448 ), default => throw new \RuntimeException( "Key algorithm {$keyPacket->getKeyAlgorithm()->name} is unsupported." @@ -308,19 +296,24 @@ private static function produceSessionKeyCryptor( } private static function readMaterial( - string $bytes, KeyAlgorithm $keyAlgorithm - ): SessionKeyCryptorInterface - { - return match($keyAlgorithm) { - KeyAlgorithm::RsaEncryptSign, KeyAlgorithm::RsaEncrypt - => Key\RSASessionKeyCryptor::fromBytes($bytes), - KeyAlgorithm::ElGamal => Key\ElGamalSessionKeyCryptor::fromBytes($bytes), + string $bytes, + KeyAlgorithm $keyAlgorithm + ): SessionKeyCryptorInterface { + return match ($keyAlgorithm) { + KeyAlgorithm::RsaEncryptSign, + KeyAlgorithm::RsaEncrypt + => Key\RSASessionKeyCryptor::fromBytes($bytes), + KeyAlgorithm::ElGamal => Key\ElGamalSessionKeyCryptor::fromBytes( + $bytes + ), KeyAlgorithm::Ecdh => Key\ECDHSessionKeyCryptor::fromBytes($bytes), KeyAlgorithm::X25519 => Key\MontgomerySessionKeyCryptor::fromBytes( - $bytes, MontgomeryCurve::Curve25519 + $bytes, + MontgomeryCurve::Curve25519 ), KeyAlgorithm::X448 => Key\MontgomerySessionKeyCryptor::fromBytes( - $bytes, MontgomeryCurve::Curve448 + $bytes, + MontgomeryCurve::Curve448 ), default => throw new \RuntimeException( "Key algorithm {$keyAlgorithm->name} is unsupported." diff --git a/src/Packet/PublicSubkey.php b/src/Packet/PublicSubkey.php index b97ea1db..1624a9b6 100644 --- a/src/Packet/PublicSubkey.php +++ b/src/Packet/PublicSubkey.php @@ -10,10 +10,7 @@ use DateTimeInterface; use OpenPGP\Enum\KeyAlgorithm; -use OpenPGP\Type\{ - KeyMaterialInterface, - SubkeyPacketInterface, -}; +use OpenPGP\Type\{KeyMaterialInterface, SubkeyPacketInterface}; /** * Implementation an OpenPGP sub public key packet (Tag 14). @@ -39,15 +36,9 @@ public function __construct( int $version, DateTimeInterface $creationTime, KeyAlgorithm $algorithm, - KeyMaterialInterface $keyMaterial, - ) - { - parent::__construct( - $version, - $creationTime, - $algorithm, - $keyMaterial, - ); + KeyMaterialInterface $keyMaterial + ) { + parent::__construct($version, $creationTime, $algorithm, $keyMaterial); } /** @@ -60,7 +51,7 @@ public static function fromBytes(string $bytes): self $publicKey->getVersion(), $publicKey->getCreationTime(), $publicKey->getKeyAlgorithm(), - $publicKey->getKeyMaterial(), + $publicKey->getKeyMaterial() ); } } diff --git a/src/Packet/SecretKey.php b/src/Packet/SecretKey.php index 6aa2a74f..48c4961a 100644 --- a/src/Packet/SecretKey.php +++ b/src/Packet/SecretKey.php @@ -9,12 +9,7 @@ namespace OpenPGP\Packet; use DateTimeInterface; -use OpenPGP\Common\{ - Argon2S2K, - Config, - GenericS2K, - Helper, -}; +use OpenPGP\Common\{Argon2S2K, Config, GenericS2K, Helper}; use OpenPGP\Enum\{ AeadAlgorithm, CurveOid, @@ -26,7 +21,7 @@ RSAKeySize, S2kType, S2kUsage, - SymmetricAlgorithm, + SymmetricAlgorithm }; use OpenPGP\Type\{ ECKeyMaterialInterface, @@ -34,7 +29,7 @@ PublicKeyPacketInterface, S2KInterface, SecretKeyPacketInterface, - SubkeyPacketInterface, + SubkeyPacketInterface }; use phpseclib3\Crypt\Random; @@ -49,7 +44,7 @@ */ class SecretKey extends AbstractPacket implements SecretKeyPacketInterface { - const HASH_ALGO = 'sha1'; + const HASH_ALGO = "sha1"; const ZERO_CHAR = "\x00"; /** @@ -66,25 +61,26 @@ class SecretKey extends AbstractPacket implements SecretKeyPacketInterface */ public function __construct( private readonly PublicKey $publicKey, - private readonly string $keyData = '', + private readonly string $keyData = "", private readonly ?KeyMaterialInterface $keyMaterial = null, private readonly S2kUsage $s2kUsage = S2kUsage::None, private readonly SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Plaintext, private readonly ?S2KInterface $s2k = null, private readonly ?AeadAlgorithm $aead = null, - private readonly string $iv = '', - ) - { + private readonly string $iv = "" + ) { parent::__construct( - $this instanceof SubkeyPacketInterface ? - PacketTag::SecretSubkey : PacketTag::SecretKey + $this instanceof SubkeyPacketInterface + ? PacketTag::SecretSubkey + : PacketTag::SecretKey ); - if ($publicKey->getVersion() === PublicKey::VERSION_6 && - ($s2kUsage === S2kUsage::MalleableCfb)) - { + if ( + $publicKey->getVersion() === PublicKey::VERSION_6 && + $s2kUsage === S2kUsage::MalleableCfb + ) { throw new \InvalidArgumentException( - "S2k usage {$s2kUsage->name} cannot be used with v{$publicKey->getVersion()} key packet.", + "S2k usage {$s2kUsage->name} cannot be used with v{$publicKey->getVersion()} key packet." ); } } @@ -111,9 +107,7 @@ public static function fromBytes(string $bytes): self case S2kUsage::Cfb: case S2kUsage::AeadProtect: // one-octet symmetric encryption algorithm. - $symmetric = SymmetricAlgorithm::from( - ord($bytes[$offset++]) - ); + $symmetric = SymmetricAlgorithm::from(ord($bytes[$offset++])); // If s2k usage octet was 253, a one-octet AEAD algorithm. if ($s2kUsage === S2kUsage::AeadProtect) { @@ -122,14 +116,19 @@ public static function fromBytes(string $bytes): self // Only for a version 6 packet, and if string-to-key usage // octet was 253 or 254, an one-octet count of the following field. - if ($isV6 && ($s2kUsage === S2kUsage::AeadProtect || $s2kUsage === S2kUsage::Cfb)) { + if ( + $isV6 && + ($s2kUsage === S2kUsage::AeadProtect || + $s2kUsage === S2kUsage::Cfb) + ) { $offset++; } $s2kType = S2kType::from(ord($bytes[$offset])); - $s2k = ($s2kType === S2kType::Argon2) ? - Argon2S2K::fromBytes(substr($bytes, $offset)) : - GenericS2K::fromBytes(substr($bytes, $offset)); + $s2k = + $s2kType === S2kType::Argon2 + ? Argon2S2K::fromBytes(substr($bytes, $offset)) + : GenericS2K::fromBytes(substr($bytes, $offset)); $offset += $s2kType->dataLength(); break; default: @@ -137,11 +136,10 @@ public static function fromBytes(string $bytes): self break; } - $iv = ''; + $iv = ""; if ($aead instanceof AeadAlgorithm) { $iv = substr($bytes, $offset, $aead->ivLength()); - } - else { + } else { $iv = substr($bytes, $offset, $symmetric->blockSize()); } $offset += strlen($iv); @@ -152,8 +150,10 @@ public static function fromBytes(string $bytes): self if (!$isV6) { $checksum = substr($keyData, strlen($keyData) - 2); $keyData = substr($keyData, 0, strlen($keyData) - 2); - if (strcmp(Helper::computeChecksum($keyData), $checksum) !== 0) { - throw new \RuntimeException('Key checksum mismatch!'); + if ( + strcmp(Helper::computeChecksum($keyData), $checksum) !== 0 + ) { + throw new \RuntimeException("Key checksum mismatch!"); } } $keyMaterial = self::readKeyMaterial($keyData, $publicKey); @@ -167,7 +167,7 @@ public static function fromBytes(string $bytes): self $symmetric, $s2k, $aead, - $iv, + $iv ); } @@ -184,32 +184,33 @@ public static function generate( KeyAlgorithm $keyAlgorithm = KeyAlgorithm::RsaEncryptSign, RSAKeySize $rsaKeySize = RSAKeySize::Normal, CurveOid $curveOid = CurveOid::Secp521r1, - ?DateTimeInterface $time = null, - ): self - { - $keyMaterial = match($keyAlgorithm) { + ?DateTimeInterface $time = null + ): self { + $keyMaterial = match ($keyAlgorithm) { KeyAlgorithm::RsaEncryptSign, KeyAlgorithm::RsaEncrypt, KeyAlgorithm::RsaSign => Key\RSASecretKeyMaterial::generate($rsaKeySize), - KeyAlgorithm::Ecdh - => Key\ECDHSecretKeyMaterial::generate($curveOid), - KeyAlgorithm::EcDsa - => Key\ECDSASecretKeyMaterial::generate($curveOid), + KeyAlgorithm::Ecdh => Key\ECDHSecretKeyMaterial::generate( + $curveOid + ), + KeyAlgorithm::EcDsa => Key\ECDSASecretKeyMaterial::generate( + $curveOid + ), KeyAlgorithm::EdDsaLegacy => Key\EdDSALegacySecretKeyMaterial::generate(), - KeyAlgorithm::X25519 - => Key\MontgomerySecretKeyMaterial::generate( - MontgomeryCurve::Curve25519 - ), - KeyAlgorithm::X448 - => Key\MontgomerySecretKeyMaterial::generate( - MontgomeryCurve::Curve448 - ), - KeyAlgorithm::Ed25519 - => Key\EdDSASecretKeyMaterial::generate(EdDSACurve::Ed25519), - KeyAlgorithm::Ed448 - => Key\EdDSASecretKeyMaterial::generate(EdDSACurve::Ed448), + KeyAlgorithm::X25519 => Key\MontgomerySecretKeyMaterial::generate( + MontgomeryCurve::Curve25519 + ), + KeyAlgorithm::X448 => Key\MontgomerySecretKeyMaterial::generate( + MontgomeryCurve::Curve448 + ), + KeyAlgorithm::Ed25519 => Key\EdDSASecretKeyMaterial::generate( + EdDSACurve::Ed25519 + ), + KeyAlgorithm::Ed448 => Key\EdDSASecretKeyMaterial::generate( + EdDSACurve::Ed448 + ), default => throw new \RuntimeException( "Key algorithm {$keyAlgorithm->name} is unsupported." ), @@ -220,18 +221,19 @@ public static function generate( KeyAlgorithm::Ed25519, KeyAlgorithm::Ed448 => PublicKey::VERSION_6, - default => Config::useV6Key() ? - PublicKey::VERSION_6 : PublicKey::VERSION_4, + default => Config::useV6Key() + ? PublicKey::VERSION_6 + : PublicKey::VERSION_4, }; return new self( new PublicKey( $version, $time ?? new \DateTime(), $keyAlgorithm, - $keyMaterial->getPublicMaterial(), + $keyMaterial->getPublicMaterial() ), $keyMaterial->toBytes(), - $keyMaterial, + $keyMaterial ); } @@ -244,25 +246,24 @@ public function toBytes(): string if ($this->isEncrypted()) { $optBytes = implode([ chr($this->symmetric->value), - !empty($this->aead) ? chr($this->aead->value) : '', - $isV6 ? chr($this->s2k->getLength()) : '', + !empty($this->aead) ? chr($this->aead->value) : "", + $isV6 ? chr($this->s2k->getLength()) : "", $this->s2k->toBytes(), $this->iv, ]); return implode([ $this->publicKey->toBytes(), chr($this->s2kUsage->value), - $isV6 ? chr(strlen($optBytes)) : '', + $isV6 ? chr(strlen($optBytes)) : "", $optBytes, $this->keyData, ]); - } - else { + } else { return implode([ $this->publicKey->toBytes(), chr(S2kUsage::None->value), $this->keyData, - $isV6 ? '' : Helper::computeChecksum($this->keyData), + $isV6 ? "" : Helper::computeChecksum($this->keyData), ]); } } @@ -320,8 +321,9 @@ public function getKeyMaterial(): ?KeyMaterialInterface */ public function getECKeyMaterial(): ?ECKeyMaterialInterface { - return $this->keyMaterial instanceof ECKeyMaterialInterface ? - $this->keyMaterial : null; + return $this->keyMaterial instanceof ECKeyMaterialInterface + ? $this->keyMaterial + : null; } /** @@ -361,8 +363,7 @@ public function isSubkey(): bool */ public function getPreferredHash( ?HashAlgorithm $preferredHash = null - ): HashAlgorithm - { + ): HashAlgorithm { return $this->publicKey->getPreferredHash($preferredHash); } @@ -387,8 +388,8 @@ public function getPublicKey(): PublicKeyPacketInterface */ public function isEncrypted(): bool { - return ($this->s2k instanceof S2KInterface) && - ($this->s2kUsage !== S2kUsage::None); + return $this->s2k instanceof S2KInterface && + $this->s2kUsage !== S2kUsage::None; } /** @@ -405,12 +406,11 @@ public function isDecrypted(): bool public function encrypt( string $passphrase, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ?AeadAlgorithm $aead = null, - ): self - { + ?AeadAlgorithm $aead = null + ): self { if ($this->isDecrypted()) { $this->getLogger()->debug( - 'Encrypt secret key material with passphrase.' + "Encrypt secret key material with passphrase." ); Helper::assertSymmetric($symmetric); @@ -421,13 +421,14 @@ public function encrypt( ); } - $s2k = $aeadProtect && Argon2S2K::argon2Supported() ? - Helper::stringToKey(S2kType::Argon2) : - Helper::stringToKey(S2kType::Iterated); + $s2k = + $aeadProtect && Argon2S2K::argon2Supported() + ? Helper::stringToKey(S2kType::Argon2) + : Helper::stringToKey(S2kType::Iterated); - $iv = $aeadProtect ? - Random::string($aead->ivLength()) : - Random::string($symmetric->blockSize()); + $iv = $aeadProtect + ? Random::string($aead->ivLength()) + : Random::string($symmetric->blockSize()); $packetTag = chr(0xc0 | $this->getTag()->value); $kek = self::produceEncryptionKey( @@ -435,30 +436,28 @@ public function encrypt( $symmetric, $s2k, $aead, - $packetTag, + $packetTag ); - $clearText = $this->keyMaterial?->toBytes() ?? ''; + $clearText = $this->keyMaterial?->toBytes() ?? ""; if ($aeadProtect) { $cipher = $aead->cipherEngine($kek, $symmetric); $encrypted = $cipher->encrypt( $clearText, $iv, - implode([ - $packetTag, - $this->publicKey->toBytes(), - ]), + implode([$packetTag, $this->publicKey->toBytes()]) ); - } - else { + } else { $cipher = $symmetric->cipherEngine(S2kUsage::Cfb->name); $cipher->setIV($iv); $cipher->setKey($kek); - $encrypted = $cipher->encrypt(implode([ - $clearText, - hash(self::HASH_ALGO, $clearText, true), - ])); + $encrypted = $cipher->encrypt( + implode([ + $clearText, + hash(self::HASH_ALGO, $clearText, true), + ]) + ); } return new self( $this->publicKey, @@ -468,10 +467,9 @@ public function encrypt( $symmetric, $s2k, $aead, - $iv, + $iv ); - } - else { + } else { return $this; } } @@ -483,20 +481,19 @@ public function decrypt(string $passphrase): self { if ($this->isDecrypted() || !$this->isEncrypted()) { return $this; - } - else { + } else { $this->getLogger()->debug( - 'Decrypt secret key material with passphrase.' + "Decrypt secret key material with passphrase." ); - $clearText = ''; + $clearText = ""; $packetTag = chr(0xc0 | $this->getTag()->value); $kek = self::produceEncryptionKey( $passphrase, $this->symmetric, $this->s2k, $this->aead, - $packetTag, + $packetTag ); if ($this->aead instanceof AeadAlgorithm) { @@ -504,29 +501,24 @@ public function decrypt(string $passphrase): self $clearText = $cipher->decrypt( $this->keyData, $this->iv, - implode([ - $packetTag, - $this->publicKey->toBytes(), - ]), + implode([$packetTag, $this->publicKey->toBytes()]) ); - } - else { + } else { $cipher = $this->symmetric->cipherEngine(S2kUsage::Cfb->name); $cipher->setIV($this->iv); $cipher->setKey($kek); $decrypted = $cipher->decrypt($this->keyData); - $length = strlen($decrypted) - HashAlgorithm::Sha1->digestSize(); + $length = + strlen($decrypted) - HashAlgorithm::Sha1->digestSize(); $clearText = substr($decrypted, 0, $length); $hashText = substr($decrypted, $length); $hashed = hash(self::HASH_ALGO, $clearText, true); if (strcmp($hashed, $hashText) !== 0) { - throw new \RuntimeException('Incorrect key passphrase.'); + throw new \RuntimeException("Incorrect key passphrase."); } } - $keyMaterial = self::readKeyMaterial( - $clearText, $this->publicKey - ); + $keyMaterial = self::readKeyMaterial($clearText, $this->publicKey); return new self( $this->publicKey, @@ -536,7 +528,7 @@ public function decrypt(string $passphrase): self $this->symmetric, $this->s2k, $this->aead, - $this->iv, + $this->iv ); } } @@ -614,17 +606,16 @@ private static function produceEncryptionKey( SymmetricAlgorithm $symmetric, ?S2KInterface $s2k = null, ?AeadAlgorithm $aead = null, - string $packetTag = '', - ): string - { + string $packetTag = "" + ): string { if ($s2k?->getType() === S2kType::Argon2 && empty($aead)) { throw new \InvalidArgumentException( - 'Using Argon2 S2K without AEAD is not allowed.' + "Using Argon2 S2K without AEAD is not allowed." ); } - $derivedKey = $s2k?->produceKey( - $passphrase, $symmetric->keySizeInByte() - ) ?? str_repeat(self::ZERO_CHAR, $symmetric->keySizeInByte()); + $derivedKey = + $s2k?->produceKey($passphrase, $symmetric->keySizeInByte()) ?? + str_repeat(self::ZERO_CHAR, $symmetric->keySizeInByte()); if ($aead instanceof AeadAlgorithm) { return hash_hkdf( Config::HKDF_ALGO, @@ -635,60 +626,71 @@ private static function produceEncryptionKey( chr(PublicKey::VERSION_6), chr($symmetric->value), chr($aead->value), - ]), + ]) ); } return $derivedKey; } private static function readKeyMaterial( - string $bytes, PublicKey $publicKey - ): KeyMaterialInterface - { - $keyMaterial = match($publicKey->getKeyAlgorithm()) { + string $bytes, + PublicKey $publicKey + ): KeyMaterialInterface { + $keyMaterial = match ($publicKey->getKeyAlgorithm()) { KeyAlgorithm::RsaEncryptSign, KeyAlgorithm::RsaEncrypt, KeyAlgorithm::RsaSign => Key\RSASecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial() - ), + $bytes, + $publicKey->getKeyMaterial() + ), KeyAlgorithm::ElGamal => Key\ElGamalSecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial() + $bytes, + $publicKey->getKeyMaterial() ), KeyAlgorithm::Dsa => Key\DSASecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial() + $bytes, + $publicKey->getKeyMaterial() ), KeyAlgorithm::Ecdh => Key\ECDHSecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial() + $bytes, + $publicKey->getKeyMaterial() ), KeyAlgorithm::EcDsa => Key\ECDSASecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial() + $bytes, + $publicKey->getKeyMaterial() ), - KeyAlgorithm::EdDsaLegacy => Key\EdDSALegacySecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial() + KeyAlgorithm::EdDsaLegacy + => Key\EdDSALegacySecretKeyMaterial::fromBytes( + $bytes, + $publicKey->getKeyMaterial() + ), + KeyAlgorithm::X25519 => Key\MontgomerySecretKeyMaterial::fromBytes( + $bytes, + $publicKey->getKeyMaterial(), + MontgomeryCurve::Curve25519 + ), + KeyAlgorithm::X448 => Key\MontgomerySecretKeyMaterial::fromBytes( + $bytes, + $publicKey->getKeyMaterial(), + MontgomeryCurve::Curve448 + ), + KeyAlgorithm::Ed25519 => Key\EdDSASecretKeyMaterial::fromBytes( + $bytes, + $publicKey->getKeyMaterial(), + EdDSACurve::Ed25519 + ), + KeyAlgorithm::Ed448 => Key\EdDSASecretKeyMaterial::fromBytes( + $bytes, + $publicKey->getKeyMaterial(), + EdDSACurve::Ed448 ), - KeyAlgorithm::X25519 - => Key\MontgomerySecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial(), MontgomeryCurve::Curve25519 - ), - KeyAlgorithm::X448 - => Key\MontgomerySecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial(), MontgomeryCurve::Curve448 - ), - KeyAlgorithm::Ed25519 - => Key\EdDSASecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial(), EdDSACurve::Ed25519 - ), - KeyAlgorithm::Ed448 - => Key\EdDSASecretKeyMaterial::fromBytes( - $bytes, $publicKey->getKeyMaterial(), EdDSACurve::Ed448 - ), default => throw new \RuntimeException( - "Key algorithm {$publicKey->getKeyAlgorithm()->name} is unsupported.", + "Key algorithm {$publicKey->getKeyAlgorithm()->name} is unsupported." ), }; if (!$keyMaterial->isValid()) { - throw new \RuntimeException('Key material is not consistent.'); + throw new \RuntimeException("Key material is not consistent."); } return $keyMaterial; } diff --git a/src/Packet/SecretSubkey.php b/src/Packet/SecretSubkey.php index 6061259f..db7aca24 100644 --- a/src/Packet/SecretSubkey.php +++ b/src/Packet/SecretSubkey.php @@ -15,13 +15,9 @@ KeyAlgorithm, RSAKeySize, S2kUsage, - SymmetricAlgorithm, -}; -use OpenPGP\Type\{ - KeyMaterialInterface, - S2KInterface, - SubkeyPacketInterface, + SymmetricAlgorithm }; +use OpenPGP\Type\{KeyMaterialInterface, S2KInterface, SubkeyPacketInterface}; /** * Implementation a possibly encrypted sub private key (Tag 7). @@ -49,15 +45,14 @@ class SecretSubkey extends SecretKey implements SubkeyPacketInterface */ public function __construct( PublicSubkey $publicKey, - string $keyData = '', + string $keyData = "", ?KeyMaterialInterface $keyMaterial = null, S2kUsage $s2kUsage = S2kUsage::None, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, ?S2KInterface $s2k = null, ?AeadAlgorithm $aead = null, - string $iv = '', - ) - { + string $iv = "" + ) { parent::__construct( $publicKey, $keyData, @@ -66,7 +61,7 @@ public function __construct( $symmetric, $s2k, $aead, - $iv, + $iv ); } @@ -91,15 +86,11 @@ public static function generate( KeyAlgorithm $keyAlgorithm = KeyAlgorithm::RsaEncryptSign, RSAKeySize $rsaKeySize = RSAKeySize::Normal, CurveOid $curveOid = CurveOid::Ed25519, - ?DateTimeInterface $time = null, - ): self - { - return self::fromSecretKey(SecretKey::generate( - $keyAlgorithm, - $rsaKeySize, - $curveOid, - $time, - )); + ?DateTimeInterface $time = null + ): self { + return self::fromSecretKey( + SecretKey::generate($keyAlgorithm, $rsaKeySize, $curveOid, $time) + ); } /** @@ -108,16 +99,12 @@ public static function generate( public function encrypt( string $passphrase, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ?AeadAlgorithm $aead = null, - ): self - { + ?AeadAlgorithm $aead = null + ): self { if ($this->getKeyMaterial() instanceof KeyMaterialInterface) { - $secretKey = parent::encrypt( - $passphrase, $symmetric, $aead - ); + $secretKey = parent::encrypt($passphrase, $symmetric, $aead); return self::fromSecretKey($secretKey); - } - else { + } else { return $this; } } @@ -129,8 +116,7 @@ public function decrypt(string $passphrase): self { if ($this->getKeyMaterial() instanceof KeyMaterialInterface) { return $this; - } - else { + } else { return self::fromSecretKey(parent::decrypt($passphrase)); } } @@ -143,7 +129,7 @@ private static function fromSecretKey(SecretKey $secretKey): self $publicKey->getVersion(), $publicKey->getCreationTime(), $publicKey->getKeyAlgorithm(), - $publicKey->getKeyMaterial(), + $publicKey->getKeyMaterial() ), $secretKey->getKeyData(), $secretKey->getKeyMaterial(), @@ -151,7 +137,7 @@ private static function fromSecretKey(SecretKey $secretKey): self $secretKey->getSymmetric(), $secretKey->getS2K(), $secretKey->getAead(), - $secretKey->getIV(), + $secretKey->getIV() ); } } diff --git a/src/Packet/Signature.php b/src/Packet/Signature.php index c833bf3d..22f22a9e 100644 --- a/src/Packet/Signature.php +++ b/src/Packet/Signature.php @@ -9,10 +9,7 @@ namespace OpenPGP\Packet; use DateTimeInterface; -use OpenPGP\Common\{ - Config, - Helper, -}; +use OpenPGP\Common\{Config, Helper}; use OpenPGP\Enum\{ AeadAlgorithm, CompressionAlgorithm, @@ -25,22 +22,22 @@ SignatureSubpacketType, SignatureType, SupportFeature, - SymmetricAlgorithm, + SymmetricAlgorithm }; use OpenPGP\Type\{ KeyPacketInterface, LiteralDataInterface, NotationDataInterface, + PublicKeyMaterialInterface, SignaturePacketInterface, SecretKeyMaterialInterface, SecretKeyPacketInterface, SubkeyPacketInterface, SubpacketInterface, - UserIDPacketInterface, - PublicKeyMaterialInterface, + UserIDPacketInterface }; -use phpseclib3\Crypt\Random; use phpseclib3\Common\Functions\Strings; +use phpseclib3\Crypt\Random; /** * Implementation an OpenPGP signature packet (Tag 2). @@ -85,36 +82,35 @@ public function __construct( private readonly string $salt, private readonly string $signature, array $hashedSubpackets = [], - array $unhashedSubpackets = [], - ) - { + array $unhashedSubpackets = [] + ) { parent::__construct(PacketTag::Signature); if ($version != self::VERSION_4 && $version != self::VERSION_6) { throw new \InvalidArgumentException( - "Version $version of the signature packet is unsupported.", + "Version $version of the signature packet is unsupported." ); } if ($version === self::VERSION_6) { Helper::assertHash($hashAlgorithm); if ($keyAlgorithm === KeyAlgorithm::Dsa) { throw new \InvalidArgumentException( - "Public key {$keyAlgorithm->name} cannot be used with v{$version} signature packet.", + "Public key {$keyAlgorithm->name} cannot be used with v{$version} signature packet." ); } if (strlen($salt) !== $hashAlgorithm->saltSize()) { throw new \LengthException( "Salt size must be {$hashAlgorithm->saltSize()} bytes." ); - }; + } } $this->hashedSubpackets = array_filter( $hashedSubpackets, - static fn ($subpacket) => $subpacket instanceof SignatureSubpacket, + static fn($subpacket) => $subpacket instanceof SignatureSubpacket ); $this->unhashedSubpackets = array_filter( $unhashedSubpackets, - static fn ($subpacket) => $subpacket instanceof SignatureSubpacket, + static fn($subpacket) => $subpacket instanceof SignatureSubpacket ); $this->signatureData = implode([ chr($this->version), @@ -123,7 +119,7 @@ public function __construct( chr($this->hashAlgorithm->value), self::subpacketsToBytes( $this->hashedSubpackets, - $this->version === self::VERSION_6, + $this->version === self::VERSION_6 ), ]); } @@ -149,20 +145,20 @@ public static function fromBytes(string $bytes): self $hashAlgorithm = HashAlgorithm::from(ord($bytes[$offset++])); // Read hashed subpackets - $hashedLength = $isV6 ? - Helper::bytesToLong($bytes, $offset) : - Helper::bytesToShort($bytes, $offset); - $offset += $isV6 ? 4: 2; + $hashedLength = $isV6 + ? Helper::bytesToLong($bytes, $offset) + : Helper::bytesToShort($bytes, $offset); + $offset += $isV6 ? 4 : 2; $hashedSubpackets = self::readSubpackets( substr($bytes, $offset, $hashedLength) ); $offset += $hashedLength; // read unhashed subpackets - $unhashedLength = $isV6 ? - Helper::bytesToLong($bytes, $offset) : - Helper::bytesToShort($bytes, $offset); - $offset += $isV6 ? 4: 2; + $unhashedLength = $isV6 + ? Helper::bytesToLong($bytes, $offset) + : Helper::bytesToShort($bytes, $offset); + $offset += $isV6 ? 4 : 2; $unhashedSubpackets = self::readSubpackets( substr($bytes, $offset, $unhashedLength) ); @@ -172,7 +168,7 @@ public static function fromBytes(string $bytes): self $signedHashValue = substr($bytes, $offset, 2); $offset += 2; - $salt = ''; + $salt = ""; if ($isV6) { $saltLength = ord($bytes[$offset++]); $salt = substr($bytes, $offset, $saltLength); @@ -190,7 +186,7 @@ public static function fromBytes(string $bytes): self $salt, $signature, $hashedSubpackets, - $unhashedSubpackets, + $unhashedSubpackets ); } @@ -211,29 +207,25 @@ public static function createSignature( string $dataToSign, HashAlgorithm $hashAlgorithm = HashAlgorithm::Sha256, array $subpackets = [], - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $version = $signKey->getVersion(); $keyAlgorithm = $signKey->getKeyAlgorithm(); $hashAlgorithm = $signKey->getPreferredHash($hashAlgorithm); Helper::assertHash($hashAlgorithm); $hashedSubpackets = [ - Signature\SignatureCreationTime::fromTime( - $time ?? new \DateTime() - ), + Signature\SignatureCreationTime::fromTime($time ?? new \DateTime()), Signature\IssuerFingerprint::fromKeyPacket($signKey), Signature\IssuerKeyID::fromKeyID($signKey->getKeyID()), ...$subpackets, ]; - $salt = ''; + $salt = ""; $isV6 = $version === self::VERSION_6; if ($isV6) { $salt = Random::string($hashAlgorithm->saltSize()); - } - else { + } else { $hashedSubpackets[] = Signature\NotationData::fromNotation( Config::SALT_NOTATION, Random::string($hashAlgorithm->saltSize()) @@ -245,19 +237,13 @@ public static function createSignature( chr($signatureType->value), chr($keyAlgorithm->value), chr($hashAlgorithm->value), - self::subpacketsToBytes( - $hashedSubpackets, - $isV6, - ), + self::subpacketsToBytes($hashedSubpackets, $isV6), ]); $message = implode([ $salt, $dataToSign, $signatureData, - self::calculateTrailer( - $version, - strlen($signatureData), - ), + self::calculateTrailer($version, strlen($signatureData)), ]); return new self( @@ -268,7 +254,7 @@ public static function createSignature( substr($hashAlgorithm->hash($message), 0, 2), $salt, self::signMessage($signKey, $hashAlgorithm, $message), - $hashedSubpackets, + $hashedSubpackets ); } @@ -283,9 +269,8 @@ public static function createSignature( public static function createDirectKeySignature( SecretKeyPacketInterface $signKey, int $keyExpiry = 0, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $props = self::keySignatureProperties($signKey->getVersion()); if ($keyExpiry > 0) { $props[] = Signature\KeyExpirationTime::fromTime($keyExpiry); @@ -296,7 +281,7 @@ public static function createDirectKeySignature( $signKey->getSignBytes(), Config::getPreferredHash(), $props, - $time, + $time ); } @@ -315,11 +300,12 @@ public static function createSelfCertificate( UserIDPacketInterface $userID, bool $isPrimaryUser = false, int $keyExpiry = 0, - ?DateTimeInterface $time = null, - ): self - { - $props = $signKey->getVersion() === self::VERSION_4 ? - self::keySignatureProperties($signKey->getVersion()) : []; + ?DateTimeInterface $time = null + ): self { + $props = + $signKey->getVersion() === self::VERSION_4 + ? self::keySignatureProperties($signKey->getVersion()) + : []; if ($isPrimaryUser) { $props[] = new Signature\PrimaryUserID("\x01"); } @@ -329,13 +315,10 @@ public static function createSelfCertificate( return self::createSignature( $signKey, SignatureType::CertGeneric, - implode([ - $signKey->getSignBytes(), - $userID->getSignBytes(), - ]), + implode([$signKey->getSignBytes(), $userID->getSignBytes()]), Config::getPreferredHash(), $props, - $time, + $time ); } @@ -352,23 +335,19 @@ public static function createCertGeneric( SecretKeyPacketInterface $signKey, KeyPacketInterface $userKey, UserIDPacketInterface $userID, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return self::createSignature( $signKey, SignatureType::CertGeneric, - implode([ - $userKey->getSignBytes(), - $userID->getSignBytes(), - ]), + implode([$userKey->getSignBytes(), $userID->getSignBytes()]), Config::getPreferredHash(), [ Signature\KeyFlags::fromFlags( KeyFlag::CertifyKeys->value | KeyFlag::SignData->value ), ], - $time, + $time ); } @@ -387,26 +366,22 @@ public static function createCertRevocation( SecretKeyPacketInterface $signKey, KeyPacketInterface $userKey, UserIDPacketInterface $userID, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return self::createSignature( $signKey, SignatureType::CertRevocation, - implode([ - $userKey->getSignBytes(), - $userID->getSignBytes(), - ]), + implode([$userKey->getSignBytes(), $userID->getSignBytes()]), Config::getPreferredHash(), [ Signature\RevocationReason::fromRevocation( $reasonTag ?? RevocationReasonTag::NoReason, $revocationReason - ) + ), ], - $time, + $time ); } @@ -423,11 +398,10 @@ public static function createCertRevocation( public static function createKeyRevocation( SecretKeyPacketInterface $signKey, KeyPacketInterface $keyPacket, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return self::createSignature( $signKey, SignatureType::KeyRevocation, @@ -437,9 +411,9 @@ public static function createKeyRevocation( Signature\RevocationReason::fromRevocation( $reasonTag ?? RevocationReasonTag::NoReason, $revocationReason - ) + ), ], - $time, + $time ); } @@ -458,9 +432,8 @@ public static function createSubkeyBinding( SubkeyPacketInterface $subkey, int $keyExpiry = 0, bool $forSigning = false, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $subpackets = []; if ($keyExpiry > 0) { $subpackets[] = Signature\KeyExpirationTime::fromTime($keyExpiry); @@ -480,27 +453,23 @@ public static function createSubkeyBinding( ]), Config::getPreferredHash(), [], - $time, + $time ) ); } - } - else { + } else { $subpackets[] = Signature\KeyFlags::fromFlags( KeyFlag::EncryptCommunication->value | - KeyFlag::EncryptStorage->value + KeyFlag::EncryptStorage->value ); } return self::createSignature( $signKey, SignatureType::SubkeyBinding, - implode([ - $signKey->getSignBytes(), - $subkey->getSignBytes(), - ]), + implode([$signKey->getSignBytes(), $subkey->getSignBytes()]), Config::getPreferredHash(), $subpackets, - $time, + $time ); } @@ -519,26 +488,22 @@ public static function createSubkeyRevocation( SecretKeyPacketInterface $signKey, KeyPacketInterface $primaryKey, SubkeyPacketInterface $subkey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { return self::createSignature( $signKey, SignatureType::SubkeyRevocation, - implode([ - $primaryKey->getSignBytes(), - $subkey->getSignBytes(), - ]), + implode([$primaryKey->getSignBytes(), $subkey->getSignBytes()]), Config::getPreferredHash(), [ Signature\RevocationReason::fromRevocation( $reasonTag ?? RevocationReasonTag::NoReason, - $revocationReason, - ) + $revocationReason + ), ], - $time, + $time ); } @@ -557,9 +522,8 @@ public static function createLiteralData( LiteralDataInterface $literalData, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, - ): self - { + ?DateTimeInterface $time = null + ): self { $signatureType = match ($literalData->getFormat()) { LiteralFormat::Text, LiteralFormat::Utf8 => SignatureType::Text, default => SignatureType::Binary, @@ -568,10 +532,13 @@ public static function createLiteralData( if ($signKey->getVersion() === PublicKey::VERSION_6) { foreach ($recipients as $recipient) { if ($recipient instanceof KeyPacketInterface) { - $subpackets[] = Signature\IntendedRecipientFingerprint::fromKeyPacket($recipient); - } - elseif (is_string($recipient)) { - $subpackets[] = new Signature\IntendedRecipientFingerprint($recipient); + $subpackets[] = Signature\IntendedRecipientFingerprint::fromKeyPacket( + $recipient + ); + } elseif (is_string($recipient)) { + $subpackets[] = new Signature\IntendedRecipientFingerprint( + $recipient + ); } } } @@ -579,7 +546,7 @@ public static function createLiteralData( $subpackets[] = Signature\NotationData::fromNotation( $notationData->getNotationName(), $notationData->getNotationValue(), - $notationData->isHumanReadable(), + $notationData->isHumanReadable() ); } @@ -589,7 +556,7 @@ public static function createLiteralData( $literalData->getSignBytes(), Config::getPreferredHash(), $subpackets, - $time, + $time ); } @@ -620,17 +587,16 @@ public function toBytes(): string public function verify( KeyPacketInterface $verifyKey, string $dataToVerify, - ?DateTimeInterface $time = null, - ): bool - { + ?DateTimeInterface $time = null + ): bool { if (strcmp($this->getIssuerKeyID(), $verifyKey->getKeyID()) !== 0) { throw new \RuntimeException( - 'Signature was not issued by the given public key.' + "Signature was not issued by the given public key." ); } if ($this->keyAlgorithm !== $verifyKey->getKeyAlgorithm()) { throw new \RuntimeException( - 'Public key algorithm used to sign signature does not match issuer key algorithm.' + "Public key algorithm used to sign signature does not match issuer key algorithm." ); } @@ -639,7 +605,9 @@ public function verify( $time = $time ?? new \DateTime(); if ($expirationTime < $time) { throw new \RuntimeException( - "Signature is expired at {$expirationTime->format(DateTimeInterface::RFC3339_EXTENDED)}." + "Signature is expired at {$expirationTime->format( + DateTimeInterface::RFC3339_EXTENDED + )}." ); } } @@ -650,23 +618,24 @@ public function verify( $this->signatureData, self::calculateTrailer( $this->version, - strlen($this->signatureData), + strlen($this->signatureData) ), ]); $hash = $this->hashAlgorithm->hash($message); if (strcmp($this->signedHashValue, substr($hash, 0, 2)) !== 0) { - throw new \RuntimeException('Signed digest mismatch!'); + throw new \RuntimeException("Signed digest mismatch!"); } $keyMaterial = $verifyKey->getKeyMaterial(); if ($keyMaterial instanceof PublicKeyMaterialInterface) { return $keyMaterial->verify( - $this->hashAlgorithm, $message, $this->signature + $this->hashAlgorithm, + $message, + $this->signature ); - } - else { - throw new \RuntimeException('Key material is not verifiable.'); + } else { + throw new \RuntimeException("Key material is not verifiable."); } } @@ -768,10 +737,11 @@ public function getCreationTime(): ?DateTimeInterface { $subpacket = self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::SignatureCreationTime, + SignatureSubpacketType::SignatureCreationTime ); - return $subpacket instanceof Signature\SignatureCreationTime ? - $subpacket->getCreationTime() : null; + return $subpacket instanceof Signature\SignatureCreationTime + ? $subpacket->getCreationTime() + : null; } /** @@ -781,10 +751,11 @@ public function getExpirationTime(): ?DateTimeInterface { $subpacket = self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::SignatureExpirationTime, + SignatureSubpacketType::SignatureExpirationTime ); - return $subpacket instanceof Signature\SignatureExpirationTime ? - $subpacket->getExpirationTime() : null; + return $subpacket instanceof Signature\SignatureExpirationTime + ? $subpacket->getExpirationTime() + : null; } /** @@ -794,7 +765,7 @@ public function getExportableCertification(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::ExportableCertification, + SignatureSubpacketType::ExportableCertification ); } @@ -805,7 +776,7 @@ public function getTrustSignature(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::TrustSignature, + SignatureSubpacketType::TrustSignature ); } @@ -816,7 +787,7 @@ public function getRegularExpression(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::RegularExpression, + SignatureSubpacketType::RegularExpression ); } @@ -827,7 +798,7 @@ public function getRevocable(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::Revocable, + SignatureSubpacketType::Revocable ); } @@ -838,7 +809,7 @@ public function getKeyExpirationTime(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::KeyExpirationTime, + SignatureSubpacketType::KeyExpirationTime ); } @@ -849,7 +820,7 @@ public function getPreferredSymmetricAlgorithms(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PreferredSymmetricAlgorithms, + SignatureSubpacketType::PreferredSymmetricAlgorithms ); } @@ -860,7 +831,7 @@ public function getRevocationKey(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::RevocationKey, + SignatureSubpacketType::RevocationKey ); } @@ -870,13 +841,15 @@ public function getRevocationKey(): ?SubpacketInterface public function getIssuerKeyID(bool $toHex = false): string { $type = SignatureSubpacketType::IssuerKeyID; - $issuerKeyID = self::getSubpacket($this->hashedSubpackets, $type) ?? - self::getSubpacket($this->unhashedSubpackets, $type); + $issuerKeyID = + self::getSubpacket($this->hashedSubpackets, $type) ?? + self::getSubpacket($this->unhashedSubpackets, $type); if (!($issuerKeyID instanceof Signature\IssuerKeyID)) { $issuerFingerprint = $this->getIssuerFingerprint(); - $keyID = $this->version === self::VERSION_6 ? - substr($issuerFingerprint, 0, PublicKey::KEY_ID_SIZE) : - substr($issuerFingerprint, 12, PublicKey::KEY_ID_SIZE); + $keyID = + $this->version === self::VERSION_6 + ? substr($issuerFingerprint, 0, PublicKey::KEY_ID_SIZE) + : substr($issuerFingerprint, 12, PublicKey::KEY_ID_SIZE); $issuerKeyID = new Signature\IssuerKeyID($keyID); } return $issuerKeyID->getKeyID($toHex); @@ -889,9 +862,8 @@ public function getNotations(): array { return array_filter( $this->hashedSubpackets, - static fn ($subpacket) => - $subpacket->getType() === - SignatureSubpacketType::NotationData->value, + static fn($subpacket) => $subpacket->getType() === + SignatureSubpacketType::NotationData->value ); } @@ -902,7 +874,7 @@ public function getPreferredHashAlgorithms(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PreferredHashAlgorithms, + SignatureSubpacketType::PreferredHashAlgorithms ); } @@ -913,7 +885,7 @@ public function getPreferredAeadCiphers(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PreferredAeadCiphers, + SignatureSubpacketType::PreferredAeadCiphers ); } @@ -924,7 +896,7 @@ public function getPreferredCompressionAlgorithms(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PreferredCompressionAlgorithms, + SignatureSubpacketType::PreferredCompressionAlgorithms ); } @@ -935,7 +907,7 @@ public function getKeyServerPreferences(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::KeyServerPreferences, + SignatureSubpacketType::KeyServerPreferences ); } @@ -946,7 +918,7 @@ public function getPreferredKeyServer(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PreferredKeyServer, + SignatureSubpacketType::PreferredKeyServer ); } @@ -957,10 +929,11 @@ public function isPrimaryUserID(): bool { $subpacket = self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PrimaryUserID, + SignatureSubpacketType::PrimaryUserID ); - return $subpacket instanceof Signature\PrimaryUserID ? - $subpacket->isPrimaryUserID() : false; + return $subpacket instanceof Signature\PrimaryUserID + ? $subpacket->isPrimaryUserID() + : false; } /** @@ -970,7 +943,7 @@ public function getPolicyURI(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::PolicyURI, + SignatureSubpacketType::PolicyURI ); } @@ -981,7 +954,7 @@ public function getKeyFlags(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::KeyFlags, + SignatureSubpacketType::KeyFlags ); } @@ -992,7 +965,7 @@ public function getSignerUserID(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::SignerUserID, + SignatureSubpacketType::SignerUserID ); } @@ -1003,7 +976,7 @@ public function getRevocationReason(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::RevocationReason, + SignatureSubpacketType::RevocationReason ); } @@ -1014,7 +987,7 @@ public function getFeatures(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::Features, + SignatureSubpacketType::Features ); } @@ -1025,7 +998,7 @@ public function getSignatureTarget(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::SignatureTarget, + SignatureSubpacketType::SignatureTarget ); } @@ -1036,7 +1009,7 @@ public function getEmbeddedSignature(): ?SubpacketInterface { return self::getSubpacket( $this->hashedSubpackets, - SignatureSubpacketType::EmbeddedSignature, + SignatureSubpacketType::EmbeddedSignature ); } @@ -1046,8 +1019,9 @@ public function getEmbeddedSignature(): ?SubpacketInterface public function getIssuerFingerprint(bool $toHex = false): string { $type = SignatureSubpacketType::IssuerFingerprint; - $subpacket = self::getSubpacket($this->hashedSubpackets, $type) ?? - self::getSubpacket($this->unhashedSubpackets, $type); + $subpacket = + self::getSubpacket($this->hashedSubpackets, $type) ?? + self::getSubpacket($this->unhashedSubpackets, $type); if ($subpacket instanceof Signature\IssuerFingerprint) { return $subpacket->getKeyFingerprint($toHex); } @@ -1063,9 +1037,8 @@ public function getIntendedRecipients(): array { return array_filter( $this->hashedSubpackets, - static fn ($subpacket) => - $subpacket->getType() === - SignatureSubpacketType::IntendedRecipientFingerprint->value, + static fn($subpacket) => $subpacket->getType() === + SignatureSubpacketType::IntendedRecipientFingerprint->value ); } @@ -1089,7 +1062,7 @@ public function isCertification(): bool */ public function isDirectKey(): bool { - return $this->signatureType === SignatureType::DirectKey; + return $this->signatureType === SignatureType::DirectKey; } /** @@ -1097,7 +1070,7 @@ public function isDirectKey(): bool */ public function isKeyRevocation(): bool { - return $this->signatureType === SignatureType::KeyRevocation; + return $this->signatureType === SignatureType::KeyRevocation; } /** @@ -1105,7 +1078,7 @@ public function isKeyRevocation(): bool */ public function isCertRevocation(): bool { - return $this->signatureType === SignatureType::CertRevocation; + return $this->signatureType === SignatureType::CertRevocation; } /** @@ -1113,7 +1086,7 @@ public function isCertRevocation(): bool */ public function isSubkeyBinding(): bool { - return $this->signatureType === SignatureType::SubkeyBinding; + return $this->signatureType === SignatureType::SubkeyBinding; } /** @@ -1121,7 +1094,7 @@ public function isSubkeyBinding(): bool */ public function isSubkeyRevocation(): bool { - return $this->signatureType === SignatureType::SubkeyRevocation; + return $this->signatureType === SignatureType::SubkeyRevocation; } /** @@ -1137,19 +1110,15 @@ private static function keySignatureProperties(int $version): array chr(SymmetricAlgorithm::Aes256->value), ]; $aeads = array_map( - static fn ($algo) => chr($algo->value), - AeadAlgorithm::cases(), + static fn($algo) => chr($algo->value), + AeadAlgorithm::cases() ); $props = [ Signature\KeyFlags::fromFlags( KeyFlag::CertifyKeys->value | KeyFlag::SignData->value ), - new Signature\PreferredSymmetricAlgorithms( - implode($symmetrics) - ), - new Signature\PreferredAeadAlgorithms( - implode($aeads) - ), + new Signature\PreferredSymmetricAlgorithms(implode($symmetrics)), + new Signature\PreferredAeadAlgorithms(implode($aeads)), new Signature\PreferredHashAlgorithms( implode([ chr(HashAlgorithm::Sha256->value), @@ -1168,19 +1137,21 @@ private static function keySignatureProperties(int $version): array ), Signature\Features::fromFeatures( SupportFeature::Version1SEIPD->value | - SupportFeature::AeadEncrypted->value | - SupportFeature::Version2SEIPD->value + SupportFeature::AeadEncrypted->value | + SupportFeature::Version2SEIPD->value ), ]; if ($version === self::VERSION_6) { $props[] = new Signature\PreferredAeadCiphers( - implode(array_map( - static fn ($aead) => implode([ - $symmetrics[0] . $aead, - $symmetrics[1] . $aead, - ]), - $aeads, - )) + implode( + array_map( + static fn($aead) => implode([ + $symmetrics[0] . $aead, + $symmetrics[1] . $aead, + ]), + $aeads + ) + ) ); } return $props; @@ -1200,13 +1171,12 @@ private static function readSubpackets(string $bytes): array private static function signMessage( SecretKeyPacketInterface $signKey, HashAlgorithm $hash, - string $message, - ): string - { - if (!($signKey->getKeyMaterial() instanceof SecretKeyMaterialInterface)) { - throw new \RuntimeException( - 'Invalid key material for signing.', - ); + string $message + ): string { + if ( + !($signKey->getKeyMaterial() instanceof SecretKeyMaterialInterface) + ) { + throw new \RuntimeException("Invalid key material for signing."); } return match ($signKey->getKeyAlgorithm()) { KeyAlgorithm::RsaEncryptSign, @@ -1215,22 +1185,19 @@ private static function signMessage( KeyAlgorithm::EcDsa, KeyAlgorithm::EdDsaLegacy, KeyAlgorithm::Ed25519, - KeyAlgorithm::Ed448 => $signKey->getKeyMaterial()->sign($hash, $message), + KeyAlgorithm::Ed448 + => $signKey->getKeyMaterial()->sign($hash, $message), default => throw new \RuntimeException( - "Key algorithm {$signKey->getKeyAlgorithm()->name} is unsupported for signing.", + "Key algorithm {$signKey->getKeyAlgorithm()->name} is unsupported for signing." ), }; } private static function calculateTrailer( - int $version, int $dataLength - ): string - { - return implode([ - chr($version), - "\xff", - pack('N', $dataLength), - ]); + int $version, + int $dataLength + ): string { + return implode([chr($version), "\xff", pack("N", $dataLength)]); } /** @@ -1241,14 +1208,16 @@ private static function calculateTrailer( * @return string */ private static function subpacketsToBytes( - array $subpackets, bool $isV6 = false - ): string - { - $bytes = implode(array_map( - static fn ($subpacket): string => $subpacket->toBytes(), - $subpackets - )); - return pack($isV6 ? 'N' : 'n', strlen($bytes)) . $bytes; + array $subpackets, + bool $isV6 = false + ): string { + $bytes = implode( + array_map( + static fn($subpacket): string => $subpacket->toBytes(), + $subpackets + ) + ); + return pack($isV6 ? "N" : "n", strlen($bytes)) . $bytes; } /** @@ -1259,12 +1228,12 @@ private static function subpacketsToBytes( * @return SubpacketInterface */ private static function getSubpacket( - array $subpackets, SignatureSubpacketType $type - ): ?SubpacketInterface - { + array $subpackets, + SignatureSubpacketType $type + ): ?SubpacketInterface { $subpackets = array_filter( $subpackets, - static fn ($subpacket) => $subpacket->getType() === $type->value + static fn($subpacket) => $subpacket->getType() === $type->value ); return array_pop($subpackets); } diff --git a/src/Packet/Signature/EmbeddedSignature.php b/src/Packet/Signature/EmbeddedSignature.php index f8728898..6b51a544 100644 --- a/src/Packet/Signature/EmbeddedSignature.php +++ b/src/Packet/Signature/EmbeddedSignature.php @@ -9,10 +9,7 @@ namespace OpenPGP\Packet\Signature; use OpenPGP\Enum\SignatureSubpacketType; -use OpenPGP\Packet\{ - Signature, - SignatureSubpacket, -}; +use OpenPGP\Packet\{Signature, SignatureSubpacket}; use OpenPGP\Type\SignaturePacketInterface; /** @@ -36,8 +33,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::EmbeddedSignature->value, $data, @@ -52,8 +48,9 @@ public function __construct( * @param SignaturePacketInterface $signature * @return self */ - public static function fromSignature(SignaturePacketInterface $signature): self - { + public static function fromSignature( + SignaturePacketInterface $signature + ): self { return new self($signature->toBytes()); } diff --git a/src/Packet/Signature/ExportableCertification.php b/src/Packet/Signature/ExportableCertification.php index dad607ea..fd818bca 100644 --- a/src/Packet/Signature/ExportableCertification.php +++ b/src/Packet/Signature/ExportableCertification.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::ExportableCertification->value, $data, @@ -50,11 +49,9 @@ public function __construct( * @return self */ public static function fromExportable( - bool $exportable = true, bool $critical = false - ): self - { - return new self( - $exportable ? "\x01" : "\x00", $critical - ); + bool $exportable = true, + bool $critical = false + ): self { + return new self($exportable ? "\x01" : "\x00", $critical); } } diff --git a/src/Packet/Signature/Features.php b/src/Packet/Signature/Features.php index 5bcd2a5c..d108a1f6 100644 --- a/src/Packet/Signature/Features.php +++ b/src/Packet/Signature/Features.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - SignatureSubpacketType, - SupportFeature, -}; +use OpenPGP\Enum\{SignatureSubpacketType, SupportFeature}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -35,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::Features->value, $data, @@ -53,9 +49,9 @@ public function __construct( * @return self */ public static function fromFeatures( - int $features = 0, bool $critical = false - ): self - { + int $features = 0, + bool $critical = false + ): self { return new self(chr($features), $critical); } @@ -66,21 +62,23 @@ public static function fromFeatures( */ public function supportV1SEIPD(): bool { - return (ord($this->getData()[0]) & SupportFeature::Version1SEIPD->value) - === SupportFeature::Version1SEIPD->value; + return (ord($this->getData()[0]) & + SupportFeature::Version1SEIPD->value) === + SupportFeature::Version1SEIPD->value; } /** * Support: - * AEAD Encrypted Data packet (packet 20). + * AEAD Encrypted Data packet (packet 20). * Version 5 Symmetric Encrypted Session Key packet. * * @return bool */ public function supportAead(): bool { - return (ord($this->getData()[0]) & SupportFeature::AeadEncrypted->value) - === SupportFeature::AeadEncrypted->value; + return (ord($this->getData()[0]) & + SupportFeature::AeadEncrypted->value) === + SupportFeature::AeadEncrypted->value; } /** @@ -90,8 +88,9 @@ public function supportAead(): bool */ public function supportV5PublicKey(): bool { - return (ord($this->getData()[0]) & SupportFeature::Version5PublicKey->value) - === SupportFeature::Version5PublicKey->value; + return (ord($this->getData()[0]) & + SupportFeature::Version5PublicKey->value) === + SupportFeature::Version5PublicKey->value; } /** @@ -101,7 +100,8 @@ public function supportV5PublicKey(): bool */ public function supportV2SEIPD(): bool { - return (ord($this->getData()[0]) & SupportFeature::Version2SEIPD->value) - === SupportFeature::Version2SEIPD->value; + return (ord($this->getData()[0]) & + SupportFeature::Version2SEIPD->value) === + SupportFeature::Version2SEIPD->value; } } diff --git a/src/Packet/Signature/IntendedRecipientFingerprint.php b/src/Packet/Signature/IntendedRecipientFingerprint.php index b3fb10ab..5890db20 100644 --- a/src/Packet/Signature/IntendedRecipientFingerprint.php +++ b/src/Packet/Signature/IntendedRecipientFingerprint.php @@ -8,10 +8,10 @@ namespace OpenPGP\Packet\Signature; -use phpseclib3\Common\Functions\Strings; use OpenPGP\Enum\SignatureSubpacketType; use OpenPGP\Packet\SignatureSubpacket; use OpenPGP\Type\KeyPacketInterface; +use phpseclib3\Common\Functions\Strings; /** * IntendedRecipientFingerprint sub-packet class @@ -35,8 +35,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::IntendedRecipientFingerprint->value, $data, @@ -53,11 +52,12 @@ public function __construct( * @return self */ public static function fromKeyPacket( - KeyPacketInterface $key, bool $critical = false - ): self - { + KeyPacketInterface $key, + bool $critical = false + ): self { return new self( - chr($key->getVersion()) . $key->getFingerprint(), $critical + chr($key->getVersion()) . $key->getFingerprint(), + $critical ); } @@ -69,9 +69,9 @@ public static function fromKeyPacket( * @return self */ public static function wildcard( - bool $isV6 = true, bool $critical = false - ): self - { + bool $isV6 = true, + bool $critical = false + ): self { return new self( chr($isV6 ? 6 : 4) . str_repeat("\x00", $isV6 ? 32 : 20), $critical @@ -96,6 +96,8 @@ public function getKeyVersion(): int */ public function getKeyFingerprint(bool $toHex = false): string { - return $toHex ? Strings::bin2hex(substr($this->getData(), 1)) : substr($this->getData(), 1); + return $toHex + ? Strings::bin2hex(substr($this->getData(), 1)) + : substr($this->getData(), 1); } } diff --git a/src/Packet/Signature/IssuerFingerprint.php b/src/Packet/Signature/IssuerFingerprint.php index 389af10a..63a2ab91 100644 --- a/src/Packet/Signature/IssuerFingerprint.php +++ b/src/Packet/Signature/IssuerFingerprint.php @@ -8,10 +8,10 @@ namespace OpenPGP\Packet\Signature; -use phpseclib3\Common\Functions\Strings; use OpenPGP\Enum\SignatureSubpacketType; use OpenPGP\Packet\SignatureSubpacket; use OpenPGP\Type\KeyPacketInterface; +use phpseclib3\Common\Functions\Strings; /** * IssuerFingerprint sub-packet class @@ -35,8 +35,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::IssuerFingerprint->value, $data, @@ -53,11 +52,12 @@ public function __construct( * @return self */ public static function fromKeyPacket( - KeyPacketInterface $key, bool $critical = false - ): self - { + KeyPacketInterface $key, + bool $critical = false + ): self { return new self( - chr($key->getVersion()) . $key->getFingerprint(), $critical + chr($key->getVersion()) . $key->getFingerprint(), + $critical ); } @@ -69,9 +69,9 @@ public static function fromKeyPacket( * @return self */ public static function wildcard( - bool $isV6 = true, bool $critical = false - ): self - { + bool $isV6 = true, + bool $critical = false + ): self { return new self( chr($isV6 ? 6 : 4) . str_repeat("\x00", $isV6 ? 32 : 20), $critical @@ -96,6 +96,8 @@ public function getKeyVersion(): int */ public function getKeyFingerprint(bool $toHex = false): string { - return $toHex ? Strings::bin2hex(substr($this->getData(), 1)) : substr($this->getData(), 1); + return $toHex + ? Strings::bin2hex(substr($this->getData(), 1)) + : substr($this->getData(), 1); } } diff --git a/src/Packet/Signature/IssuerKeyID.php b/src/Packet/Signature/IssuerKeyID.php index ec084a9a..a6e0a0c1 100644 --- a/src/Packet/Signature/IssuerKeyID.php +++ b/src/Packet/Signature/IssuerKeyID.php @@ -8,9 +8,9 @@ namespace OpenPGP\Packet\Signature; -use phpseclib3\Common\Functions\Strings; use OpenPGP\Enum\SignatureSubpacketType; use OpenPGP\Packet\SignatureSubpacket; +use phpseclib3\Common\Functions\Strings; /** * IssuerKeyID sub-packet class @@ -34,8 +34,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::IssuerKeyID->value, $data, @@ -52,9 +51,9 @@ public function __construct( * @return self */ public static function fromKeyID( - string $keyID, bool $critical = false - ): self - { + string $keyID, + bool $critical = false + ): self { return new self($keyID, $critical); } @@ -64,9 +63,7 @@ public static function fromKeyID( * @param bool $critical * @return self */ - public static function wildcard( - bool $critical = false - ): self + public static function wildcard(bool $critical = false): self { return new self(str_repeat("\x00", 8), $critical); } diff --git a/src/Packet/Signature/KeyExpirationTime.php b/src/Packet/Signature/KeyExpirationTime.php index 6901b91a..8f0ec351 100644 --- a/src/Packet/Signature/KeyExpirationTime.php +++ b/src/Packet/Signature/KeyExpirationTime.php @@ -34,8 +34,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::KeyExpirationTime->value, $data, @@ -51,11 +50,9 @@ public function __construct( * @param bool $critical * @return self */ - public static function fromTime( - int $seconds, bool $critical = false - ): self + public static function fromTime(int $seconds, bool $critical = false): self { - return new self(pack('N', $seconds), $critical); + return new self(pack("N", $seconds), $critical); } /** diff --git a/src/Packet/Signature/KeyFlags.php b/src/Packet/Signature/KeyFlags.php index 54b63fa8..8ac3593e 100644 --- a/src/Packet/Signature/KeyFlags.php +++ b/src/Packet/Signature/KeyFlags.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - KeyFlag, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{KeyFlag, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -36,8 +33,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::KeyFlags->value, $data, @@ -53,9 +49,7 @@ public function __construct( * @param bool $critical * @return self */ - public static function fromFlags( - int $flags, bool $critical = false - ): self + public static function fromFlags(int $flags, bool $critical = false): self { return new self(self::flagsToBytes($flags), $critical); } @@ -70,7 +64,7 @@ public function getFlags(): int $flags = 0; $data = $this->getData(); for ($i = 0; $i != strlen($data); $i++) { - $flags |= ord($data[$i]) << ($i * 8); + $flags |= ord($data[$i]) << $i * 8; } return $flags; } @@ -82,8 +76,8 @@ public function getFlags(): int */ public function isCertifyKeys(): bool { - return ($this->getFlags() & KeyFlag::CertifyKeys->value) - === KeyFlag::CertifyKeys->value; + return ($this->getFlags() & KeyFlag::CertifyKeys->value) === + KeyFlag::CertifyKeys->value; } /** @@ -93,8 +87,8 @@ public function isCertifyKeys(): bool */ public function isSignData(): bool { - return ($this->getFlags() & KeyFlag::SignData->value) - === KeyFlag::SignData->value; + return ($this->getFlags() & KeyFlag::SignData->value) === + KeyFlag::SignData->value; } /** @@ -104,8 +98,8 @@ public function isSignData(): bool */ public function isEncryptCommunication(): bool { - return ($this->getFlags() & KeyFlag::EncryptCommunication->value) - === KeyFlag::EncryptCommunication->value; + return ($this->getFlags() & KeyFlag::EncryptCommunication->value) === + KeyFlag::EncryptCommunication->value; } /** @@ -115,8 +109,8 @@ public function isEncryptCommunication(): bool */ public function isEncryptStorage(): bool { - return ($this->getFlags() & KeyFlag::EncryptStorage->value) - === KeyFlag::EncryptStorage->value; + return ($this->getFlags() & KeyFlag::EncryptStorage->value) === + KeyFlag::EncryptStorage->value; } private static function flagsToBytes(int $flags): string @@ -124,7 +118,7 @@ private static function flagsToBytes(int $flags): string $size = 0; $bytes = []; for ($i = 0; $i < 4; $i++) { - $bytes[$i] = chr(($flags >> ($i * 8)) & 0xff); + $bytes[$i] = chr(($flags >> $i * 8) & 0xff); if (ord($bytes[$i]) != 0) { $size = $i; } diff --git a/src/Packet/Signature/KeyServerPreferences.php b/src/Packet/Signature/KeyServerPreferences.php index 04508c74..900862bd 100644 --- a/src/Packet/Signature/KeyServerPreferences.php +++ b/src/Packet/Signature/KeyServerPreferences.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::KeyServerPreferences->value, $data, diff --git a/src/Packet/Signature/NotationData.php b/src/Packet/Signature/NotationData.php index 424e3279..0aff149b 100644 --- a/src/Packet/Signature/NotationData.php +++ b/src/Packet/Signature/NotationData.php @@ -23,8 +23,8 @@ */ class NotationData extends SignatureSubpacket implements NotationDataInterface { - const FLAG_LENGTH = 4; - const NAME_LENGTH = 2; + const FLAG_LENGTH = 4; + const NAME_LENGTH = 2; const VALUE_LENGTH = 2; /** @@ -39,8 +39,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::NotationData->value, $data, @@ -62,12 +61,13 @@ public static function fromNotation( string $notationName, string $notationValue, bool $humanReadable = false, - bool $critical = false, - ): self - { + bool $critical = false + ): self { return new self( self::notationToBytes( - $notationName, $notationValue, $humanReadable + $notationName, + $notationValue, + $humanReadable ), $critical ); @@ -87,9 +87,11 @@ public function isHumanReadable(): bool public function getNotationName(): string { $data = $this->getData(); - $nameLength = (((ord($data[self::FLAG_LENGTH]) & 0xff) << 8) + - (ord($data[self::FLAG_LENGTH + 1]) & 0xff)); - $nameOffset = self::FLAG_LENGTH + self::NAME_LENGTH + self::VALUE_LENGTH; + $nameLength = + ((ord($data[self::FLAG_LENGTH]) & 0xff) << 8) + + (ord($data[self::FLAG_LENGTH + 1]) & 0xff); + $nameOffset = + self::FLAG_LENGTH + self::NAME_LENGTH + self::VALUE_LENGTH; return substr($data, $nameOffset, $nameLength); } @@ -99,11 +101,14 @@ public function getNotationName(): string public function getNotationValue(): string { $data = $this->getData(); - $nameLength = (((ord($data[self::FLAG_LENGTH]) & 0xff) << 8) + - (ord($this->getData()[self::FLAG_LENGTH + 1]) & 0xff)); - $valueLength = (((ord($data[self::FLAG_LENGTH + self::NAME_LENGTH]) & 0xff) << 8) + - (ord($data[self::FLAG_LENGTH + self::NAME_LENGTH + 1]) & 0xff)); - $valueOffset = self::FLAG_LENGTH + + $nameLength = + ((ord($data[self::FLAG_LENGTH]) & 0xff) << 8) + + (ord($this->getData()[self::FLAG_LENGTH + 1]) & 0xff); + $valueLength = + ((ord($data[self::FLAG_LENGTH + self::NAME_LENGTH]) & 0xff) << 8) + + (ord($data[self::FLAG_LENGTH + self::NAME_LENGTH + 1]) & 0xff); + $valueOffset = + self::FLAG_LENGTH + self::NAME_LENGTH + self::VALUE_LENGTH + $nameLength; @@ -113,28 +118,27 @@ public function getNotationValue(): string private static function notationToBytes( string $notationName, string $notationValue, - bool $humanReadable = false, - ): string - { - $notationName = mb_convert_encoding($notationName, 'UTF-8'); + bool $humanReadable = false + ): string { + $notationName = mb_convert_encoding($notationName, "UTF-8"); $nameLength = min(strlen($notationName), 0xffff); if ($nameLength !== strlen($notationName)) { throw new \InvalidArgumentException( - 'Notation name exceeds maximum length.' + "Notation name exceeds maximum length." ); } $valueLength = min(strlen($notationValue), 0xffff); if ($valueLength !== strlen($notationValue)) { throw new \InvalidArgumentException( - 'Notation value exceeds maximum length.' + "Notation value exceeds maximum length." ); } return implode([ $humanReadable ? "\x80\x00\x00\x00" : "\x00\x00\x00\x00", - pack('n', $nameLength), - pack('n', $valueLength), + pack("n", $nameLength), + pack("n", $valueLength), substr($notationName, 0, $nameLength), substr($notationValue, 0, $valueLength), ]); diff --git a/src/Packet/Signature/PolicyURI.php b/src/Packet/Signature/PolicyURI.php index 379d1b91..ba7cab79 100644 --- a/src/Packet/Signature/PolicyURI.php +++ b/src/Packet/Signature/PolicyURI.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PolicyURI->value, $data, diff --git a/src/Packet/Signature/PreferredAeadAlgorithms.php b/src/Packet/Signature/PreferredAeadAlgorithms.php index 6fb25b37..4b102b28 100644 --- a/src/Packet/Signature/PreferredAeadAlgorithms.php +++ b/src/Packet/Signature/PreferredAeadAlgorithms.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - AeadAlgorithm, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{AeadAlgorithm, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -35,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PreferredAeadAlgorithms->value, $data, @@ -53,7 +49,7 @@ public function __construct( public function getPreferences(): array { return array_map( - fn ($pref) => AeadAlgorithm::from(ord($pref)), + fn($pref) => AeadAlgorithm::from(ord($pref)), str_split($this->getData()) ); } diff --git a/src/Packet/Signature/PreferredAeadCiphers.php b/src/Packet/Signature/PreferredAeadCiphers.php index f9bd85c1..ddfdfbe1 100644 --- a/src/Packet/Signature/PreferredAeadCiphers.php +++ b/src/Packet/Signature/PreferredAeadCiphers.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - AeadAlgorithm, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{AeadAlgorithm, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -35,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PreferredAeadCiphers->value, $data, diff --git a/src/Packet/Signature/PreferredCompressionAlgorithms.php b/src/Packet/Signature/PreferredCompressionAlgorithms.php index fe00ab30..310d8b2a 100644 --- a/src/Packet/Signature/PreferredCompressionAlgorithms.php +++ b/src/Packet/Signature/PreferredCompressionAlgorithms.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - CompressionAlgorithm, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{CompressionAlgorithm, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -35,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PreferredCompressionAlgorithms->value, $data, @@ -53,7 +49,7 @@ public function __construct( public function getPreferences(): array { return array_map( - fn ($pref) => CompressionAlgorithm::from(ord($pref)), + fn($pref) => CompressionAlgorithm::from(ord($pref)), str_split($this->getData()) ); } diff --git a/src/Packet/Signature/PreferredHashAlgorithms.php b/src/Packet/Signature/PreferredHashAlgorithms.php index 797f23b9..933db50e 100644 --- a/src/Packet/Signature/PreferredHashAlgorithms.php +++ b/src/Packet/Signature/PreferredHashAlgorithms.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - HashAlgorithm, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{HashAlgorithm, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -35,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PreferredHashAlgorithms->value, $data, @@ -53,7 +49,7 @@ public function __construct( public function getPreferences(): array { return array_map( - fn ($pref) => HashAlgorithm::from(ord($pref)), + fn($pref) => HashAlgorithm::from(ord($pref)), str_split($this->getData()) ); } diff --git a/src/Packet/Signature/PreferredKeyServer.php b/src/Packet/Signature/PreferredKeyServer.php index 4698846f..c1a50da8 100644 --- a/src/Packet/Signature/PreferredKeyServer.php +++ b/src/Packet/Signature/PreferredKeyServer.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PreferredKeyServer->value, $data, diff --git a/src/Packet/Signature/PreferredSymmetricAlgorithms.php b/src/Packet/Signature/PreferredSymmetricAlgorithms.php index 251a1eaf..d5d9ff0e 100644 --- a/src/Packet/Signature/PreferredSymmetricAlgorithms.php +++ b/src/Packet/Signature/PreferredSymmetricAlgorithms.php @@ -8,10 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - SignatureSubpacketType, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{SignatureSubpacketType, SymmetricAlgorithm}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -35,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PreferredSymmetricAlgorithms->value, $data, @@ -53,7 +49,7 @@ public function __construct( public function getPreferences(): array { return array_map( - fn ($pref) => SymmetricAlgorithm::from(ord($pref)), + fn($pref) => SymmetricAlgorithm::from(ord($pref)), str_split($this->getData()) ); } diff --git a/src/Packet/Signature/PrimaryUserID.php b/src/Packet/Signature/PrimaryUserID.php index 15f3dffb..774bb5f3 100644 --- a/src/Packet/Signature/PrimaryUserID.php +++ b/src/Packet/Signature/PrimaryUserID.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::PrimaryUserID->value, $data, diff --git a/src/Packet/Signature/RegularExpression.php b/src/Packet/Signature/RegularExpression.php index 659c5a27..14c8c80b 100644 --- a/src/Packet/Signature/RegularExpression.php +++ b/src/Packet/Signature/RegularExpression.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::RegularExpression->value, $data, diff --git a/src/Packet/Signature/Revocable.php b/src/Packet/Signature/Revocable.php index 85f468a9..6e08076a 100644 --- a/src/Packet/Signature/Revocable.php +++ b/src/Packet/Signature/Revocable.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::Revocable->value, $data, diff --git a/src/Packet/Signature/RevocationKey.php b/src/Packet/Signature/RevocationKey.php index be3bbb94..fd6c39ae 100644 --- a/src/Packet/Signature/RevocationKey.php +++ b/src/Packet/Signature/RevocationKey.php @@ -8,11 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - KeyAlgorithm, - RevocationKeyTag, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{KeyAlgorithm, RevocationKeyTag, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -36,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::RevocationKey->value, $data, @@ -60,11 +55,12 @@ public static function fromRevocation( KeyAlgorithm $keyAlgorithm, string $fingerprint, bool $critical = false - ): self - { + ): self { return new self( self::revocationToBytes( - $signatureClass, $keyAlgorithm, $fingerprint + $signatureClass, + $keyAlgorithm, + $fingerprint ), $critical ); @@ -104,8 +100,7 @@ private static function revocationToBytes( RevocationKeyTag $signatureClass, KeyAlgorithm $keyAlgorithm, string $fingerprint - ): string - { + ): string { return implode([ chr($signatureClass->value), chr($keyAlgorithm->value), diff --git a/src/Packet/Signature/RevocationReason.php b/src/Packet/Signature/RevocationReason.php index 28801e23..e218fdf3 100644 --- a/src/Packet/Signature/RevocationReason.php +++ b/src/Packet/Signature/RevocationReason.php @@ -8,11 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - KeyAlgorithm, - RevocationReasonTag, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{RevocationReasonTag, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -37,8 +33,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::RevocationReason->value, $data, @@ -59,10 +54,10 @@ public static function fromRevocation( RevocationReasonTag $reason, string $description, bool $critical = false - ): self - { + ): self { return new self( - self::revocationToBytes($reason, $description), $critical + self::revocationToBytes($reason, $description), + $critical ); } @@ -89,11 +84,7 @@ public function getDescription(): string private static function revocationToBytes( RevocationReasonTag $reason, string $description - ): string - { - return implode([ - chr($reason->value), - $description, - ]); + ): string { + return implode([chr($reason->value), $description]); } } diff --git a/src/Packet/Signature/SignatureCreationTime.php b/src/Packet/Signature/SignatureCreationTime.php index 31cb9942..ebe6a713 100644 --- a/src/Packet/Signature/SignatureCreationTime.php +++ b/src/Packet/Signature/SignatureCreationTime.php @@ -34,8 +34,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::SignatureCreationTime->value, $data, @@ -52,10 +51,10 @@ public function __construct( * @return self */ public static function fromTime( - DateTimeInterface $time, bool $critical = false - ): self - { - return new self(pack('N', $time->getTimestamp()), $critical); + DateTimeInterface $time, + bool $critical = false + ): self { + return new self(pack("N", $time->getTimestamp()), $critical); } /** diff --git a/src/Packet/Signature/SignatureExpirationTime.php b/src/Packet/Signature/SignatureExpirationTime.php index 2f169ca8..d02a047c 100644 --- a/src/Packet/Signature/SignatureExpirationTime.php +++ b/src/Packet/Signature/SignatureExpirationTime.php @@ -35,8 +35,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::SignatureExpirationTime->value, $data, @@ -53,10 +52,10 @@ public function __construct( * @return self */ public static function fromTime( - DateTimeInterface $time, bool $critical = false - ): self - { - return new self(pack('N', $time->getTimestamp()), $critical); + DateTimeInterface $time, + bool $critical = false + ): self { + return new self(pack("N", $time->getTimestamp()), $critical); } /** diff --git a/src/Packet/Signature/SignatureTarget.php b/src/Packet/Signature/SignatureTarget.php index 51a8d0f3..a327be6d 100644 --- a/src/Packet/Signature/SignatureTarget.php +++ b/src/Packet/Signature/SignatureTarget.php @@ -8,11 +8,7 @@ namespace OpenPGP\Packet\Signature; -use OpenPGP\Enum\{ - HashAlgorithm, - KeyAlgorithm, - SignatureSubpacketType, -}; +use OpenPGP\Enum\{HashAlgorithm, KeyAlgorithm, SignatureSubpacketType}; use OpenPGP\Packet\SignatureSubpacket; /** @@ -38,8 +34,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::SignatureTarget->value, $data, @@ -62,8 +57,7 @@ public static function fromRevocation( HashAlgorithm $hashAlgorithm, string $hashData, bool $critical = false - ): self - { + ): self { return new self( self::hashDataToBytes($keyAlgorithm, $hashAlgorithm, $hashData), $critical @@ -104,8 +98,7 @@ private static function hashDataToBytes( KeyAlgorithm $keyAlgorithm, HashAlgorithm $hashAlgorithm, string $hashData - ): string - { + ): string { return implode([ chr($keyAlgorithm->value), chr($hashAlgorithm->value), diff --git a/src/Packet/Signature/SignerUserID.php b/src/Packet/Signature/SignerUserID.php index 8d861543..7dc79c2a 100644 --- a/src/Packet/Signature/SignerUserID.php +++ b/src/Packet/Signature/SignerUserID.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::SignerUserID->value, $data, diff --git a/src/Packet/Signature/TrustSignature.php b/src/Packet/Signature/TrustSignature.php index 4a8cd225..7b61bfda 100644 --- a/src/Packet/Signature/TrustSignature.php +++ b/src/Packet/Signature/TrustSignature.php @@ -32,8 +32,7 @@ public function __construct( string $data, bool $critical = false, bool $isLong = false - ) - { + ) { parent::__construct( SignatureSubpacketType::TrustSignature->value, $data, diff --git a/src/Packet/SignatureSubpacket.php b/src/Packet/SignatureSubpacket.php index 1a0b6a61..32be515d 100644 --- a/src/Packet/SignatureSubpacket.php +++ b/src/Packet/SignatureSubpacket.php @@ -33,9 +33,8 @@ public function __construct( private readonly int $type, private readonly string $data, private readonly bool $critical = false, - private readonly bool $isLong = false, - ) - { + private readonly bool $isLong = false + ) { } /** diff --git a/src/Packet/SubpacketReader.php b/src/Packet/SubpacketReader.php index 7f4cdf87..691c2cac 100644 --- a/src/Packet/SubpacketReader.php +++ b/src/Packet/SubpacketReader.php @@ -32,11 +32,10 @@ class SubpacketReader */ public function __construct( private readonly int $type = 0, - private readonly string $data = '', + private readonly string $data = "", private readonly int $length = 0, - private readonly bool $isLong = false, - ) - { + private readonly bool $isLong = false + ) { } /** @@ -91,119 +90,172 @@ public static function readSignatureSubpackets(string $bytes): array while (strlen($bytes)) { $reader = self::read($bytes); Strings::shift($bytes, $reader->getLength()); - $critical = (($reader->getType() & 0x80) != 0); + $critical = ($reader->getType() & 0x80) != 0; $type = SignatureSubpacketType::from($reader->getType() & 0x7f); $subpackets[] = match ($type) { SignatureSubpacketType::SignatureCreationTime => new Signature\SignatureCreationTime( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::SignatureExpirationTime => new Signature\SignatureExpirationTime( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::ExportableCertification => new Signature\ExportableCertification( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::TrustSignature => new Signature\TrustSignature( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::RegularExpression => new Signature\RegularExpression( - $reader->getData(), $critical, $reader->isLong() - ), - SignatureSubpacketType::Revocable - => new Signature\Revocable( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), + SignatureSubpacketType::Revocable => new Signature\Revocable( + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::KeyExpirationTime => new Signature\KeyExpirationTime( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PreferredSymmetricAlgorithms => new Signature\PreferredSymmetricAlgorithms( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::RevocationKey => new Signature\RevocationKey( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::IssuerKeyID => new Signature\IssuerKeyID( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::NotationData => new Signature\NotationData( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PreferredHashAlgorithms => new Signature\PreferredHashAlgorithms( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PreferredCompressionAlgorithms => new Signature\PreferredCompressionAlgorithms( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::KeyServerPreferences => new Signature\KeyServerPreferences( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PreferredKeyServer => new Signature\PreferredKeyServer( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PrimaryUserID => new Signature\PrimaryUserID( - $reader->getData(), $critical, $reader->isLong() - ), - SignatureSubpacketType::PolicyURI - => new Signature\PolicyURI( - $reader->getData(), $critical, $reader->isLong() - ), - SignatureSubpacketType::KeyFlags - => new Signature\KeyFlags( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), + SignatureSubpacketType::PolicyURI => new Signature\PolicyURI( + $reader->getData(), + $critical, + $reader->isLong() + ), + SignatureSubpacketType::KeyFlags => new Signature\KeyFlags( + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::SignerUserID => new Signature\SignerUserID( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::RevocationReason => new Signature\RevocationReason( - $reader->getData(), $critical, $reader->isLong() - ), - SignatureSubpacketType::Features - => new Signature\Features( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), + SignatureSubpacketType::Features => new Signature\Features( + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::SignatureTarget => new Signature\SignatureTarget( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::EmbeddedSignature => new Signature\EmbeddedSignature( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::IssuerFingerprint => new Signature\IssuerFingerprint( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PreferredAeadAlgorithms => new Signature\PreferredAeadAlgorithms( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::IntendedRecipientFingerprint => new Signature\IntendedRecipientFingerprint( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), SignatureSubpacketType::PreferredAeadCiphers => new Signature\PreferredAeadCiphers( - $reader->getData(), $critical, $reader->isLong() - ), + $reader->getData(), + $critical, + $reader->isLong() + ), default => new SignatureSubpacket( - $type->value, $reader->getData(), $critical, $reader->isLong() + $type->value, + $reader->getData(), + $critical, + $reader->isLong() ), }; } @@ -225,12 +277,12 @@ public static function readUserAttributes(string $bytes): array $attributes[] = match ($reader->getType()) { ImageUserAttribute::JPEG => new ImageUserAttribute( $reader->getData(), - $reader->isLong(), + $reader->isLong() ), default => new UserAttributeSubpacket( $reader->getType(), $reader->getData(), - $reader->isLong(), + $reader->isLong() ), }; } @@ -250,11 +302,9 @@ public static function read(string $bytes): self $header = ord($bytes[$offset++]); if ($header < 192) { $length = $header; - } - elseif ($header < 255) { - $length = (($header - 192) << 8) + (ord($bytes[$offset++])) + 192; - } - else { + } elseif ($header < 255) { + $length = ($header - 192 << 8) + ord($bytes[$offset++]) + 192; + } else { $isLong = true; $length = Helper::bytesToLong($bytes, $offset); $offset += 4; @@ -264,7 +314,7 @@ public static function read(string $bytes): self ord($bytes[$offset]), substr($bytes, $offset + 1, $length - 1), $offset + $length, - $isLong, + $isLong ); } } diff --git a/src/Packet/SymEncryptedData.php b/src/Packet/SymEncryptedData.php index 1e57347b..2aa5819b 100644 --- a/src/Packet/SymEncryptedData.php +++ b/src/Packet/SymEncryptedData.php @@ -8,18 +8,12 @@ namespace OpenPGP\Packet; -use OpenPGP\Common\{ - Config, - Helper, -}; -use OpenPGP\Enum\{ - PacketTag, - SymmetricAlgorithm, -}; +use OpenPGP\Common\{Config, Helper}; +use OpenPGP\Enum\{PacketTag, SymmetricAlgorithm}; use OpenPGP\Type\{ EncryptedDataPacketInterface, PacketListInterface, - SessionKeyInterface, + SessionKeyInterface }; /** @@ -31,7 +25,8 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class SymEncryptedData extends AbstractPacket implements EncryptedDataPacketInterface +class SymEncryptedData extends AbstractPacket implements + EncryptedDataPacketInterface { use EncryptedDataTrait; @@ -46,9 +41,8 @@ class SymEncryptedData extends AbstractPacket implements EncryptedDataPacketInte */ public function __construct( private readonly string $encrypted, - private readonly ?PacketListInterface $packetList = null, - ) - { + private readonly ?PacketListInterface $packetList = null + ) { parent::__construct(PacketTag::SymEncryptedData); } @@ -71,9 +65,8 @@ public static function fromBytes(string $bytes): self public static function encryptPackets( string $key, PacketListInterface $packetList, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ): self - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ): self { Helper::assertSymmetric($symmetric); $cipher = $symmetric->cipherEngine(Config::CIPHER_MODE); $cipher->setKey($key); @@ -82,7 +75,8 @@ public static function encryptPackets( $cipher->setIV(substr($prefix, 2)); return new self( - $prefix . $cipher->encrypt($packetList->encode()), $packetList + $prefix . $cipher->encrypt($packetList->encode()), + $packetList ); } @@ -94,13 +88,13 @@ public static function encryptPackets( * @return self */ public static function encryptPacketsWithSessionKey( - SessionKeyInterface $sessionKey, PacketListInterface $packetList - ): self - { + SessionKeyInterface $sessionKey, + PacketListInterface $packetList + ): self { return self::encryptPackets( $sessionKey->getEncryptionKey(), $packetList, - $sessionKey->getSymmetric(), + $sessionKey->getSymmetric() ); } @@ -117,16 +111,14 @@ public function toBytes(): string */ public function decrypt( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ): self - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ): self { if (!Config::allowUnauthenticated()) { - throw new \RuntimeException('Message is not authenticated.'); + throw new \RuntimeException("Message is not authenticated."); } if ($this->packetList instanceof PacketListInterface) { return $this; - } - else { + } else { $blockSize = $symmetric->blockSize(); $cipher = $symmetric->cipherEngine(Config::CIPHER_MODE); $cipher->setKey($key); @@ -136,7 +128,7 @@ public function decrypt( $this->encrypted, PacketList::decode( $cipher->decrypt(substr($this->encrypted, $blockSize + 2)) - ), + ) ); } } diff --git a/src/Packet/SymEncryptedIntegrityProtectedData.php b/src/Packet/SymEncryptedIntegrityProtectedData.php index 25911543..3415b070 100644 --- a/src/Packet/SymEncryptedIntegrityProtectedData.php +++ b/src/Packet/SymEncryptedIntegrityProtectedData.php @@ -8,20 +8,12 @@ namespace OpenPGP\Packet; -use OpenPGP\Common\{ - Config, - Helper, -}; -use OpenPGP\Enum\{ - AeadAlgorithm, - HashAlgorithm, - PacketTag, - SymmetricAlgorithm, -}; +use OpenPGP\Common\{Config, Helper}; +use OpenPGP\Enum\{AeadAlgorithm, HashAlgorithm, PacketTag, SymmetricAlgorithm}; use OpenPGP\Type\{ AeadEncryptedDataPacketInterface, PacketListInterface, - SessionKeyInterface, + SessionKeyInterface }; use phpseclib3\Common\Functions\Strings; use phpseclib3\Crypt\Random; @@ -35,15 +27,16 @@ * @category Packet * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -class SymEncryptedIntegrityProtectedData extends AbstractPacket implements AeadEncryptedDataPacketInterface +class SymEncryptedIntegrityProtectedData extends AbstractPacket implements + AeadEncryptedDataPacketInterface { use AeadEncryptedDataTrait, EncryptedDataTrait; - const VERSION_1 = 1; - const VERSION_2 = 2; - const HASH_ALGO = 'sha1'; + const VERSION_1 = 1; + const VERSION_2 = 2; + const HASH_ALGO = "sha1"; const MDC_SUFFIX = "\xd3\x14"; - const SALT_SIZE = 32; + const SALT_SIZE = 32; /** * Constructor @@ -63,14 +56,13 @@ public function __construct( private readonly ?SymmetricAlgorithm $symmetric = null, private readonly ?AeadAlgorithm $aead = null, private readonly int $chunkSize = 12, - private readonly string $salt = '', - private readonly ?PacketListInterface $packetList = null, - ) - { + private readonly string $salt = "", + private readonly ?PacketListInterface $packetList = null + ) { parent::__construct(PacketTag::SymEncryptedIntegrityProtectedData); if ($version !== self::VERSION_1 && $version !== self::VERSION_2) { throw new \InvalidArgumentException( - "Version $version of the SEIPD packet is unsupported.", + "Version $version of the SEIPD packet is unsupported." ); } $isV2 = $version === self::VERSION_2; @@ -84,7 +76,7 @@ public function __construct( } if (!empty($salt) && strlen($salt) !== self::SALT_SIZE) { throw new \LengthException( - 'Salt size must be ' . self::SALT_SIZE . ' bytes.' + "Salt size must be " . self::SALT_SIZE . " bytes." ); } } @@ -119,14 +111,11 @@ public static function fromBytes(string $bytes): self $symmetric, $aead, $chunkSize, - $salt, + $salt ); } - return new self( - $version, - substr($bytes, $offset), - ); + return new self($version, substr($bytes, $offset)); } /** @@ -142,31 +131,31 @@ public static function encryptPackets( string $key, PacketListInterface $packetList, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ?AeadAlgorithm $aead = null, - ): self - { + ?AeadAlgorithm $aead = null + ): self { Helper::assertSymmetric($symmetric); $aeadProtect = $aead instanceof AeadAlgorithm; $version = $aeadProtect ? self::VERSION_2 : self::VERSION_1; - $salt = ''; + $salt = ""; $chunkSize = 0; if ($aeadProtect) { $salt = Random::string(self::SALT_SIZE); $chunkSize = Config::getAeadChunkSize(); $cryptor = new self( $version, - '', + "", $symmetric, $aead, $chunkSize, - $salt, + $salt ); $encrypted = $cryptor->aeadCrypt( - self::AEAD_ENCRYPT, $key, $packetList->encode() + self::AEAD_ENCRYPT, + $key, + $packetList->encode() ); - } - else { + } else { $toHash = implode([ Helper::generatePrefix($symmetric), $packetList->encode(), @@ -189,7 +178,7 @@ public static function encryptPackets( $aead, $chunkSize, $salt, - $packetList, + $packetList ); } @@ -204,14 +193,13 @@ public static function encryptPackets( public static function encryptPacketsWithSessionKey( SessionKeyInterface $sessionKey, PacketListInterface $packetList, - ?AeadAlgorithm $aead = null, - ): self - { + ?AeadAlgorithm $aead = null + ): self { return self::encryptPackets( $sessionKey->getEncryptionKey(), $packetList, $sessionKey->getSymmetric(), - $aead, + $aead ); } @@ -220,19 +208,16 @@ public static function encryptPacketsWithSessionKey( */ public function toBytes(): string { - return $this->version === self::VERSION_2 ? - implode([ + return $this->version === self::VERSION_2 + ? implode([ chr($this->version), chr($this->symmetric->value), chr($this->aead->value), chr($this->chunkSize), $this->salt, $this->encrypted, - ]) : - implode([ - chr($this->version), - $this->encrypted, - ]); + ]) + : implode([chr($this->version), $this->encrypted]); } /** @@ -245,35 +230,37 @@ public function getSalt(): string return $this->salt; } - /** * {@inheritdoc} */ public function decrypt( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ): self - { + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 + ): self { if ($this->packetList instanceof PacketListInterface) { return $this; - } - else { + } else { $this->getLogger()->debug( - 'Decrypt the encrypted data contained in the packet.' + "Decrypt the encrypted data contained in the packet." ); if ($this->aead instanceof AeadAlgorithm) { $length = strlen($this->encrypted); $data = substr( - $this->encrypted, 0, $length - $this->aead->tagLength() + $this->encrypted, + 0, + $length - $this->aead->tagLength() ); $authTag = substr( - $this->encrypted, $length - $this->aead->tagLength() + $this->encrypted, + $length - $this->aead->tagLength() ); $packetBytes = $this->aeadCrypt( - self::AEAD_DECRYPT, $key, $data, $authTag + self::AEAD_DECRYPT, + $key, + $data, + $authTag ); - } - else { + } else { $symmetric = $this->symmetric ?? $symmetric; $size = $symmetric->blockSize(); $cipher = $symmetric->cipherEngine(Config::CIPHER_MODE); @@ -281,15 +268,21 @@ public function decrypt( $cipher->setIV(str_repeat(self::ZERO_CHAR, $size)); $decrypted = $cipher->decrypt($this->encrypted); - $digestSize = strlen($decrypted) - HashAlgorithm::Sha1->digestSize(); + $digestSize = + strlen($decrypted) - HashAlgorithm::Sha1->digestSize(); $realHash = substr($decrypted, $digestSize); $toHash = substr($decrypted, 0, $digestSize); - if (strcmp($realHash, hash(self::HASH_ALGO, $toHash, true)) !== 0) { - throw new \RuntimeException('Modification detected.'); + if ( + strcmp($realHash, hash(self::HASH_ALGO, $toHash, true)) !== + 0 + ) { + throw new \RuntimeException("Modification detected."); } // Remove random prefix & MDC packet $packetBytes = substr( - $toHash, $size + 2, strlen($toHash) - $size - 4 + $toHash, + $size + 2, + strlen($toHash) - $size - 4 ); } @@ -300,7 +293,7 @@ public function decrypt( $this->aead, $this->chunkSize, $this->salt, - PacketList::decode($packetBytes), + PacketList::decode($packetBytes) ); } } @@ -315,11 +308,13 @@ public function decrypt( * @return string */ private function aeadCrypt( - string $fn, string $key, string $data, string $finalChunk = '' - ): string - { + string $fn, + string $key, + string $data, + string $finalChunk = "" + ): string { // chunkSize = (uint32_t) 1 << (c + 6) - $chunkSize = (1 << ($this->chunkSize + 6)); + $chunkSize = 1 << $this->chunkSize + 6; if ($fn === self::AEAD_DECRYPT) { $chunkSize += $this->aead->tagLength(); } @@ -329,47 +324,52 @@ private function aeadCrypt( $keySize = $this->symmetric->keySizeInByte(); $ivLength = $this->aead->ivLength(); $derivedKey = hash_hkdf( - Config::HKDF_ALGO, $key, $keySize + $ivLength, $aData, $this->salt + Config::HKDF_ALGO, + $key, + $keySize + $ivLength, + $aData, + $this->salt ); $kek = substr($derivedKey, 0, $keySize); $nonce = substr($derivedKey, $keySize, $ivLength); // The last 8 bytes of HKDF output are unneeded, but this avoids one copy. $nonce = substr_replace( - $nonce, str_repeat(self::ZERO_CHAR, 8), $ivLength - 8 + $nonce, + str_repeat(self::ZERO_CHAR, 8), + $ivLength - 8 ); $cipher = $this->aead->cipherEngine($kek, $this->symmetric); $crypted = []; - for ($index = 0; $index === 0 || strlen($data);) { + for ($index = 0; $index === 0 || strlen($data); ) { // Take a chunk of `data`, en/decrypt it, and shift `data` to the next chunk. $crypted[] = $cipher->$fn( Strings::shift($data, $chunkSize), $nonce, - $aData, + $aData ); $nonce = substr_replace( - $nonce, pack('N', ++$index), $ivLength - 4, 4 + $nonce, + pack("N", ++$index), + $ivLength - 4, + 4 ); } $processed = array_sum( - array_map(static fn ($bytes) => strlen($bytes), $crypted) + array_map(static fn($bytes) => strlen($bytes), $crypted) ); - $aDataTag = implode([ - $aData, - str_repeat(self::ZERO_CHAR, 8), - ]); + $aDataTag = implode([$aData, str_repeat(self::ZERO_CHAR, 8)]); $aDataTag = substr_replace( - $aDataTag, pack('N', $processed), strlen($aDataTag) - 4, 4 + $aDataTag, + pack("N", $processed), + strlen($aDataTag) - 4, + 4 ); // After the final chunk, we either encrypt a final, empty data // chunk to get the final authentication tag or validate that final // authentication tag. - $crypted[] = $cipher->$fn( - $finalChunk, - $nonce, - $aDataTag, - ); + $crypted[] = $cipher->$fn($finalChunk, $nonce, $aDataTag); return implode($crypted); } } diff --git a/src/Packet/SymEncryptedSessionKey.php b/src/Packet/SymEncryptedSessionKey.php index 72e91bbb..e79313a8 100644 --- a/src/Packet/SymEncryptedSessionKey.php +++ b/src/Packet/SymEncryptedSessionKey.php @@ -8,22 +8,9 @@ namespace OpenPGP\Packet; -use OpenPGP\Common\{ - Argon2S2K, - Config, - GenericS2K, - Helper, -}; -use OpenPGP\Enum\{ - AeadAlgorithm, - PacketTag, - S2kType, - SymmetricAlgorithm, -}; -use OpenPGP\Type\{ - S2KInterface, - SessionKeyInterface, -}; +use OpenPGP\Common\{Argon2S2K, Config, GenericS2K, Helper}; +use OpenPGP\Enum\{AeadAlgorithm, PacketTag, S2kType, SymmetricAlgorithm}; +use OpenPGP\Type\{S2KInterface, SessionKeyInterface}; use phpseclib3\Crypt\Random; /** @@ -59,13 +46,13 @@ public function __construct( private readonly S2KInterface $s2k, private readonly SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, private readonly ?AeadAlgorithm $aead = null, - private readonly string $iv = '', - private readonly string $encrypted = '', - private readonly ?SessionKeyInterface $sessionKey = null, - ) - { + private readonly string $iv = "", + private readonly string $encrypted = "", + private readonly ?SessionKeyInterface $sessionKey = null + ) { parent::__construct(PacketTag::SymEncryptedSessionKey); - if ($version != self::VERSION_4 && + if ( + $version != self::VERSION_4 && $version != self::VERSION_5 && $version != self::VERSION_6 ) { @@ -116,9 +103,10 @@ public static function fromBytes(string $bytes): self // A string-to-key (S2K) specifier, length as defined above. $s2kType = S2kType::from(ord($bytes[$offset])); - $s2k = ($s2kType === S2kType::Argon2) ? - Argon2S2K::fromBytes(substr($bytes, $offset)) : - GenericS2K::fromBytes(substr($bytes, $offset)); + $s2k = + $s2kType === S2kType::Argon2 + ? Argon2S2K::fromBytes(substr($bytes, $offset)) + : GenericS2K::fromBytes(substr($bytes, $offset)); $offset += $s2kType->dataLength(); // A starting initialization vector of size specified by the AEAD algorithm. @@ -131,7 +119,7 @@ public static function fromBytes(string $bytes): self $symmetric, $aead, $iv, - substr($bytes, $offset), + substr($bytes, $offset) ); } @@ -148,23 +136,23 @@ public static function encryptSessionKey( string $password, ?SessionKeyInterface $sessionKey = null, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ?AeadAlgorithm $aead = null, - ): self - { + ?AeadAlgorithm $aead = null + ): self { $aeadProtect = $aead instanceof AeadAlgorithm; $version = $aeadProtect ? self::VERSION_6 : self::VERSION_4; $symmetric = $sessionKey?->getSymmetric() ?? $symmetric; Helper::assertSymmetric($symmetric); - $s2k = $aeadProtect && Argon2S2K::argon2Supported() ? - Helper::stringToKey(S2kType::Argon2) : - Helper::stringToKey(S2kType::Iterated); + $s2k = + $aeadProtect && Argon2S2K::argon2Supported() + ? Helper::stringToKey(S2kType::Argon2) + : Helper::stringToKey(S2kType::Iterated); $keySize = $symmetric->keySizeInByte(); $key = $s2k->produceKey($password, $keySize); - $iv = ''; - $encrypted = ''; + $iv = ""; + $encrypted = ""; if ($sessionKey instanceof SessionKeyInterface) { if ($aeadProtect) { @@ -176,16 +164,15 @@ public static function encryptSessionKey( ]); $iv = Random::string($aead->ivLength()); $cipher = $aead->cipherEngine( - hash_hkdf( - Config::HKDF_ALGO, $key, $keySize, $aData - ), - $symmetric, + hash_hkdf(Config::HKDF_ALGO, $key, $keySize, $aData), + $symmetric ); $encrypted = $cipher->encrypt( - $sessionKey->getEncryptionKey(), $iv, $aData + $sessionKey->getEncryptionKey(), + $iv, + $aData ); - } - else { + } else { $cipher = $symmetric->cipherEngine(Config::CIPHER_MODE); $cipher->setKey($key); $cipher->setIV( @@ -193,8 +180,7 @@ public static function encryptSessionKey( ); $encrypted = $cipher->encrypt($sessionKey->toBytes()); } - } - else { + } else { $sessionKey = new Key\SessionKey($key, $symmetric); } @@ -205,7 +191,7 @@ public static function encryptSessionKey( $aead, $iv, $encrypted, - $sessionKey, + $sessionKey ); } @@ -289,17 +275,15 @@ public function decrypt(string $password): self { if ($this->sessionKey instanceof SessionKeyInterface) { return $this; - } - else { + } else { $this->getLogger()->debug( - 'Decrypt symmetric key encrypted session key.' + "Decrypt symmetric key encrypted session key." ); $keySize = $this->symmetric->keySizeInByte(); $key = $this->s2k->produceKey($password, $keySize); if (empty($this->encrypted)) { $sessionKey = new Key\SessionKey($key, $this->symmetric); - } - else { + } else { if ($this->aead instanceof AeadAlgorithm) { $aData = implode([ chr(0xc0 | $this->getTag()->value), @@ -307,33 +291,43 @@ public function decrypt(string $password): self chr($this->symmetric->value), chr($this->aead->value), ]); - $kek = $this->version === self::VERSION_6 ? hash_hkdf( - Config::HKDF_ALGO, $key, $keySize, $aData - ) : $key; - $cipher = $this->aead->cipherEngine( - $kek, $this->symmetric - ); + $kek = + $this->version === self::VERSION_6 + ? hash_hkdf( + Config::HKDF_ALGO, + $key, + $keySize, + $aData + ) + : $key; + $cipher = $this->aead->cipherEngine($kek, $this->symmetric); $decrypted = $cipher->decrypt( - $this->encrypted, $this->iv, $aData + $this->encrypted, + $this->iv, + $aData ); $sessionKey = new Key\SessionKey( - $decrypted, $this->symmetric + $decrypted, + $this->symmetric ); - } - else { + } else { $cipher = $this->symmetric->cipherEngine( Config::CIPHER_MODE ); $cipher->setKey($key); - $cipher->setIV(str_repeat( - self::ZERO_CHAR, $this->symmetric->blockSize() - )); + $cipher->setIV( + str_repeat( + self::ZERO_CHAR, + $this->symmetric->blockSize() + ) + ); $decrypted = $cipher->decrypt($this->encrypted); $sessionKeySymmetric = SymmetricAlgorithm::from( ord($decrypted[0]) ); $sessionKey = new Key\SessionKey( - substr($decrypted, 1), $sessionKeySymmetric + substr($decrypted, 1), + $sessionKeySymmetric ); } } @@ -344,7 +338,7 @@ public function decrypt(string $password): self $this->aead, $this->iv, $this->encrypted, - $sessionKey, + $sessionKey ); } } diff --git a/src/Packet/UserAttribute.php b/src/Packet/UserAttribute.php index 8b12380a..8b79c4a4 100644 --- a/src/Packet/UserAttribute.php +++ b/src/Packet/UserAttribute.php @@ -35,7 +35,7 @@ public function __construct(array $attributes) parent::__construct(PacketTag::UserAttribute); $this->attributes = array_filter( $attributes, - static fn ($attr) => $attr instanceof UserAttributeSubpacket, + static fn($attr) => $attr instanceof UserAttributeSubpacket ); } @@ -52,10 +52,12 @@ public static function fromBytes(string $bytes): self */ public function toBytes(): string { - return implode(array_map( - static fn ($attr): string => $attr->toBytes(), - $this->attributes, - )); + return implode( + array_map( + static fn($attr): string => $attr->toBytes(), + $this->attributes + ) + ); } /** @@ -64,11 +66,7 @@ public function toBytes(): string public function getSignBytes(): string { $bytes = $this->toBytes(); - return implode([ - "\xd1", - pack('N', strlen($bytes)), - $bytes, - ]); + return implode(["\xd1", pack("N", strlen($bytes)), $bytes]); } /** diff --git a/src/Packet/UserAttributeSubpacket.php b/src/Packet/UserAttributeSubpacket.php index 4f26956c..52ae9a47 100644 --- a/src/Packet/UserAttributeSubpacket.php +++ b/src/Packet/UserAttributeSubpacket.php @@ -30,10 +30,9 @@ class UserAttributeSubpacket implements SubpacketInterface */ public function __construct( private readonly int $type = 0, - private readonly string $data = '', - private readonly bool $isLong = false, - ) - { + private readonly string $data = "", + private readonly bool $isLong = false + ) { } /** diff --git a/src/Packet/UserID.php b/src/Packet/UserID.php index 0ee92dc1..cc7e2cbe 100644 --- a/src/Packet/UserID.php +++ b/src/Packet/UserID.php @@ -37,8 +37,8 @@ class UserID extends AbstractPacket implements UserIDPacketInterface public function __construct(private readonly string $userID) { parent::__construct(PacketTag::UserID); - $this->name = $this->extractName(); - $this->email = $this->extractEmail(); + $this->name = $this->extractName(); + $this->email = $this->extractEmail(); $this->comment = $this->extractComment(); } @@ -65,7 +65,7 @@ public function getSignBytes(): string { return implode([ "\xb4", - pack('N', strlen($this->userID)), + pack("N", strlen($this->userID)), $this->userID, ]); } @@ -115,7 +115,7 @@ private function extractName(): string $nameChars = []; $chars = str_split($this->userID); foreach ($chars as $char) { - if ($char === '(' || $char === '<') { + if ($char === "(" || $char === "<") { break; } $nameChars[] = $char; @@ -125,21 +125,20 @@ private function extractName(): string private function extractEmail(): string { - preg_match('/[\w\.-]+@[\w\.-]+\.\w{2,4}/', $this->userID, $matches); - return $matches[0] ?? ''; + preg_match("/[\w\.-]+@[\w\.-]+\.\w{2,4}/", $this->userID, $matches); + return $matches[0] ?? ""; } private function extractComment(): string { - if (str_contains($this->userID, '(') && str_contains($this->userID, ')')) { - $start = (int) strpos($this->userID, '(') + 1; - $end = (int) strpos($this->userID, ')'); - return substr( - $this->userID, - $start, - $end - $start, - ); + if ( + str_contains($this->userID, "(") && + str_contains($this->userID, ")") + ) { + $start = (int) strpos($this->userID, "(") + 1; + $end = (int) strpos($this->userID, ")"); + return substr($this->userID, $start, $end - $start); } - return ''; + return ""; } } diff --git a/src/Type/AeadEncryptedDataPacketInterface.php b/src/Type/AeadEncryptedDataPacketInterface.php index 40f20b9b..a250b9b3 100644 --- a/src/Type/AeadEncryptedDataPacketInterface.php +++ b/src/Type/AeadEncryptedDataPacketInterface.php @@ -8,10 +8,7 @@ namespace OpenPGP\Type; -use OpenPGP\Enum\{ - AeadAlgorithm, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{AeadAlgorithm, SymmetricAlgorithm}; /** * Aead encrypted data packet packet interface @@ -24,8 +21,8 @@ interface AeadEncryptedDataPacketInterface extends EncryptedDataPacketInterface { const ZERO_CHAR = "\x00"; - const AEAD_ENCRYPT = 'encrypt'; - const AEAD_DECRYPT = 'decrypt'; + const AEAD_ENCRYPT = "encrypt"; + const AEAD_DECRYPT = "decrypt"; /** * Get version diff --git a/src/Type/CleartextMessageInterface.php b/src/Type/CleartextMessageInterface.php index ff186bc9..689a4e7b 100644 --- a/src/Type/CleartextMessageInterface.php +++ b/src/Type/CleartextMessageInterface.php @@ -46,7 +46,7 @@ function sign( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): SignedMessageInterface; /** @@ -62,7 +62,7 @@ function signDetached( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): SignatureInterface; /** @@ -76,6 +76,6 @@ function signDetached( function verifyDetached( array $verificationKeys, SignatureInterface $signature, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): array; } diff --git a/src/Type/EncryptedDataPacketInterface.php b/src/Type/EncryptedDataPacketInterface.php index 8dd627a0..3f716774 100644 --- a/src/Type/EncryptedDataPacketInterface.php +++ b/src/Type/EncryptedDataPacketInterface.php @@ -42,7 +42,7 @@ function getPacketList(): ?PacketListInterface; */ function encrypt( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 ): self; /** @@ -51,9 +51,7 @@ function encrypt( * @param SessionKeyInterface $sessionKey * @return self */ - function encryptWithSessionKey( - SessionKeyInterface $sessionKey - ): self; + function encryptWithSessionKey(SessionKeyInterface $sessionKey): self; /** * Decrypt the encrypted data contained in the packet. @@ -64,7 +62,7 @@ function encryptWithSessionKey( */ function decrypt( string $key, - SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, + SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128 ): self; /** @@ -73,7 +71,5 @@ function decrypt( * @param SessionKeyInterface $sessionKey * @return self */ - function decryptWithSessionKey( - SessionKeyInterface $sessionKey - ): self; + function decryptWithSessionKey(SessionKeyInterface $sessionKey): self; } diff --git a/src/Type/KeyInterface.php b/src/Type/KeyInterface.php index 8f677727..6dbc9b17 100644 --- a/src/Type/KeyInterface.php +++ b/src/Type/KeyInterface.php @@ -9,14 +9,8 @@ namespace OpenPGP\Type; use DateTimeInterface; -use OpenPGP\Enum\{ - KeyAlgorithm, - RevocationReasonTag, -}; -use Psr\Log\{ - LoggerAwareInterface, - LoggerInterface, -}; +use OpenPGP\Enum\{KeyAlgorithm, RevocationReasonTag}; +use Psr\Log\{LoggerAwareInterface, LoggerInterface}; /** * Key interface @@ -25,7 +19,10 @@ * @category Type * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -interface KeyInterface extends ArmorableInterface, LoggerAwareInterface, PacketContainerInterface +interface KeyInterface extends + ArmorableInterface, + LoggerAwareInterface, + PacketContainerInterface { /** * Return key packet @@ -122,7 +119,8 @@ function getLatestDirectSignature(): ?SignaturePacketInterface; * @return KeyPacketInterface */ function getSigningKeyPacket( - string $keyID = '', ?DateTimeInterface $time = null + string $keyID = "", + ?DateTimeInterface $time = null ): KeyPacketInterface; /** @@ -134,7 +132,8 @@ function getSigningKeyPacket( * @return KeyPacketInterface */ function getEncryptionKeyPacket( - string $keyID = '', ?DateTimeInterface $time = null + string $keyID = "", + ?DateTimeInterface $time = null ): KeyPacketInterface; /** @@ -184,7 +183,7 @@ function aeadSupported(): bool; function isRevoked( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): bool; /** @@ -198,7 +197,7 @@ function isRevoked( function isCertified( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): bool; /** @@ -209,9 +208,7 @@ function isCertified( * @param DateTimeInterface $time * @return bool */ - function verify( - string $userID = '', ?DateTimeInterface $time = null - ): bool; + function verify(string $userID = "", ?DateTimeInterface $time = null): bool; /** * Certify by private key. @@ -221,7 +218,8 @@ function verify( * @return self */ function certifyBy( - PrivateKeyInterface $signKey, ?DateTimeInterface $time = null + PrivateKeyInterface $signKey, + ?DateTimeInterface $time = null ): self; /** @@ -235,9 +233,9 @@ function certifyBy( */ function revokeBy( PrivateKeyInterface $signKey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; /** diff --git a/src/Type/KeyPacketInterface.php b/src/Type/KeyPacketInterface.php index 8b588949..b736a4b3 100644 --- a/src/Type/KeyPacketInterface.php +++ b/src/Type/KeyPacketInterface.php @@ -9,10 +9,7 @@ namespace OpenPGP\Type; use DateTimeInterface; -use OpenPGP\Enum\{ - HashAlgorithm, - KeyAlgorithm, -}; +use OpenPGP\Enum\{HashAlgorithm, KeyAlgorithm}; /** * Key packet interface diff --git a/src/Type/LiteralMessageInterface.php b/src/Type/LiteralMessageInterface.php index 3963b931..2812d9a6 100644 --- a/src/Type/LiteralMessageInterface.php +++ b/src/Type/LiteralMessageInterface.php @@ -9,10 +9,7 @@ namespace OpenPGP\Type; use DateTimeInterface; -use OpenPGP\Enum\{ - CompressionAlgorithm, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{CompressionAlgorithm, SymmetricAlgorithm}; /** * Literal message interface @@ -21,7 +18,9 @@ * @category Type * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -interface LiteralMessageInterface extends ArmorableInterface, PacketContainerInterface +interface LiteralMessageInterface extends + ArmorableInterface, + PacketContainerInterface { /** * Get literal data @@ -43,7 +42,7 @@ function sign( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; /** @@ -59,7 +58,7 @@ function signDetached( array $signingKeys, array $recipients = [], ?NotationDataInterface $notationData = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): SignatureInterface; /** @@ -74,7 +73,7 @@ function signDetached( function verifyDetached( array $verificationKeys, SignatureInterface $signature, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): array; /** @@ -89,7 +88,7 @@ function verifyDetached( function encrypt( array $encryptionKeys = [], array $passwords = [], - ?SymmetricAlgorithm $symmetric = null, + ?SymmetricAlgorithm $symmetric = null ): EncryptedMessageInterface; /** @@ -99,7 +98,5 @@ function encrypt( * @param CompressionAlgorithm $algorithm * @return self */ - function compress( - ?CompressionAlgorithm $algorithm = null - ): self; + function compress(?CompressionAlgorithm $algorithm = null): self; } diff --git a/src/Type/PacketListInterface.php b/src/Type/PacketListInterface.php index bb6994fb..e8101cbe 100644 --- a/src/Type/PacketListInterface.php +++ b/src/Type/PacketListInterface.php @@ -17,7 +17,10 @@ * @category Type * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -interface PacketListInterface extends \ArrayAccess, \IteratorAggregate, \Countable +interface PacketListInterface extends + \ArrayAccess, + \IteratorAggregate, + \Countable { /** * Get array packets diff --git a/src/Type/PrivateKeyInterface.php b/src/Type/PrivateKeyInterface.php index 96876e47..9468e94c 100644 --- a/src/Type/PrivateKeyInterface.php +++ b/src/Type/PrivateKeyInterface.php @@ -9,12 +9,7 @@ namespace OpenPGP\Type; use DateTimeInterface; -use OpenPGP\Enum\{ - CurveOid, - KeyAlgorithm, - RevocationReasonTag, - RSAKeySize, -}; +use OpenPGP\Enum\{CurveOid, KeyAlgorithm, RevocationReasonTag, RSAKeySize}; /** * Private key interface @@ -61,7 +56,8 @@ function getSecretKeyPacket(): SecretKeyPacketInterface; * @return array */ function getDecryptionKeyPackets( - string $keyID = '', ?DateTimeInterface $time = null + string $keyID = "", + ?DateTimeInterface $time = null ): array; /** @@ -72,10 +68,7 @@ function getDecryptionKeyPackets( * @param array $subkeyPassphrases * @return self */ - function encrypt( - string $passphrase, - array $subkeyPassphrases = [], - ): self; + function encrypt(string $passphrase, array $subkeyPassphrases = []): self; /** * Unlock a private key with the given passphrase. @@ -85,10 +78,7 @@ function encrypt( * @param array $subkeyPassphrases * @return self */ - function decrypt( - string $passphrase, - array $subkeyPassphrases = [], - ): self; + function decrypt(string $passphrase, array $subkeyPassphrases = []): self; /** * Add userIDs to the key. @@ -119,7 +109,7 @@ function addSubkey( CurveOid $curve = CurveOid::Secp521r1, int $keyExpiry = 0, bool $forSigning = false, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; /** @@ -132,7 +122,7 @@ function addSubkey( */ function certifyKey( KeyInterface $key, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): KeyInterface; /** @@ -147,9 +137,9 @@ function certifyKey( */ function revokeKey( KeyInterface $key, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): KeyInterface; /** @@ -163,9 +153,9 @@ function revokeKey( */ function revokeUser( string $userID, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; /** @@ -179,8 +169,8 @@ function revokeUser( */ function revokeSubkey( string $keyID, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; } diff --git a/src/Type/PublicKeyMaterialInterface.php b/src/Type/PublicKeyMaterialInterface.php index 71001eaf..0a54fcfa 100644 --- a/src/Type/PublicKeyMaterialInterface.php +++ b/src/Type/PublicKeyMaterialInterface.php @@ -8,8 +8,8 @@ namespace OpenPGP\Type; -use phpseclib3\Crypt\Common\PublicKey; use OpenPGP\Enum\HashAlgorithm; +use phpseclib3\Crypt\Common\PublicKey; /** * Public key material interface @@ -38,6 +38,6 @@ function getPublicKey(): PublicKey; function verify( HashAlgorithm $hash, string $message, - string $signature, + string $signature ): bool; } diff --git a/src/Type/SecretKeyMaterialInterface.php b/src/Type/SecretKeyMaterialInterface.php index f2a4c6da..4aaaa059 100644 --- a/src/Type/SecretKeyMaterialInterface.php +++ b/src/Type/SecretKeyMaterialInterface.php @@ -8,11 +8,8 @@ namespace OpenPGP\Type; -use phpseclib3\Crypt\Common\{ - PrivateKey, - PublicKey, -}; use OpenPGP\Enum\HashAlgorithm; +use phpseclib3\Crypt\Common\{PrivateKey, PublicKey}; /** * Secret key material interface diff --git a/src/Type/SecretKeyPacketInterface.php b/src/Type/SecretKeyPacketInterface.php index 886ccacf..8cdc1821 100644 --- a/src/Type/SecretKeyPacketInterface.php +++ b/src/Type/SecretKeyPacketInterface.php @@ -8,10 +8,7 @@ namespace OpenPGP\Type; -use OpenPGP\Enum\{ - AeadAlgorithm, - SymmetricAlgorithm, -}; +use OpenPGP\Enum\{AeadAlgorithm, SymmetricAlgorithm}; /** * Secret key packet interface @@ -61,7 +58,7 @@ function isDecrypted(): bool; function encrypt( string $passphrase, SymmetricAlgorithm $symmetric = SymmetricAlgorithm::Aes128, - ?AeadAlgorithm $aead = null, + ?AeadAlgorithm $aead = null ): self; /** diff --git a/src/Type/SignatureInterface.php b/src/Type/SignatureInterface.php index af82104f..ee198b07 100644 --- a/src/Type/SignatureInterface.php +++ b/src/Type/SignatureInterface.php @@ -17,7 +17,9 @@ * @category Type * @author Nguyen Van Nguyen - nguyennv1981@gmail.com */ -interface SignatureInterface extends ArmorableInterface, PacketContainerInterface +interface SignatureInterface extends + ArmorableInterface, + PacketContainerInterface { /** * Get signing key IDs @@ -39,7 +41,7 @@ function getSigningKeyIDs(bool $toHex = false): array; function verify( array $verificationKeys, LiteralDataInterface $literalData, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): array; /** @@ -54,6 +56,6 @@ function verify( function verifyCleartext( array $verificationKeys, CleartextMessageInterface $cleartext, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): array; } diff --git a/src/Type/SignaturePacketInterface.php b/src/Type/SignaturePacketInterface.php index c32e0ba9..65565b29 100644 --- a/src/Type/SignaturePacketInterface.php +++ b/src/Type/SignaturePacketInterface.php @@ -9,11 +9,7 @@ namespace OpenPGP\Type; use DateTimeInterface; -use OpenPGP\Enum\{ - HashAlgorithm, - KeyAlgorithm, - SignatureType, -}; +use OpenPGP\Enum\{HashAlgorithm, KeyAlgorithm, SignatureType}; /** * Signature packet interface @@ -116,7 +112,7 @@ function isExpired(?DateTimeInterface $time = null): bool; function verify( KeyPacketInterface $verifyKey, string $dataToVerify, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): bool; /** diff --git a/src/Type/SignedMessageInterface.php b/src/Type/SignedMessageInterface.php index dd9a9828..13551693 100644 --- a/src/Type/SignedMessageInterface.php +++ b/src/Type/SignedMessageInterface.php @@ -36,6 +36,6 @@ function getSignature(): SignatureInterface; */ function verify( array $verificationKeys, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): array; } diff --git a/src/Type/SubkeyInterface.php b/src/Type/SubkeyInterface.php index 400c3ff6..b6b09cda 100644 --- a/src/Type/SubkeyInterface.php +++ b/src/Type/SubkeyInterface.php @@ -9,10 +9,7 @@ namespace OpenPGP\Type; use DateTimeInterface; -use OpenPGP\Enum\{ - KeyAlgorithm, - RevocationReasonTag, -}; +use OpenPGP\Enum\{KeyAlgorithm, RevocationReasonTag}; /** * Subkey interface @@ -134,7 +131,7 @@ function isEncryptionKey(): bool; function isRevoked( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): bool; /** @@ -157,8 +154,8 @@ function verify(?DateTimeInterface $time = null): bool; */ function revokeBy( PrivateKeyInterface $signKey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; } diff --git a/src/Type/UserInterface.php b/src/Type/UserInterface.php index 24fbfa52..4f72e1cc 100644 --- a/src/Type/UserInterface.php +++ b/src/Type/UserInterface.php @@ -88,7 +88,7 @@ function isPrimary(): bool; function isRevoked( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): bool; /** @@ -104,7 +104,7 @@ function isRevoked( function isCertified( ?KeyInterface $verifyKey = null, ?SignaturePacketInterface $certificate = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): bool; /** @@ -126,7 +126,8 @@ function verify(?DateTimeInterface $time = null): bool; * @return self */ function certifyBy( - PrivateKeyInterface $signKey, ?DateTimeInterface $time = null + PrivateKeyInterface $signKey, + ?DateTimeInterface $time = null ): self; /** @@ -140,8 +141,8 @@ function certifyBy( */ function revokeBy( PrivateKeyInterface $signKey, - string $revocationReason = '', + string $revocationReason = "", ?RevocationReasonTag $reasonTag = null, - ?DateTimeInterface $time = null, + ?DateTimeInterface $time = null ): self; }