Skip to content

Commit

Permalink
remove singleton from Encryptor (to make dependency injection easier)…
Browse files Browse the repository at this point in the history
…. More strict_types
  • Loading branch information
pavarnos committed Aug 13, 2018
1 parent f327e6c commit 04068d8
Show file tree
Hide file tree
Showing 11 changed files with 150 additions and 137 deletions.
77 changes: 29 additions & 48 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,49 +43,12 @@ If you want to check whether your server meets the requirements and everything i
### Creating a connection

```php
use Threema\MsgApi\Connection;
use Threema\MsgApi\ConnectionSettings;
use Threema\MsgApi\Receiver;

require_once('lib/bootstrap.php');

//define your connection settings
$settings = new ConnectionSettings(
'*MYKEY12',
'MYAPISECRET'
);

$connection = new Connection($settings);
```

### Creating a connection with advanced options

**Attention:** These settings change internal values of the TLS connection. Choosing wrong settings can weaken the TLS connection or prevent a successful connection to the server. Use them with care!

Each of the additional options shown below is optional. You can leave it out or use `null` to use the default value determined by cURL for this option.

```php
use Threema\MsgApi\Connection;
use Threema\MsgApi\ConnectionSettings;
use Threema\MsgApi\Receiver;

//define your connection settings
$settings = new ConnectionSettings(
'*MYKEY12',
'MYAPISECRET',
null, //the host to be used, set to null to use the default (recommend)
[
'forceHttps' => true, //set to true to force HTTPS, default: true
'tlsVersion' => '1.2', //set the version of TLS to be used, default: '1.2'
'tlsCipher' => 'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384' //choose a cipher or a list of ciphers, default: null
'pinnedKey' => MsgApi\Constants::DEFAULT_PINNED_KEY // the hashes to pin, it is NOT recommend to change this value!
]
);

$connection = new Connection($settings);
$connectionFactory = new ConnectionFactory();
$connection = $connectionFactory->getConnection('*MYKEY12', 'MYAPISECRET');
```

**Note:** For `pinnedKey` to work you must install cURL 7.39 or higher. You can test whether it works by specifying an invalid pin.
There is only one encryption method and one HttpDriver (currently) available. If you want to change connection settings
or provide alternate drivers or mock for testing, pass them in to the ConnectionFactory constructor

### Sending a text message to a Threema ID (Simple Mode)

