GithubHelp home page GithubHelp logo

valga / php-encrypted-streams Goto Github PK

View Code? Open in Web Editor NEW

This project forked from jeskew/php-encrypted-streams

0.0 0.0 0.0 80 KB

Encrypt or decrypt streaming data of unbounded sizes. Uses PSR-7 compatible streams.

License: Apache License 2.0

PHP 100.00%

php-encrypted-streams's Introduction

PSR-7 Stream Encryption Decorators

Build Status Total Downloads Author

PHP's built-in OpenSSL bindings provide a convenient means of encrypting and decrypting data. The interface provided by ext-openssl, however, only operates on strings, so decrypting a large ciphertext would require loading the entire ciphertext into memory and receiving a string containing the entirety of the decoded plaintext.

This package aims to allow the encryption and decryption of streams of arbitrary size. It supports streaming encryption and decryption using AES-CBC, AES-CTR, and AES-ECB.

Using AES-ECB is NOT RECOMMENDED for new systems. It is included to allow interoperability with older systems. Please consult Wikipedia for a discussion of the drawbacks of ECB.

Usage

Decorate an instance of Psr\Http\Message\StreamInterface with an encrypting decorator to incrementally encrypt the contents of the decorated stream as read is called on the decorating stream:

$iv = random_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$cipherMethod = new Cbc($iv);
$key = 'some-secret-password-here';

$inStream = new Stream(fopen('some-input-file', 'r')); // Any PSR-7 stream will be fine here
$cipherTextStream = new AesEncryptingStream($inStream, $key, $cipherMethod); // Wrap the stream in an EncryptingStream
$cipherTextFile = Psr7\stream_for(fopen('encrypted.file', 'w'));
Psr7\copy_to_stream($cipherTextStream, $cipherTextFile); // When you read from the encrypting stream, the data will be encrypted.

// You'll also need to store the IV somewhere, because we'll need it later to decrypt the data.
// In this case, I'll base64 encode it and stick it in a file (but we could put it anywhere where we can retrieve it later, like a database column)
file_put_contents('encrypted.iv', base64_encode($iv));

No encryption is performed until read is called on the encrypting stream.

To calculate the HMAC of a cipher text, wrap a decorated stream with an instance of HashingStream:

$hash = null;
$ciphertext = new Jsq\EncryptionStreams\AesEncryptingStream(
    $plaintext,
    $key,
    $cipherMethod
);
$hashingDecorator = new Jsq\EncryptionStreams\HashingStream(
    $ciphertext,
    $key,
    function ($calculatedHash) use (&$hash) {
        $hash = $calculatedHash;
    }
);

while (!$ciphertext->eof()) {
    $ciphertext->read(1024 * 1024);
}

assert('$hash === $hashingDecorator->getHash()');

When decrypting a cipher text, wrap the cipher text in a hasing decorator before passing it as an argument to the decrypting stream:

$key = 'secret key';
$iv = random_bytes(openssl_cipher_iv_length('aes-256-cbc'));
$plainText = 'Super secret text';
$cipherText = openssl_encrypt(
    $plainText,
    'aes-256-cbc',
    $key,
    OPENSSL_RAW_DATA
    $iv
);
$expectedHash = hash('sha256', $cipherText);

$hashingDecorator = new Jsq\EncryptingStreams\HashingStream(
    GuzzleHttp\Psr7\stream_for($cipherText),
    $key,
    function ($hash) use ($expectedHash) {
        if ($hash !== $expectedHash) {
            throw new DomainException('Cipher text mac does not match expected value!');
        }
    }
);

$decrypted = new Jsq\EncryptionStreams\AesEncryptingStream(
    $cipherText,
    $key,
    $cipherMethod
);
while (!$decrypted->eof()) {
    $decrypted->read(1024 * 1024);
}

As with the encrypting decorators, HashingStreams are lazy and will only hash the underlying stream as it is read. In the example above, no exception would be thrown until the entire cipher text had been read (and all but the last block deciphered).

HashingStreams are not seekable, so you will need to wrap on in a GuzzleHttp\Psr7\CachingStream to support random access.

php-encrypted-streams's People

Contributors

jeskew avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.