first commit
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
github: singpolyma
|
||||
liberapay: singpolyma
|
||||
patreon: singpolyma
|
||||
@@ -0,0 +1,8 @@
|
||||
.DS_Store
|
||||
.tmp
|
||||
pkg
|
||||
tmp
|
||||
composer.lock
|
||||
.phpunit.result.cache
|
||||
.idea
|
||||
vendor/
|
||||
@@ -0,0 +1,30 @@
|
||||
let Prelude = https://prelude.dhall-lang.org/v17.0.0/package.dhall
|
||||
let phpseclib = \(max: Natural) -> \(filter: (Natural -> Bool)) ->
|
||||
Prelude.List.map Natural Text
|
||||
(\(m: Natural) -> "PHPSECLIB='2.0.${Prelude.Natural.show m}'")
|
||||
(Prelude.List.filter Natural filter (Prelude.Natural.enumerate max))
|
||||
let Exclusion = { php: Text, env: Text }
|
||||
in
|
||||
{
|
||||
language = "php",
|
||||
php = [
|
||||
"7.3",
|
||||
"7.4",
|
||||
"8.0"
|
||||
],
|
||||
dist = "xenial",
|
||||
env = [
|
||||
"PHPSECLIB='^2.0 !=2.0.8'"
|
||||
] # (phpseclib 28 (\(m: Natural) -> Prelude.Bool.not (Prelude.Natural.equal m 8))
|
||||
),
|
||||
matrix = {
|
||||
exclude = Prelude.List.concatMap Text Exclusion (\(php: Text) ->
|
||||
Prelude.List.map Text Exclusion (\(env: Text) ->
|
||||
{ php = php, env = env }
|
||||
) (phpseclib 7 (\(_: Natural) -> True))
|
||||
) ["7.3", "7.4", "8.0"],
|
||||
fast_finish = True
|
||||
},
|
||||
before_script = ''
|
||||
sed -i "s/\"phpseclib\/phpseclib\": \"[^\"]*/\"phpseclib\/phpseclib\": \"$PHPSECLIB/" composer.json && composer install --prefer-source''
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
# Code generated by dhall-to-yaml. DO NOT EDIT.
|
||||
before_script: "sed -i \"s/\\\"phpseclib\\/phpseclib\\\": \\\"[^\\\"]*/\\\"phpseclib\\/phpseclib\\\": \\\"$PHPSECLIB/\" composer.json && composer install --prefer-source"
|
||||
dist: xenial
|
||||
env:
|
||||
- "PHPSECLIB='^2.0 !=2.0.8'"
|
||||
- "PHPSECLIB='2.0.0'"
|
||||
- "PHPSECLIB='2.0.1'"
|
||||
- "PHPSECLIB='2.0.2'"
|
||||
- "PHPSECLIB='2.0.3'"
|
||||
- "PHPSECLIB='2.0.4'"
|
||||
- "PHPSECLIB='2.0.5'"
|
||||
- "PHPSECLIB='2.0.6'"
|
||||
- "PHPSECLIB='2.0.7'"
|
||||
- "PHPSECLIB='2.0.9'"
|
||||
- "PHPSECLIB='2.0.10'"
|
||||
- "PHPSECLIB='2.0.11'"
|
||||
- "PHPSECLIB='2.0.12'"
|
||||
- "PHPSECLIB='2.0.13'"
|
||||
- "PHPSECLIB='2.0.14'"
|
||||
- "PHPSECLIB='2.0.15'"
|
||||
- "PHPSECLIB='2.0.16'"
|
||||
- "PHPSECLIB='2.0.17'"
|
||||
- "PHPSECLIB='2.0.18'"
|
||||
- "PHPSECLIB='2.0.19'"
|
||||
- "PHPSECLIB='2.0.20'"
|
||||
- "PHPSECLIB='2.0.21'"
|
||||
- "PHPSECLIB='2.0.22'"
|
||||
- "PHPSECLIB='2.0.23'"
|
||||
- "PHPSECLIB='2.0.24'"
|
||||
- "PHPSECLIB='2.0.25'"
|
||||
- "PHPSECLIB='2.0.26'"
|
||||
- "PHPSECLIB='2.0.27'"
|
||||
language: php
|
||||
matrix:
|
||||
exclude:
|
||||
- env: "PHPSECLIB='2.0.0'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.1'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.2'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.3'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.4'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.5'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.6'"
|
||||
php: '7.3'
|
||||
- env: "PHPSECLIB='2.0.0'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.1'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.2'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.3'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.4'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.5'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.6'"
|
||||
php: '7.4'
|
||||
- env: "PHPSECLIB='2.0.0'"
|
||||
php: '8.0'
|
||||
- env: "PHPSECLIB='2.0.1'"
|
||||
php: '8.0'
|
||||
- env: "PHPSECLIB='2.0.2'"
|
||||
php: '8.0'
|
||||
- env: "PHPSECLIB='2.0.3'"
|
||||
php: '8.0'
|
||||
- env: "PHPSECLIB='2.0.4'"
|
||||
php: '8.0'
|
||||
- env: "PHPSECLIB='2.0.5'"
|
||||
php: '8.0'
|
||||
- env: "PHPSECLIB='2.0.6'"
|
||||
php: '8.0'
|
||||
fast_finish: true
|
||||
php:
|
||||
- '7.3'
|
||||
- '7.4'
|
||||
- '8.0'
|
||||
@@ -0,0 +1,2 @@
|
||||
* Arto Bendiken <arto.bendiken@gmail.com>
|
||||
* Stephen Paul Weber <singpolyma@singpolyma.net>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
README.md
|
||||
@@ -0,0 +1,73 @@
|
||||
[](https://travis-ci.org/singpolyma/openpgp-php)
|
||||
|
||||
OpenPGP.php: OpenPGP for PHP
|
||||
============================
|
||||
|
||||
This is a pure-PHP implementation of the OpenPGP Message Format (RFC 4880).
|
||||
|
||||
* <https://github.com/singpolyma/openpgp-php>
|
||||
|
||||
About OpenPGP
|
||||
-------------
|
||||
|
||||
OpenPGP is the most widely-used e-mail encryption standard in the world. It
|
||||
is defined by the OpenPGP Working Group of the Internet Engineering Task
|
||||
Force (IETF) Proposed Standard RFC 4880. The OpenPGP standard was originally
|
||||
derived from PGP (Pretty Good Privacy), first created by Phil Zimmermann in
|
||||
1991.
|
||||
|
||||
* <https://tools.ietf.org/html/rfc4880>
|
||||
* <https://www.openpgp.org/>
|
||||
|
||||
Features
|
||||
--------
|
||||
|
||||
* Encodes and decodes ASCII-armored OpenPGP messages.
|
||||
* Parses OpenPGP messages into their constituent packets.
|
||||
* Supports both old-format (PGP 2.6.x) and new-format (RFC 4880) packets.
|
||||
* Helper class for verifying, signing, encrypting, and decrypting messages <http://phpseclib.sourceforge.net>
|
||||
* Helper class for encrypting and decrypting messages and keys using <http://phpseclib.sourceforge.net>
|
||||
* openssl or mcrypt required for CAST5 encryption and decryption
|
||||
|
||||
Bugs, Feature Requests, Patches
|
||||
-------------------------------
|
||||
|
||||
This project is primarily maintained by a single volunteer with many other
|
||||
things vying for their attention, please be patient.
|
||||
|
||||
Bugs, feature request, pull requests, patches, and general discussion may
|
||||
be submitted publicly via email to: dev@singpolyma.net
|
||||
|
||||
Github users may alternately submit on the web there.
|
||||
|
||||
Users
|
||||
-----
|
||||
|
||||
OpenPGP.php is currently being used in the following projects:
|
||||
|
||||
* <https://wordpress.org/plugins/wp-pgp-encrypted-emails/>
|
||||
* [Passbolt API](https://github.com/passbolt/passbolt_api)
|
||||
|
||||
Download
|
||||
--------
|
||||
|
||||
To get a local working copy of the development repository, do:
|
||||
|
||||
git clone https://github.com/singpolyma/openpgp-php.git
|
||||
|
||||
Alternatively, you can download the latest development version as a tarball
|
||||
as follows:
|
||||
|
||||
wget https://github.com/singpolyma/openpgp-php/tarball/master
|
||||
|
||||
Authors
|
||||
-------
|
||||
|
||||
* [Arto Bendiken](mailto:arto.bendiken@gmail.com) (Original author) - <http://ar.to/>
|
||||
* [Stephen Paul Weber](mailto:singpolyma@singpolyma.net) (Maintainer) - <https://singpolyma.net/>
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
OpenPGP.php is free and unencumbered public domain software. For more
|
||||
information, see <https://unlicense.org/> or the accompanying UNLICENSE file.
|
||||
@@ -0,0 +1,24 @@
|
||||
This is free and unencumbered software released into the public domain.
|
||||
|
||||
Anyone is free to copy, modify, publish, use, compile, sell, or
|
||||
distribute this software, either in source code form or as a compiled
|
||||
binary, for any purpose, commercial or non-commercial, and by any
|
||||
means.
|
||||
|
||||
In jurisdictions that recognize copyright laws, the author or authors
|
||||
of this software dedicate any and all copyright interest in the
|
||||
software to the public domain. We make this dedication for the benefit
|
||||
of the public at large and to the detriment of our heirs and
|
||||
successors. We intend this dedication to be an overt act of
|
||||
relinquishment in perpetuity of all present and future rights to this
|
||||
software under copyright law.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
|
||||
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
|
||||
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
|
||||
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
For more information, please refer to <http://unlicense.org/>
|
||||
@@ -0,0 +1 @@
|
||||
0.3.0
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"name": "singpolyma/openpgp-php",
|
||||
"description": "Pure-PHP implementation of the OpenPGP Message Format (RFC 4880)",
|
||||
"license": "Unlicense",
|
||||
"authors": [
|
||||
{
|
||||
"name": "Arto Bendiken",
|
||||
"email": "arto.bendiken@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Stephen Paul Weber",
|
||||
"email": "singpolyma@singpolyma.net"
|
||||
}
|
||||
],
|
||||
"require": {
|
||||
"php": "^5.6 || ^7.0 || ^8.0",
|
||||
"phpseclib/phpseclib": "^3.0.14"
|
||||
},
|
||||
"require-dev": {
|
||||
"phpunit/phpunit": "^9.0"
|
||||
},
|
||||
"suggest": {
|
||||
"ext-mcrypt": "required if you use encryption cast5",
|
||||
"ext-openssl": "required if you use encryption cast5"
|
||||
},
|
||||
"autoload": {
|
||||
"classmap": ["lib/"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
OpenPGP.php Examples
|
||||
====================
|
||||
|
||||
The scripts in this folder show how to use this library to perform various tasks
|
||||
such as [generating a new key](keygen.php), [signing a message](sign.php), and
|
||||
[verifying a message](verify.php) that has been signed.
|
||||
|
||||
To use these examples, make sure [`phpseclib`](http://phpseclib.sourceforge.net/) is available. You can install it
|
||||
using [Composer](https://getcomposer.org/):
|
||||
|
||||
```sh
|
||||
git clone https://github.com/singpolyma/openpgp-php.git # Clone the repository.
|
||||
cd openpgp-php
|
||||
composer install # Use Composer to install the requirements.
|
||||
```
|
||||
|
||||
Once Composer has installed the requirements, run the examples using PHP:
|
||||
|
||||
```sh
|
||||
# Generate a new OpenPGP key; see the `keygen.php` file for parameters.
|
||||
php ./examples/keygen.php > mykey.gpg
|
||||
```
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
|
||||
$recipientPublicKey = OpenPGP_Message::parse(OpenPGP::unarmor(file_get_contents('public.asc'), 'PGP PUBLIC KEY BLOCK'));
|
||||
|
||||
$encryptedPrivateKey = OpenPGP_Message::parse(OpenPGP::unarmor(file_get_contents('sekret.asc'), 'PGP PRIVATE KEY BLOCK'));
|
||||
$privateKeyPassphrase = 'test';
|
||||
$key = OpenPGP_Crypt_Symmetric::decryptSecretKey($privateKeyPassphrase, $encryptedPrivateKey[0]);
|
||||
|
||||
$signer = new OpenPGP_Crypt_RSA($key);
|
||||
$data = new OpenPGP_LiteralDataPacket("some text\n", ['format' => 'u']);
|
||||
$signed = $signer->sign($data);
|
||||
|
||||
$compressed = new OpenPGP_CompressedDataPacket($signed);
|
||||
$encrypted = OpenPGP_Crypt_Symmetric::encrypt([$recipientPublicKey, $key], new OpenPGP_Message([$compressed]));
|
||||
|
||||
echo OpenPGP::enarmor($encrypted->to_bytes(), 'PGP MESSAGE');
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
|
||||
/* Parse secret key from STDIN, the key must not be password protected */
|
||||
$wkey = OpenPGP_Message::parse(file_get_contents('php://stdin'));
|
||||
$wkey = $wkey[0];
|
||||
|
||||
$string = "This\nis\na\ntest.";
|
||||
|
||||
/* Create a new literal data packet */
|
||||
$data = new OpenPGP_LiteralDataPacket($string, array('format' => 'u', 'filename' => 'stuff.txt'));
|
||||
$data->normalize(true); // Clearsign-style normalization of the LiteralDataPacket
|
||||
|
||||
/* Create a signer from the key */
|
||||
$sign = new OpenPGP_Crypt_RSA($wkey);
|
||||
|
||||
/* The message is the signed data packet */
|
||||
$m = $sign->sign($data);
|
||||
|
||||
/* Generate clearsigned data */
|
||||
$packets = $m->signatures()[0];
|
||||
echo "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\n";
|
||||
// Output normalised data. You could convert line endings here
|
||||
// without breaking the signature, but do not add any
|
||||
// trailing whitespace to lines.
|
||||
echo preg_replace("/^-/", "- -", $packets[0]->data)."\n";
|
||||
echo OpenPGP::enarmor($packets[1][0]->to_bytes(), "PGP SIGNATURE");
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
// USAGE: php examples/deASCIIdeCrypt.php secretkey.asc password message.asc
|
||||
// This will fail if the algo on key or message is not 3DES or AES
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_symmetric.php';
|
||||
|
||||
$keyASCII = file_get_contents($argv[1]);
|
||||
$msgASCII = file_get_contents($argv[3]);
|
||||
|
||||
$keyEncrypted = OpenPGP_Message::parse(OpenPGP::unarmor($keyASCII, 'PGP PRIVATE KEY BLOCK'));
|
||||
|
||||
// Try each secret key packet
|
||||
foreach($keyEncrypted as $p) {
|
||||
if(!($p instanceof OpenPGP_SecretKeyPacket)) continue;
|
||||
|
||||
$key = OpenPGP_Crypt_Symmetric::decryptSecretKey($argv[2], $p);
|
||||
|
||||
$msg = OpenPGP_Message::parse(OpenPGP::unarmor($msgASCII, 'PGP MESSAGE'));
|
||||
|
||||
$decryptor = new OpenPGP_Crypt_RSA($key);
|
||||
$decrypted = $decryptor->decrypt($msg);
|
||||
|
||||
var_dump($decrypted);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_symmetric.php';
|
||||
|
||||
$key = OpenPGP_Message::parse(file_get_contents(dirname(__FILE__) . '/../tests/data/helloKey.gpg'));
|
||||
$data = new OpenPGP_LiteralDataPacket('This is text.', array('format' => 'u', 'filename' => 'stuff.txt'));
|
||||
$encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message(array($data)));
|
||||
|
||||
// Now decrypt it with the same key
|
||||
$decryptor = new OpenPGP_Crypt_RSA($key);
|
||||
$decrypted = $decryptor->decrypt($encrypted);
|
||||
|
||||
var_dump($decrypted);
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use phpseclib3\Crypt\RSA;
|
||||
use phpseclib3\Crypt\RSA\Formats\Keys\PKCS1;
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
|
||||
$privateKey = RSA::createKey(512);
|
||||
$publickey = $privateKey->getPublicKey();
|
||||
|
||||
$privateKeyComponents = PKCS1::load($privateKey->toString('PKCS1'));
|
||||
|
||||
$nkey = new OpenPGP_SecretKeyPacket(array(
|
||||
'n' => $privateKeyComponents["modulus"]->toBytes(),
|
||||
'e' => $privateKeyComponents["publicExponent"]->toBytes(),
|
||||
'd' => $privateKeyComponents["privateExponent"]->toBytes(),
|
||||
'p' => $privateKeyComponents["primes"][1]->toBytes(),
|
||||
'q' => $privateKeyComponents["primes"][2]->toBytes(),
|
||||
'u' => $privateKeyComponents["coefficients"][2]->toBytes()
|
||||
));
|
||||
|
||||
$uid = new OpenPGP_UserIDPacket('Test <test@example.com>');
|
||||
|
||||
$wkey = new OpenPGP_Crypt_RSA($nkey);
|
||||
$m = $wkey->sign_key_userid(array($nkey, $uid));
|
||||
|
||||
// Serialize private key
|
||||
print $m->to_bytes();
|
||||
|
||||
// Serialize public key message
|
||||
$pubm = clone($m);
|
||||
$pubm[0] = new OpenPGP_PublicKeyPacket($pubm[0]);
|
||||
|
||||
$public_bytes = $pubm->to_bytes();
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use phpseclib3\Crypt\RSA;
|
||||
use phpseclib3\Crypt\RSA\Formats\Keys\PKCS1;
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_symmetric.php';
|
||||
|
||||
$privateKey = RSA::createKey(512);
|
||||
$publickey = $privateKey->getPublicKey();
|
||||
|
||||
$privateKeyComponents = PKCS1::load($privateKey->toString('PKCS1'));
|
||||
|
||||
$nkey = new OpenPGP_SecretKeyPacket(array(
|
||||
'n' => $privateKeyComponents["modulus"]->toBytes(),
|
||||
'e' => $privateKeyComponents["publicExponent"]->toBytes(),
|
||||
'd' => $privateKeyComponents["privateExponent"]->toBytes(),
|
||||
'p' => $privateKeyComponents["primes"][1]->toBytes(),
|
||||
'q' => $privateKeyComponents["primes"][2]->toBytes(),
|
||||
'u' => $privateKeyComponents["coefficients"][2]->toBytes()
|
||||
));
|
||||
|
||||
$uid = new OpenPGP_UserIDPacket('Test <test@example.com>');
|
||||
|
||||
$wkey = new OpenPGP_Crypt_RSA($nkey);
|
||||
$m = $wkey->sign_key_userid(array($nkey, $uid));
|
||||
$m[0] = OpenPGP_Crypt_Symmetric::encryptSecretKey("password", $nkey);
|
||||
|
||||
// Serialize encrypted private key
|
||||
print $m->to_bytes();
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
use phpseclib3\Crypt\RSA;
|
||||
use phpseclib3\Crypt\RSA\Formats\Keys\PKCS1;
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
|
||||
// Key length: 512, 1024, 2048, 3072, 4096
|
||||
$key_length = 512;
|
||||
|
||||
// Generate a master signing key
|
||||
$privateKey = RSA::createKey(512);
|
||||
$privateKeyComponents = PKCS1::load($privateKey->toString('PKCS1'));
|
||||
|
||||
$nkey = new OpenPGP_SecretKeyPacket(array(
|
||||
'n' => $privateKeyComponents["modulus"]->toBytes(),
|
||||
'e' => $privateKeyComponents["publicExponent"]->toBytes(),
|
||||
'd' => $privateKeyComponents["privateExponent"]->toBytes(),
|
||||
'p' => $privateKeyComponents["primes"][1]->toBytes(),
|
||||
'q' => $privateKeyComponents["primes"][2]->toBytes(),
|
||||
'u' => $privateKeyComponents["coefficients"][2]->toBytes()
|
||||
));
|
||||
|
||||
// Start assembling packets for our eventual OpenPGP_Message
|
||||
$packets = array($nkey);
|
||||
|
||||
$wkey = new OpenPGP_Crypt_RSA($nkey);
|
||||
$fingerprint = $wkey->key()->fingerprint;
|
||||
$key = $wkey->private_key();
|
||||
$key = $key->withHash('sha256');
|
||||
$keyid = substr($fingerprint, -16);
|
||||
|
||||
// Add multiple UID packets and signatures
|
||||
|
||||
$uids = array(
|
||||
new OpenPGP_UserIDPacket('Support', '', 'support@example.com'),
|
||||
new OpenPGP_UserIDPacket('Security', '', 'security@example.com'),
|
||||
);
|
||||
|
||||
foreach($uids as $uid) {
|
||||
// Append the UID packet
|
||||
$packets[] = $uid;
|
||||
|
||||
$sig = new OpenPGP_SignaturePacket(new OpenPGP_Message(array($nkey, $uid)), 'RSA', 'SHA256');
|
||||
$sig->signature_type = 0x13;
|
||||
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0x01 | 0x02)); // Certify + sign bits
|
||||
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket($keyid);
|
||||
$m = $wkey->sign_key_userid(array($nkey, $uid, $sig));
|
||||
|
||||
// Append the UID signature from the master key
|
||||
$packets[] = $m->packets[2];
|
||||
}
|
||||
|
||||
// Generate an encryption subkey
|
||||
|
||||
$rsa_subkey = RSA::createKey(512);
|
||||
$privateKeyComponents = PKCS1::load($rsa_subkey->toString('PKCS1'));
|
||||
|
||||
$subkey = new OpenPGP_SecretKeyPacket(array(
|
||||
'n' => $privateKeyComponents["modulus"]->toBytes(),
|
||||
'e' => $privateKeyComponents["publicExponent"]->toBytes(),
|
||||
'd' => $privateKeyComponents["privateExponent"]->toBytes(),
|
||||
'p' => $privateKeyComponents["primes"][2]->toBytes(),
|
||||
'q' => $privateKeyComponents["primes"][1]->toBytes(),
|
||||
'u' => $privateKeyComponents["coefficients"][2]->toBytes()
|
||||
));
|
||||
|
||||
// Append the encryption subkey
|
||||
$packets[] = $subkey;
|
||||
|
||||
$sub_wkey = new OpenPGP_Crypt_RSA($subkey);
|
||||
|
||||
/*
|
||||
* Sign the encryption subkey with the master key
|
||||
*
|
||||
* OpenPGP_SignaturePacket assumes any message starting with an
|
||||
* OpenPGP_PublicKeyPacket is followed by a OpenPGP_UserIDPacket. We need
|
||||
* to pass `null` in the constructor and generate the `->data` ourselves.
|
||||
*/
|
||||
$sub_sig = new OpenPGP_SignaturePacket(null, 'RSA', 'SHA256');
|
||||
$sub_sig->signature_type = 0x18;
|
||||
$sub_sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_SignatureCreationTimePacket(time());
|
||||
$sub_sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0x0C)); // Encrypt bits
|
||||
$sub_sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket($keyid);
|
||||
$sub_sig->data = implode('', $nkey->fingerprint_material()) . implode('', $subkey->fingerprint_material());
|
||||
$sub_sig->sign_data(array('RSA' => array('SHA256' => function($data) use($key) {return array($key->sign($data));})));
|
||||
|
||||
// Append the subkey signature
|
||||
$packets[] = $sub_sig;
|
||||
|
||||
// Build the OpenPGP_Message for the secret key from our packets
|
||||
$m = new OpenPGP_Message($packets);
|
||||
|
||||
// Serialize the private key
|
||||
print $m->to_bytes();
|
||||
|
||||
// Clone a public key message from the secret key
|
||||
$pubm = clone($m);
|
||||
|
||||
// Convert the private key packets to public so we only export public data
|
||||
// (n+e in RSA)
|
||||
foreach($pubm as $idx => $p) {
|
||||
if($p instanceof OpenPGP_SecretSubkeyPacket) {
|
||||
$pubm[$idx] = new OpenPGP_PublicSubkeyPacket($p);
|
||||
} else if($p instanceof OpenPGP_SecretKeyPacket) {
|
||||
$pubm[$idx] = new OpenPGP_PublicKeyPacket($p);
|
||||
}
|
||||
}
|
||||
|
||||
// Serialize the public key
|
||||
$public_bytes = $pubm->to_bytes();
|
||||
|
||||
// Note: If using PHP 7.4 CLI, disable deprecated warnings:
|
||||
// php -d error_reporting="E_ALL & ~E_DEPRECATED" examples/keygenSubkeys.php > mykey.gpg
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
|
||||
/* Parse secret key from STDIN, the key must not be password protected */
|
||||
$wkey = OpenPGP_Message::parse(file_get_contents('php://stdin'));
|
||||
$wkey = $wkey[0];
|
||||
|
||||
/* Create a new literal data packet */
|
||||
$data = new OpenPGP_LiteralDataPacket('This is text.', array('format' => 'u', 'filename' => 'stuff.txt'));
|
||||
|
||||
/* Create a signer from the key */
|
||||
$sign = new OpenPGP_Crypt_RSA($wkey);
|
||||
|
||||
/* The message is the signed data packet */
|
||||
$m = $sign->sign($data);
|
||||
|
||||
/* Output the raw message bytes to STDOUT */
|
||||
echo $m->to_bytes();
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
@include_once dirname(__FILE__).'/../vendor/autoload.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp.php';
|
||||
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
|
||||
|
||||
/* Parse public key from STDIN */
|
||||
$wkey = OpenPGP_Message::parse(file_get_contents('php://stdin'));
|
||||
|
||||
/* Parse signed message from file named "t" */
|
||||
$m = OpenPGP_Message::parse(file_get_contents('t'));
|
||||
|
||||
/* Create a verifier for the key */
|
||||
$verify = new OpenPGP_Crypt_RSA($wkey);
|
||||
|
||||
/* Dump verification information to STDOUT */
|
||||
var_dump($verify->verify($m));
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,301 @@
|
||||
<?php
|
||||
// This is free and unencumbered software released into the public domain.
|
||||
/**
|
||||
* OpenPGP_Crypt_RSA.php is a wrapper for using the classes from OpenPGP.php with Crypt_RSA
|
||||
*
|
||||
* @package OpenPGP
|
||||
*/
|
||||
|
||||
// From http://phpseclib.sourceforge.net/
|
||||
use phpseclib3\Crypt\PublicKeyLoader;
|
||||
use phpseclib3\Crypt\RSA as Crypt_RSA;
|
||||
use phpseclib3\Crypt\RSA\PublicKey;
|
||||
use phpseclib3\Math\BigInteger as Math_BigInteger;
|
||||
|
||||
define('CRYPT_RSA_ENCRYPTION_PKCS1', Crypt_RSA::ENCRYPTION_PKCS1);
|
||||
define('CRYPT_RSA_SIGNATURE_PKCS1', Crypt_RSA::SIGNATURE_PKCS1);
|
||||
exit ;
|
||||
|
||||
echo dirname(__FILE__).'/openpgp.php' ;
|
||||
exit ;
|
||||
|
||||
require_once dirname(__FILE__).'/openpgp.php';
|
||||
@include_once dirname(__FILE__).'/openpgp_crypt_symmetric.php'; /* For encrypt/decrypt */
|
||||
|
||||
class OpenPGP_Crypt_RSA {
|
||||
protected $key, $message;
|
||||
|
||||
// Construct a wrapper object from a key or a message packet
|
||||
function __construct($packet) {
|
||||
if(!is_object($packet)) $packet = OpenPGP_Message::parse($packet);
|
||||
if($packet instanceof OpenPGP_PublicKeyPacket || $packet[0] instanceof OpenPGP_PublicKeyPacket) { // If it's a key (other keys are subclasses of this one)
|
||||
$this->key = $packet;
|
||||
} else {
|
||||
$this->message = $packet;
|
||||
}
|
||||
}
|
||||
|
||||
function key($keyid=NULL) {
|
||||
if(!$this->key) return NULL; // No key
|
||||
if($this->key instanceof OpenPGP_Message) {
|
||||
foreach($this->key as $p) {
|
||||
if($p instanceof OpenPGP_PublicKeyPacket) {
|
||||
if(!$keyid || strtoupper(substr($p->fingerprint, strlen($keyid)*-1)) == strtoupper($keyid)) return $p;
|
||||
}
|
||||
}
|
||||
}
|
||||
return $this->key;
|
||||
}
|
||||
|
||||
// Get Crypt_RSA for the public key
|
||||
function public_key($keyid=NULL) {
|
||||
return self::convert_public_key($this->key($keyid));
|
||||
}
|
||||
|
||||
// Get Crypt_RSA for the private key
|
||||
function private_key($keyid=NULL) {
|
||||
return self::convert_private_key($this->key($keyid));
|
||||
}
|
||||
|
||||
// Pass a message to verify with this key, or a key (OpenPGP or Crypt_RSA) to check this message with
|
||||
// Second optional parameter to specify which signature to verify (if there is more than one)
|
||||
function verify($packet) {
|
||||
$self = $this; // For old PHP
|
||||
if(!is_object($packet)) $packet = OpenPGP_Message::parse($packet);
|
||||
if(!$this->message) {
|
||||
$m = $packet;
|
||||
$verifier = function($m, $s) use($self) {
|
||||
$key = $self->public_key($s->issuer());
|
||||
if(!$key) return false;
|
||||
$key = $key->withHash(strtolower($s->hash_algorithm_name()));
|
||||
return $key->verify($m, reset($s->data));
|
||||
};
|
||||
} else {
|
||||
if(!($packet instanceof Crypt_RSA)) {
|
||||
$packet = new self($packet);
|
||||
}
|
||||
|
||||
$m = $this->message;
|
||||
$verifier = function($m, $s) use($self, $packet) {
|
||||
if(!($packet instanceof Crypt_RSA)) {
|
||||
$key = $packet->public_key($s->issuer());
|
||||
}
|
||||
if(!$key) return false;
|
||||
$key = $key->withHash(strtolower($s->hash_algorithm_name()));
|
||||
return $key->verify($m, reset($s->data));
|
||||
};
|
||||
}
|
||||
|
||||
return $m->verified_signatures(array('RSA' => array(
|
||||
'MD5' => $verifier,
|
||||
'SHA1' => $verifier,
|
||||
'SHA224' => $verifier,
|
||||
'SHA256' => $verifier,
|
||||
'SHA384' => $verifier,
|
||||
'SHA512' => $verifier
|
||||
)));
|
||||
}
|
||||
|
||||
// Pass a message to sign with this key, or a secret key to sign this message with
|
||||
// Second parameter is hash algorithm to use (default SHA256)
|
||||
// Third parameter is the 16-digit key ID to use... defaults to the key id in the key packet
|
||||
function sign($packet, $hash='SHA256', $keyid=NULL) {
|
||||
if(!is_object($packet)) {
|
||||
if($this->key) {
|
||||
$packet = new OpenPGP_LiteralDataPacket($packet);
|
||||
} else {
|
||||
$packet = OpenPGP_Message::parse($packet);
|
||||
}
|
||||
}
|
||||
|
||||
if($packet instanceof OpenPGP_SecretKeyPacket || $packet instanceof Crypt_RSA
|
||||
|| ($packet instanceof ArrayAccess && $packet[0] instanceof OpenPGP_SecretKeyPacket)) {
|
||||
$key = $packet;
|
||||
$message = $this->message;
|
||||
} else {
|
||||
$key = $this->key;
|
||||
$message = $packet;
|
||||
}
|
||||
|
||||
if(!$key || !$message) return NULL; // Missing some data
|
||||
|
||||
if($message instanceof OpenPGP_Message) {
|
||||
$sign = $message->signatures();
|
||||
$message = $sign[0][0];
|
||||
}
|
||||
|
||||
if(!($key instanceof Crypt_RSA)) {
|
||||
$key = new self($key);
|
||||
if(!$keyid) $keyid = substr($key->key()->fingerprint, -16, 16);
|
||||
$key = $key->private_key($keyid);
|
||||
}
|
||||
$key = $key->withHash(strtolower($hash));
|
||||
|
||||
$sig = new OpenPGP_SignaturePacket($message, 'RSA', strtoupper($hash));
|
||||
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket($keyid);
|
||||
$sig->sign_data(array('RSA' => array($hash => function($data) use($key) {return array($key->sign($data));})));
|
||||
|
||||
return new OpenPGP_Message(array($sig, $message));
|
||||
}
|
||||
|
||||
/** Pass a message with a key and userid packet to sign */
|
||||
// TODO: merge this with the normal sign function
|
||||
function sign_key_userid($packet, $hash='SHA256', $keyid=NULL) {
|
||||
if(is_array($packet)) {
|
||||
$packet = new OpenPGP_Message($packet);
|
||||
} else if(!is_object($packet)) {
|
||||
$packet = OpenPGP_Message::parse($packet);
|
||||
}
|
||||
|
||||
$key = $this->private_key($keyid);
|
||||
if(!$key || !$packet) return NULL; // Missing some data
|
||||
|
||||
if(!$keyid) $keyid = substr($this->key->fingerprint, -16);
|
||||
$key = $key->withHash(strtolower($hash));
|
||||
|
||||
$sig = NULL;
|
||||
foreach($packet as $p) {
|
||||
if($p instanceof OpenPGP_SignaturePacket) $sig = $p;
|
||||
}
|
||||
if(!$sig) {
|
||||
$sig = new OpenPGP_SignaturePacket($packet, 'RSA', strtoupper($hash));
|
||||
$sig->signature_type = 0x13;
|
||||
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0x01 | 0x02));
|
||||
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket($keyid);
|
||||
$packet[] = $sig;
|
||||
}
|
||||
|
||||
$sig->sign_data(array('RSA' => array($hash => function($data) use($key) {return array($key->sign($data));})));
|
||||
|
||||
return $packet;
|
||||
}
|
||||
|
||||
function decrypt($packet) {
|
||||
if(!is_object($packet)) $packet = OpenPGP_Message::parse($packet);
|
||||
|
||||
if($packet instanceof OpenPGP_SecretKeyPacket || $packet instanceof Crypt_RSA
|
||||
|| ($packet instanceof ArrayAccess && $packet[0] instanceof OpenPGP_SecretKeyPacket)) {
|
||||
$keys = $packet;
|
||||
$message = $this->message;
|
||||
} else {
|
||||
$keys = $this->key;
|
||||
$message = $packet;
|
||||
}
|
||||
|
||||
if(!$keys || !$message) return NULL; // Missing some data
|
||||
|
||||
if(!($keys instanceof Crypt_RSA)) {
|
||||
$keys = new self($keys);
|
||||
}
|
||||
|
||||
$session_key = NULL;
|
||||
foreach($message as $p) {
|
||||
if($p instanceof OpenPGP_AsymmetricSessionKeyPacket) {
|
||||
$session_key = $p;
|
||||
if($keys instanceof Crypt_RSA) {
|
||||
$sk = self::try_decrypt_session($keys, substr($p->encrypted_data, 2));
|
||||
} else if(strlen(str_replace('0', '', $p->keyid)) < 1) {
|
||||
foreach($keys->key as $k) {
|
||||
$sk = self::try_decrypt_session(self::convert_private_key($k), substr($p->encrypted_data, 2));
|
||||
if($sk) break;
|
||||
}
|
||||
} else {
|
||||
$key = $keys->private_key($p->keyid);
|
||||
$sk = self::try_decrypt_session($key, substr($p->encrypted_data, 2));
|
||||
}
|
||||
|
||||
if(!$sk) continue;
|
||||
|
||||
$r = OpenPGP_Crypt_Symmetric::decryptPacket(OpenPGP_Crypt_Symmetric::getEncryptedData($message), $sk[0], $sk[1]);
|
||||
if($r) return $r;
|
||||
}
|
||||
}
|
||||
|
||||
if (!$session_key) throw new Exception("Not an asymmetrically encrypted message");
|
||||
|
||||
return NULL; /* Failed */
|
||||
}
|
||||
|
||||
static function try_decrypt_session($key, $edata) {
|
||||
$key = $key->withPadding(CRYPT_RSA_ENCRYPTION_PKCS1 | CRYPT_RSA_SIGNATURE_PKCS1);
|
||||
try {
|
||||
$data = $key->decrypt($edata);
|
||||
} catch (\RuntimeException $e) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if(!$data) return NULL;
|
||||
$sk = substr($data, 1, strlen($data)-3);
|
||||
$chk = unpack('n', substr($data, -2));
|
||||
$chk = reset($chk);
|
||||
|
||||
$sk_chk = 0;
|
||||
for($i = 0; $i < strlen($sk); $i++) {
|
||||
$sk_chk = ($sk_chk + ord($sk[$i])) % 65536;
|
||||
}
|
||||
|
||||
if($sk_chk != $chk) return NULL;
|
||||
return array(ord($data[0]), $sk);
|
||||
}
|
||||
|
||||
static function crypt_rsa_key($mod, $exp, $hash='SHA256') {
|
||||
return Crypt_RSA::loadPublicKey([
|
||||
'e' => new Math_BigInteger($exp, 256),
|
||||
'n' => new Math_BigInteger($mod, 256),
|
||||
])
|
||||
->withPadding(CRYPT_RSA_SIGNATURE_PKCS1 | CRYPT_RSA_ENCRYPTION_PKCS1)
|
||||
->withHash(strtolower($hash));
|
||||
}
|
||||
|
||||
static function convert_key($packet, $private=false) {
|
||||
if(!is_object($packet)) $packet = OpenPGP_Message::parse($packet);
|
||||
if($packet instanceof OpenPGP_Message) $packet = $packet[0];
|
||||
|
||||
$exp = $packet->key['e'];
|
||||
if($private) $exp = $packet->key['d'];
|
||||
if(!$exp) return NULL; // Packet doesn't have needed data
|
||||
|
||||
/**
|
||||
* @see https://github.com/phpseclib/phpseclib/issues/1113
|
||||
* Primes and coefficients now use BigIntegers.
|
||||
**/
|
||||
|
||||
if($private) {
|
||||
// Invert p and q to make u work out as q'
|
||||
$rawKey = [
|
||||
'e' => new Math_BigInteger($packet->key['e'], 256),
|
||||
'n' => new Math_BigInteger($packet->key['n'], 256),
|
||||
'd' => new Math_BigInteger($packet->key['d'], 256),
|
||||
'q' => new Math_BigInteger($packet->key['p'], 256),
|
||||
'p' => new Math_BigInteger($packet->key['q'], 256),
|
||||
];
|
||||
if (array_key_exists('u', $packet->key)) {
|
||||
// possible keys for 'u': https://github.com/phpseclib/phpseclib/blob/master/phpseclib/Crypt/RSA/Formats/Keys/Raw.php#L108
|
||||
$rawKey['inerseq'] = new Math_BigInteger($packet->key['u'], 256);
|
||||
}
|
||||
|
||||
return publickeyloader::loadPrivateKey($rawKey)
|
||||
->withPadding(CRYPT_RSA_SIGNATURE_PKCS1 | CRYPT_RSA_ENCRYPTION_PKCS1)
|
||||
->withHash('sha256');
|
||||
} else {
|
||||
|
||||
return publickeyloader::loadPublicKey([
|
||||
'e' => new Math_BigInteger($packet->key['e'], 256),
|
||||
'n' => new Math_BigInteger($packet->key['n'], 256),
|
||||
])
|
||||
->withPadding(CRYPT_RSA_SIGNATURE_PKCS1 | CRYPT_RSA_ENCRYPTION_PKCS1)
|
||||
->withHash('sha256');
|
||||
}
|
||||
}
|
||||
|
||||
static function convert_public_key($packet) {
|
||||
return self::convert_key($packet, false);
|
||||
}
|
||||
|
||||
static function convert_private_key($packet) {
|
||||
return self::convert_key($packet, true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -0,0 +1,242 @@
|
||||
<?php
|
||||
|
||||
use phpseclib3\Crypt\AES as Crypt_AES;
|
||||
use phpseclib3\Crypt\Blowfish as Crypt_Blowfish;
|
||||
use phpseclib3\Crypt\TripleDES as Crypt_TripleDES;
|
||||
use phpseclib3\Crypt\Twofish as Crypt_Twofish;
|
||||
use phpseclib3\Crypt\Random;
|
||||
|
||||
require_once dirname(__FILE__).'/openpgp.php';
|
||||
@include_once dirname(__FILE__).'/openpgp_crypt_rsa.php';
|
||||
@include_once dirname(__FILE__).'/openpgp_mcrypt_wrapper.php';
|
||||
@include_once dirname(__FILE__).'/openpgp_openssl_wrapper.php';
|
||||
|
||||
class OpenPGP_Crypt_Symmetric {
|
||||
public static function encrypt($passphrases_and_keys, $message, $symmetric_algorithm=9) {
|
||||
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($symmetric_algorithm);
|
||||
if(!$cipher) throw new Exception("Unsupported cipher");
|
||||
$prefix = Random::string($key_block_bytes);
|
||||
$prefix .= substr($prefix, -2);
|
||||
|
||||
$key = Random::string($key_bytes);
|
||||
$cipher->setKey($key);
|
||||
|
||||
$to_encrypt = $prefix . $message->to_bytes();
|
||||
$mdc = new OpenPGP_ModificationDetectionCodePacket(hash('sha1', $to_encrypt . "\xD3\x14", true));
|
||||
$to_encrypt .= $mdc->to_bytes();
|
||||
$encrypted = array(new OpenPGP_IntegrityProtectedDataPacket($cipher->encrypt($to_encrypt)));
|
||||
|
||||
if(!is_array($passphrases_and_keys) && !($passphrases_and_keys instanceof IteratorAggregate)) {
|
||||
$passphrases_and_keys = (array)$passphrases_and_keys;
|
||||
}
|
||||
|
||||
foreach($passphrases_and_keys as $pass) {
|
||||
if($pass instanceof OpenPGP_PublicKeyPacket) {
|
||||
if(!in_array($pass->algorithm, array(1,2,3))) throw new Exception("Only RSA keys are supported.");
|
||||
$crypt_rsa = new OpenPGP_Crypt_RSA($pass);
|
||||
$rsa = $crypt_rsa->public_key()->withPadding(CRYPT_RSA_ENCRYPTION_PKCS1 | CRYPT_RSA_SIGNATURE_PKCS1);
|
||||
$esk = $rsa->encrypt(chr($symmetric_algorithm) . $key . pack('n', self::checksum($key)));
|
||||
$esk = pack('n', OpenPGP::bitlength($esk)) . $esk;
|
||||
array_unshift($encrypted, new OpenPGP_AsymmetricSessionKeyPacket($pass->algorithm, $pass->fingerprint(), $esk));
|
||||
} else if(is_string($pass)) {
|
||||
$s2k = new OpenPGP_S2K(Random::string(8));
|
||||
$cipher->setKey($s2k->make_key($pass, $key_bytes));
|
||||
$esk = $cipher->encrypt(chr($symmetric_algorithm) . $key);
|
||||
array_unshift($encrypted, new OpenPGP_SymmetricSessionKeyPacket($s2k, $esk, $symmetric_algorithm));
|
||||
}
|
||||
}
|
||||
|
||||
return new OpenPGP_Message($encrypted);
|
||||
}
|
||||
|
||||
public static function decryptSymmetric($pass, $m) {
|
||||
$epacket = self::getEncryptedData($m);
|
||||
|
||||
foreach($m as $p) {
|
||||
if($p instanceof OpenPGP_SymmetricSessionKeyPacket) {
|
||||
if(strlen($p->encrypted_data) > 0) {
|
||||
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($p->symmetric_algorithm);
|
||||
if(!$cipher) continue;
|
||||
$cipher->setKey($p->s2k->make_key($pass, $key_bytes));
|
||||
|
||||
$padAmount = $key_block_bytes - (strlen($p->encrypted_data) % $key_block_bytes);
|
||||
$data = substr($cipher->decrypt($p->encrypted_data . str_repeat("\0", $padAmount)), 0, strlen($p->encrypted_data));
|
||||
$decrypted = self::decryptPacket($epacket, ord($data[0]), substr($data, 1));
|
||||
} else {
|
||||
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($p->symmetric_algorithm);
|
||||
$decrypted = self::decryptPacket($epacket, $p->symmetric_algorithm, $p->s2k->make_key($pass, $key_bytes));
|
||||
}
|
||||
|
||||
if($decrypted) return $decrypted;
|
||||
}
|
||||
}
|
||||
|
||||
return NULL; /* If we get here, we failed */
|
||||
}
|
||||
|
||||
public static function encryptSecretKey($pass, $packet, $symmetric_algorithm=9) {
|
||||
$packet = clone $packet; // Do not mutate original
|
||||
$packet->s2k_useage = 254;
|
||||
$packet->symmetric_algorithm = $symmetric_algorithm;
|
||||
|
||||
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($packet->symmetric_algorithm);
|
||||
if(!$cipher) throw new Exception("Unsupported cipher");
|
||||
|
||||
$material = '';
|
||||
foreach(OpenPGP_SecretKeyPacket::$secret_key_fields[$packet->algorithm] as $field) {
|
||||
$f = $packet->key[$field];
|
||||
$material .= pack('n', OpenPGP::bitlength($f)) . $f;
|
||||
unset($packet->key[$field]);
|
||||
}
|
||||
$material .= hash('sha1', $material, true);
|
||||
|
||||
$iv = Random::string($key_block_bytes);
|
||||
if(!$packet->s2k) $packet->s2k = new OpenPGP_S2K(Random::string(8));
|
||||
$cipher->setKey($packet->s2k->make_key($pass, $key_bytes));
|
||||
$cipher->setIV($iv);
|
||||
$packet->encrypted_data = $iv . $cipher->encrypt($material);
|
||||
|
||||
return $packet;
|
||||
}
|
||||
|
||||
public static function decryptSecretKey($pass, $packet) {
|
||||
$packet = clone $packet; // Do not mutate orinigal
|
||||
|
||||
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($packet->symmetric_algorithm);
|
||||
if(!$cipher) throw new Exception("Unsupported cipher");
|
||||
$cipher->setKey($packet->s2k->make_key($pass, $key_bytes));
|
||||
$cipher->setIV(substr($packet->encrypted_data, 0, $key_block_bytes));
|
||||
$material = $cipher->decrypt(substr($packet->encrypted_data, $key_block_bytes));
|
||||
|
||||
if($packet->s2k_useage == 254) {
|
||||
$chk = substr($material, -20);
|
||||
$material = substr($material, 0, -20);
|
||||
if($chk != hash('sha1', $material, true)) return NULL;
|
||||
} else {
|
||||
$chk = unpack('n', substr($material, -2));
|
||||
$chk = reset($chk);
|
||||
$material = substr($material, 0, -2);
|
||||
|
||||
$mkChk = self::checksum($material);
|
||||
if($chk != $mkChk) return NULL;
|
||||
}
|
||||
|
||||
$packet->s2k = NULL;
|
||||
$packet->s2k_useage = 0;
|
||||
$packet->symmetric_algorithm = 0;
|
||||
$packet->encrypted_data = NULL;
|
||||
$packet->input = $material;
|
||||
$packet->key_from_input();
|
||||
unset($packet->input);
|
||||
return $packet;
|
||||
}
|
||||
|
||||
public static function decryptPacket($epacket, $symmetric_algorithm, $key) {
|
||||
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($symmetric_algorithm);
|
||||
if(!$cipher) return NULL;
|
||||
$cipher->setKey($key);
|
||||
|
||||
if($epacket instanceof OpenPGP_IntegrityProtectedDataPacket) {
|
||||
$padAmount = $key_block_bytes - (strlen($epacket->data) % $key_block_bytes);
|
||||
$data = substr($cipher->decrypt($epacket->data . str_repeat("\0", $padAmount)), 0, strlen($epacket->data));
|
||||
$prefix = substr($data, 0, $key_block_bytes + 2);
|
||||
$mdc = substr(substr($data, -22, 22), 2);
|
||||
$data = substr($data, $key_block_bytes + 2, -22);
|
||||
|
||||
$mkMDC = hash("sha1", $prefix . $data . "\xD3\x14", true);
|
||||
if($mkMDC !== $mdc) return false;
|
||||
|
||||
try {
|
||||
$msg = OpenPGP_Message::parse($data);
|
||||
} catch (Exception $ex) { $msg = NULL; }
|
||||
if($msg) return $msg; /* Otherwise keep trying */
|
||||
} else {
|
||||
// No MDC mean decrypt with resync
|
||||
$iv = substr($epacket->data, 2, $key_block_bytes);
|
||||
$edata = substr($epacket->data, $key_block_bytes + 2);
|
||||
$padAmount = $key_block_bytes - (strlen($edata) % $key_block_bytes);
|
||||
|
||||
$cipher->setIV($iv);
|
||||
$data = substr($cipher->decrypt($edata . str_repeat("\0", $padAmount)), 0, strlen($edata));
|
||||
|
||||
try {
|
||||
$msg = OpenPGP_Message::parse($data);
|
||||
} catch (Exception $ex) { $msg = NULL; }
|
||||
if($msg) return $msg; /* Otherwise keep trying */
|
||||
}
|
||||
|
||||
return NULL; /* Failed */
|
||||
}
|
||||
|
||||
public static function getCipher($algo) {
|
||||
$cipher = NULL;
|
||||
|
||||
// https://datatracker.ietf.org/doc/html/rfc4880#section-13.9
|
||||
// " 1. The feedback register (FR) is set to the IV, which is all zeros."
|
||||
switch($algo) {
|
||||
case NULL:
|
||||
case 0:
|
||||
throw new Exception("Data is already unencrypted");
|
||||
case 2:
|
||||
$cipher = new Crypt_TripleDES('cfb');
|
||||
$cipher->setIV(str_repeat(pack('x'), 8));
|
||||
$key_bytes = 24;
|
||||
$key_block_bytes = 8;
|
||||
break;
|
||||
case 3:
|
||||
if(class_exists('OpenSSLWrapper')) {
|
||||
$cipher = new OpenSSLWrapper("CAST5-CFB");
|
||||
} else if(defined('MCRYPT_CAST_128')) {
|
||||
$cipher = new MCryptWrapper(MCRYPT_CAST_128);
|
||||
}
|
||||
break;
|
||||
case 4:
|
||||
$cipher = new Crypt_Blowfish('cfb');
|
||||
$cipher->setIV(str_repeat(pack('x'), 8));
|
||||
$key_bytes = 16;
|
||||
$key_block_bytes = 8;
|
||||
break;
|
||||
case 7:
|
||||
$cipher = new Crypt_AES('cfb');
|
||||
$cipher->setKeyLength(128);
|
||||
$cipher->setIV(str_repeat(pack('x'), 16));
|
||||
break;
|
||||
case 8:
|
||||
$cipher = new Crypt_AES('cfb');
|
||||
$cipher->setKeyLength(192);
|
||||
$cipher->setIV(str_repeat(pack('x'), 16));
|
||||
break;
|
||||
case 9:
|
||||
$cipher = new Crypt_AES('cfb');
|
||||
$cipher->setKeyLength(256);
|
||||
$cipher->setIV(str_repeat(pack('x'), 16));
|
||||
break;
|
||||
case 10:
|
||||
$cipher = new Crypt_Twofish('cfb');
|
||||
$cipher->setIV(str_repeat(pack('x'), 16));
|
||||
$key_bytes = 32;
|
||||
break;
|
||||
}
|
||||
if(!$cipher) return array(NULL, NULL, NULL); // Unsupported cipher
|
||||
|
||||
|
||||
if(!isset($key_bytes)) $key_bytes = $cipher->getKeyLength() >> 3;
|
||||
if(!isset($key_block_bytes)) $key_block_bytes = $cipher->getBlockLengthInBytes();
|
||||
return array($cipher, $key_bytes, $key_block_bytes);
|
||||
}
|
||||
|
||||
public static function getEncryptedData($m) {
|
||||
foreach($m as $p) {
|
||||
if($p instanceof OpenPGP_EncryptedDataPacket) return $p;
|
||||
}
|
||||
throw new Exception("Can only decrypt EncryptedDataPacket");
|
||||
}
|
||||
|
||||
public static function checksum($s) {
|
||||
$mkChk = 0;
|
||||
for($i = 0; $i < strlen($s); $i++) {
|
||||
$mkChk = ($mkChk + ord($s[$i])) % 65536;
|
||||
}
|
||||
return $mkChk;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
if(function_exists('mcrypt_encrypt') && defined('MCRYPT_MODE_CFB')) {
|
||||
class MCryptWrapper {
|
||||
public $cipher, $key, $iv, $key_size, $block_size;
|
||||
|
||||
|
||||
function __construct($cipher) {
|
||||
$this->cipher = $cipher;
|
||||
$this->key_size = mcrypt_module_get_algo_key_size($cipher);
|
||||
$this->block_size = mcrypt_module_get_algo_block_size($cipher);
|
||||
$this->iv = str_repeat("\0", mcrypt_get_iv_size($cipher, 'ncfb'));
|
||||
}
|
||||
|
||||
function getBlockLengthInBytes()
|
||||
{
|
||||
return $this->block_size;
|
||||
}
|
||||
|
||||
function getKeyLength() {
|
||||
return $this->key_size << 3;
|
||||
}
|
||||
|
||||
function setKey($key) {
|
||||
$this->key = $key;
|
||||
}
|
||||
|
||||
function setIV($iv) {
|
||||
$this->iv = $iv;
|
||||
}
|
||||
|
||||
function encrypt($data) {
|
||||
return mcrypt_encrypt($this->cipher, $this->key, $data, 'ncfb', $this->iv);
|
||||
}
|
||||
|
||||
function decrypt($data) {
|
||||
return mcrypt_decrypt($this->cipher, $this->key, $data, 'ncfb', $this->iv);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
if(function_exists('openssl_encrypt')) {
|
||||
class OpenSSLWrapper {
|
||||
public $cipher, $key, $iv, $key_size, $block_size;
|
||||
|
||||
|
||||
function __construct($cipher) {
|
||||
if($cipher != "CAST5-CFB") throw Exception("OpenSSLWrapper is only used for CAST5 right now");
|
||||
|
||||
$this->cipher = $cipher;
|
||||
$this->key_size = 16;
|
||||
$this->block_size = 8;
|
||||
$this->iv = str_repeat("\0", 8);
|
||||
}
|
||||
|
||||
function getBlockLengthInBytes()
|
||||
{
|
||||
return $this->block_size;
|
||||
}
|
||||
|
||||
function getKeyLength() {
|
||||
return $this->key_size << 3;
|
||||
}
|
||||
|
||||
function setKey($key) {
|
||||
$this->key = $key;
|
||||
}
|
||||
|
||||
function setIV($iv) {
|
||||
$this->iv = $iv;
|
||||
}
|
||||
|
||||
function encrypt($data) {
|
||||
return openssl_encrypt($data, $this->cipher, $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $this->iv);
|
||||
}
|
||||
|
||||
function decrypt($data) {
|
||||
return openssl_decrypt($data, $this->cipher, $this->key, OPENSSL_RAW_DATA|OPENSSL_ZERO_PADDING, $this->iv);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
function sodium_make_verifier($pk) {
|
||||
return function($m, $s) use ($pk) {
|
||||
if($pk instanceof OpenPGP_Message) {
|
||||
foreach($pk as $p) {
|
||||
if($p instanceof OpenPGP_PublicKeyPacket) {
|
||||
if(substr($p->fingerprint, strlen($s->issuer())*-1) == $s->issuer()) {
|
||||
$pk = $p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($pk->algorithm != 22) throw new Exception("Only EdDSA supported");
|
||||
if (bin2hex($pk->key['oid']) != '2b06010401da470f01') throw new Exception("Only ed25519 supported");
|
||||
return sodium_crypto_sign_verify_detached(
|
||||
implode($s->data),
|
||||
hash($s->hash_algorithm_name(), $m, true),
|
||||
substr($pk->key['p'], 1)
|
||||
);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<phpunit bootstrap="tests/bootstrap.php">
|
||||
<testsuites>
|
||||
<testsuite name="Serialization">
|
||||
<file>tests/suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="Fingerprint">
|
||||
<file>tests/suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="Signature">
|
||||
<file>tests/suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="MessageVerification">
|
||||
<file>tests/phpseclib_suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="KeyVerification">
|
||||
<file>tests/phpseclib_suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="Decryption">
|
||||
<file>tests/phpseclib_suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="Encryption">
|
||||
<file>tests/phpseclib_suite.php</file>
|
||||
</testsuite>
|
||||
|
||||
<testsuite name="SodiumMessageVerification">
|
||||
<file>tests/sodium_suite.php</file>
|
||||
</testsuite>
|
||||
</testsuites>
|
||||
</phpunit>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?php
|
||||
@include_once dirname(__FILE__) . '/../vendor/autoload.php';
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´$Test Key (RSA) <testkey@example.org>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´$Test Key (DSA) <testkey@example.com>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´+Test Key (DSA sign-only) <test@example.net>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´.Test Key (RSA sign-only) <testkey@example.net>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´$Test Key (RSA) <testkey@example.org>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´$Test Key (DSA) <testkey@example.com>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´+Test Key (DSA sign-only) <test@example.net>
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
´.Test Key (RSA sign-only) <testkey@example.net>
|
||||
Binary file not shown.
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user