Expand All @@ -104,8 +67,7 @@ else {
### Sending a text message to a Threema ID (E2E Mode)

```php
$e2eHelper = new \Threema\MsgApi\Helpers\E2EHelper($senderPrivateKey,$connection);
$result = $e2eHelper->sendTextMessage("TEST1234", "thePublicKeyAsHex", "This is an end-to-end encrypted message");
$result = $connection->sendTextMessage($myPrivateKeyHex, "TEST1234", "thePublicKeyAsHex", "This is an end-to-end encrypted message");

if(true === $result->isSuccess()) {
echo 'Message ID: '.$result->getMessageId() . "\n";
Expand All @@ -118,11 +80,9 @@ else {
### Sending a file message to a Threema ID (E2E Mode)

```php
$senderPrivateKey = "MY_PUBLIC_KEY_IN_BIN";
$filePath = "/path/to/my/file.pdf";

$e2eHelper = new \Threema\MsgApi\Helpers\E2EHelper($senderPrivateKey,$connection);
$result = $e2eHelper->sendFileMessage("TEST1234", "thePublicKeyAsHex", $filePath);
$result = $connection->sendFileMessage($myPrivateKeyHex, "TEST1234", "thePublicKeyAsHex", $filePath);

if(true === $result->isSuccess()) {
echo 'File Message ID: '.$result->getMessageId() . "\n";
Expand All @@ -132,20 +92,41 @@ else {
}
```

### Technical notes

Much of the communication with the Threema Gateway server is in binary. But not all of it. Sometimes you get a hex version of the binary value back.
The PHP wrapper attempts to hide all this from you: pass all values to `$connection` as hex encoded binary (`$encryptor->bin2hex()`).
All values coming back are hex encoded binary.

The encryptor mostly requires and returns binary strings as parameters, but for normal use of the api you will not need the
encryptor so will not need to worry about it. See the console commands for examples if unsure. Most parameters now have
phpDoc comments to tell you if they are binary strings or hex strings.

tl;dr: expect to see and use hex

## Console client usage

Run
```
vendor\bin\threema-gateway
```
for a list of commands and their options
for a list of commands and their options.

Store your api secret, public and private keys in a file called `default.key` in the current working directory. See
`default.key.sample` for a template.

A good smoke test to see if everything is working right is
```
vendor\bin\threema-gateway -C *MYKEY12 MYAPISECRET
vendor\bin\threema-gateway credits
```
which should show you the number of credits remaining in your account or an error message on failure.

To generate a new key pair,
```
vendor\bin\threema-gateway key:create-pair
```
which will print the keys to the console. Copy and paste those to your `default.key` file.

## Contributing

Your pull requests are welcome here. Please follow the informal coding style that already exists (which tries to stay close to Threema's original).
Expand Down
23 changes: 13 additions & 10 deletions src/Threema/MsgApi/Commands/LookupBulk.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,12 @@
* @copyright Copyright (c) 2015-2016 Threema GmbH
*/

declare(strict_types=1);

namespace Threema\MsgApi\Commands;

use Threema\MsgApi\Commands\Results\LookupBulkResult;
use Threema\MsgApi\Commands\Results\Result;
use Threema\MsgApi\Encryptor\AbstractEncryptor;

/**
Expand Down Expand Up @@ -59,19 +62,19 @@ public function getParams(): array

public function getJson(): string
{
$encryptor = AbstractEncryptor::getInstance();
$request = [];

return json_encode(['emailHashes' => array_keys($this->hashedEmail),
'phoneHashes' => array_keys($this->hashedPhone)]);
}

public function calculateHashes(AbstractEncryptor $encryptor)
{
foreach ($this->phone as $id => $phoneNumber) {
$hashedPhoneNumber = $encryptor->hashPhoneNo($phoneNumber);
$request['phoneHashes'][] = $hashedPhoneNumber;
$this->hashedPhone[$hashedPhoneNumber][$id] = $phoneNumber;
$this->hashedPhone[$encryptor->hashPhoneNo($phoneNumber)][$id] = $phoneNumber;
}
foreach ($this->email as $id => $emailAddress) {
$hashedEmail = $encryptor->hashEmail($emailAddress);
$request['emailHashes'][] = $hashedEmail;
$this->hashedEmail[$hashedEmail][$id] = $emailAddress;
$this->hashedEmail[$encryptor->hashEmail($emailAddress)][$id] = $emailAddress;
}
return json_encode($request);
}

/**
Expand All @@ -87,7 +90,7 @@ public function getPath(): string
* @param object $res
* @return LookupBulkResult
*/
public function parseResult($httpCode, $res): \Threema\MsgApi\Commands\Results\Result
public function parseResult($httpCode, $res): Result
{
return new LookupBulkResult($httpCode, $res, $this);
}
Expand Down
24 changes: 19 additions & 5 deletions src/Threema/MsgApi/Commands/LookupEmail.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
* @copyright Copyright (c) 2015-2016 Threema GmbH
*/

declare(strict_types=1);

namespace Threema\MsgApi\Commands;

use Threema\MsgApi\Commands\Results\LookupIdResult;
use Threema\MsgApi\Encryptor\AbstractEncryptor;
use Threema\MsgApi\Commands\Results\Result;

class LookupEmail implements CommandInterface
{
Expand All @@ -16,22 +18,34 @@ class LookupEmail implements CommandInterface
*/
private $emailAddress;

/** @var string */
private $hashedEmail;

/**
* @param string $emailAddress
*/
public function __construct($emailAddress)
public function __construct(string $emailAddress, string $hashedEmail)
{
$this->emailAddress = $emailAddress;
$this->hashedEmail = $hashedEmail;
}

/**
* @return string
*/
public function getEmailAddress()
public function getEmailAddress(): string
{
return $this->emailAddress;
}

/**
* @return string
*/
public function getHashedEmail(): string
{
return $this->hashedEmail;
}

/**
* @return array
*/
Expand All @@ -45,15 +59,15 @@ public function getParams(): array
*/
public function getPath(): string
{
return 'lookup/email_hash/' . urlencode(AbstractEncryptor::getInstance()->hashEmail($this->emailAddress));
return 'lookup/email_hash/' . $this->hashedEmail;
}

/**
* @param int $httpCode
* @param object $res
* @return LookupIdResult
*/
public function parseResult($httpCode, $res): \Threema\MsgApi\Commands\Results\Result
public function parseResult($httpCode, $res): Result
{
return new LookupIdResult($httpCode, $res);
}
Expand Down
27 changes: 19 additions & 8 deletions src/Threema/MsgApi/Commands/LookupPhone.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
* @copyright Copyright (c) 2015-2016 Threema GmbH
*/

declare(strict_types=1);

namespace Threema\MsgApi\Commands;

use Threema\MsgApi\Commands\Results\LookupIdResult;
use Threema\MsgApi\Encryptor\AbstractEncryptor;
use Threema\MsgApi\Commands\Results\Result;

class LookupPhone implements CommandInterface
{
Expand All @@ -16,22 +18,31 @@ class LookupPhone implements CommandInterface
*/
private $phoneNumber;

/**
* @param string $phoneNumber
*/
public function __construct($phoneNumber)
/** @var string */
private $hashedPhone;

public function __construct(string $phoneNumber, string $hashedPhone)
{
$this->phoneNumber = $phoneNumber;
$this->hashedPhone = $hashedPhone;
}

/**
* @return string
*/
public function getPhoneNumber()
public function getPhoneNumber(): string
{
return $this->phoneNumber;
}

/**
* @return string
*/
public function getHashedPhone(): string
{
return $this->hashedPhone;
}

/**
* @return array
*/
Expand All @@ -45,15 +56,15 @@ public function getParams(): array
*/
public function getPath(): string
{
return 'lookup/phone_hash/' . urlencode(AbstractEncryptor::getInstance()->hashPhoneNo($this->phoneNumber));
return 'lookup/phone_hash/' . $this->hashedPhone;
}

/**
* @param int $httpCode
* @param object $res
* @return LookupIdResult
*/
public function parseResult($httpCode, $res): \Threema\MsgApi\Commands\Results\Result
public function parseResult($httpCode, $res): Result
{
return new LookupIdResult($httpCode, $res);
}
Expand Down
2 changes: 1 addition & 1 deletion src/Threema/MsgApi/Commands/Results/Result.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ abstract class Result
* @param int $httpCode
* @param string $response
*/
public function __construct($httpCode, $response)
public function __construct(int $httpCode, $response)
{
$this->httpCode = $httpCode;
$this->processResponse($response);
Expand Down
30 changes: 19 additions & 11 deletions src/Threema/MsgApi/Commands/SendE2E.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@
* @copyright Copyright (c) 2015-2016 Threema GmbH
*/

declare(strict_types=1);

namespace Threema\MsgApi\Commands;

use Threema\MsgApi\Commands\Results\Result;
use Threema\MsgApi\Commands\Results\SendE2EResult;
use Threema\MsgApi\Encryptor\AbstractEncryptor;

class SendE2E implements CommandInterface
{
Expand All @@ -28,10 +30,10 @@ class SendE2E implements CommandInterface

/**
* @param string $threemaId
* @param string $nonce
* @param string $box
* @param string $nonce hex
* @param string $box hex
*/
public function __construct($threemaId, $nonce, $box)
public function __construct(string $threemaId, string $nonce, string $box)
{
$this->nonce = $nonce;
$this->box = $box;
Expand All @@ -41,15 +43,23 @@ public function __construct($threemaId, $nonce, $box)
/**
* @return string
*/
public function getNonce()
public function getThreemaId(): string
{
return $this->threemaId;
}

/**
* @return string
*/
public function getNonce(): string
{
return $this->nonce;
}

/**
* @return string
*/
public function getBox()
public function getBox(): string
{
return $this->box;
}
Expand All @@ -59,11 +69,9 @@ public function getBox()
*/
public function getParams(): array
{
$encryptor = AbstractEncryptor::getInstance();

$p['to'] = $this->threemaId;
$p['nonce'] = $encryptor->bin2hex($this->getNonce());
$p['box'] = $encryptor->bin2hex($this->getBox());
$p['nonce'] = $this->nonce;
$p['box'] = $this->box;
return $p;
}

Expand All @@ -80,7 +88,7 @@ public function getPath(): string
* @param object $res
* @return SendE2EResult
*/
public function parseResult($httpCode, $res): \Threema\MsgApi\Commands\Results\Result
public function parseResult($httpCode, $res): Result
{
return new SendE2EResult($httpCode, $res);
}
Expand Down
Loading

0 comments on commit 04068d8

Please sign in to comment.