Add defuse/php-encryption 2.0 to Composer dependencies

This commit is contained in:
Hypolite Petovan 2017-11-09 02:13:02 -05:00
parent ede20ac95a
commit 3b2cd85483
61 changed files with 6289 additions and 1 deletions

View file

@ -0,0 +1,260 @@
Class: Defuse\Crypto\Crypto
============================
The `Crypto` class provides encryption and decryption of strings either using
a secret key or secret password. For encryption and decryption of large files,
see the `File` class.
This code for this class is in `src/Crypto.php`.
Instance Methods
-----------------
This class has no instance methods.
Static Methods
---------------
### Crypto::encrypt($plaintext, Key $key, $raw\_binary = false)
**Description:**
Encrypts a plaintext string using a secret key.
**Parameters:**
1. `$plaintext` is the string to encrypt.
2. `$key` is an instance of `Key` containing the secret key for encryption.
3. `$raw_binary` determines whether the output will be a byte string (true) or
hex encoded (false, the default).
**Return value:**
Returns a ciphertext string representing `$plaintext` encrypted with the key
`$key`. Knowledge of `$key` is required in order to decrypt the ciphertext and
recover the plaintext.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
This method runs a small and very fast set of self-tests if it is the very first
time one of the `Crypto` methods has been called. The performance overhead is
negligible and can be safely ignored in all applications.
**Cautions:**
The ciphertext returned by this method is decryptable by anyone with knowledge
of the key `$key`. It is the caller's responsibility to keep `$key` secret.
Where `$key` should be stored is up to the caller and depends on the threat
model the caller is designing their application under. If you are unsure where
to store `$key`, consult with a professional cryptographer to get help designing
your application.
### Crypto::decrypt($ciphertext, Key $key, $raw\_binary = false)
**Description:**
Decrypts a ciphertext string using a secret key.
**Parameters:**
1. `$ciphertext` is the ciphertext to be decrypted.
2. `$key` is an instance of `Key` containing the secret key for decryption.
3. `$raw_binary` must have the same value as the `$raw_binary` given to the
call to `encrypt()` that generated `$ciphertext`.
**Return value:**
If the decryption succeeds, returns a string containing the same value as the
string that was passed to `encrypt()` when `$ciphertext` was produced. Upon
a successful return, the caller can be assured that `$ciphertext` could not have
been produced except by someone with knowledge of `$key`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$key` is not the correct key for the given ciphertext, or if the
ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects and performance:**
This method runs a small and very fast set of self-tests if it is the very first
time one of the `Crypto` methods has been called. The performance overhead is
negligible and can be safely ignored in all applications.
**Cautions:**
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong key and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.
### Crypto::encryptWithPassword($plaintext, $password, $raw\_binary = false)
**Description:**
Encrypts a plaintext string using a secret password.
**Parameters:**
1. `$plaintext` is the string to encrypt.
2. `$password` is a string containing the secret password used for encryption.
3. `$raw_binary` determines whether the output will be a byte string (true) or
hex encoded (false, the default).
**Return value:**
Returns a ciphertext string representing `$plaintext` encrypted with a key
derived from `$password`. Knowledge of `$password` is required in order to
decrypt the ciphertext and recover the plaintext.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
This method is intentionally slow, using a lot of CPU resources for a fraction
of a second. It applies key stretching to the password in order to make password
guessing attacks more computationally expensive. If you need a faster way to
encrypt multiple ciphertexts under the same password, see the
`KeyProtectedByPassword` class.
This method runs a small and very fast set of self-tests if it is the very first
time one of the `Crypto` methods has been called. The performance overhead is
negligible and can be safely ignored in all applications.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
### Crypto::decryptWithPassword($ciphertext, $password, $raw\_binary = false)
**Description:**
Decrypts a ciphertext string using a secret password.
**Parameters:**
1. `$ciphertext` is the ciphertext to be decrypted.
2. `$password` is a string containing the secret password used for decryption.
3. `$raw_binary` must have the same value as the `$raw_binary` given to the
call to `encryptWithPassword()` that generated `$ciphertext`.
**Return value:**
If the decryption succeeds, returns a string containing the same value as the
string that was passed to `encryptWithPassword()` when `$ciphertext` was
produced. Upon a successful return, the caller can be assured that `$ciphertext`
could not have been produced except by someone with knowledge of `$password`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$password` is not the correct password for the given ciphertext, or if
the ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects:**
This method is intentionally slow. It applies key stretching to the password in
order to make password guessing attacks more computationally expensive. If you
need a faster way to encrypt multiple ciphertexts under the same password, see
the `KeyProtectedByPassword` class.
This method runs a small and very fast set of self-tests if it is the very first
time one of the `Crypto` methods has been called. The performance overhead is
negligible and can be safely ignored in all applications.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong password and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.
### Crypto::legacyDecrypt($ciphertext, $key)
**Description:**
Decrypts a ciphertext produced by version 1 of this library so that the
plaintext can be re-encrypted into a version 2 ciphertext. See [Upgrading from
v1.2](../UpgradingFromV1.2.md).
**Parameters:**
1. `$ciphertext` is a ciphertext produced by version 1.x of this library.
2. `$key` is a 16-byte string (*not* a Key object) containing the key that was
used with version 1.x of this library to produce `$ciphertext`.
**Return value:**
If the decryption succeeds, returns the string that was encrypted to make
`$ciphertext` by version 1.x of this library. Upon a successful return, the
caller can be assured that `$ciphertext` could not have been produced except by
someone with knowledge of `$key`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$key` is not the correct key for the given ciphertext, or if the
ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects:**
This method runs a small and very fast set of self-tests if it is the very first
time one of the `Crypto` methods has been called. The performance overhead is
negligible and can be safely ignored in all applications.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$key` may be leaked out to an attacker through the stack trace. We
recommend configuring PHP to never output stack traces (either displaying them
to the user or saving them to log files).
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong key and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.

View file

@ -0,0 +1,446 @@
Class: Defuse\Crypto\File
==========================
Instance Methods
-----------------
This class has no instance methods.
Static Methods
---------------
### File::encryptFile($inputFilename, $outputFilename, Key $key)
**Description:**
Encrypts a file using a secret key.
**Parameters:**
1. `$inputFilename` is the path to a file containing the plaintext to encrypt.
2. `$outputFilename` is the path to save the ciphertext file.
3. `$key` is an instance of `Key` containing the secret key for encryption.
**Behavior:**
Encrypts the contents of the input file, writing the result to the output file.
If the output file already exists, it is overwritten.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
None.
**Cautions:**
The ciphertext output by this method is decryptable by anyone with knowledge of
the key `$key`. It is the caller's responsibility to keep `$key` secret. Where
`$key` should be stored is up to the caller and depends on the threat model the
caller is designing their application under. If you are unsure where to store
`$key`, consult with a professional cryptographer to get help designing your
application.
### File::decryptFile($inputFilename, $outputFilename, Key $key)
**Description:**
Decrypts a file using a secret key.
**Parameters:**
1. `$inputFilename` is the path to a file containing the ciphertext to decrypt.
2. `$outputFilename` is the path to save the decrypted plaintext file.
3. `$key` is an instance of `Key` containing the secret key for decryption.
**Behavior:**
Decrypts the contents of the input file, writing the result to the output file.
If the output file already exists, it is overwritten.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$key` is not the correct key for the given ciphertext, or if the
ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects and performance:**
The input ciphertext is processed in two passes. The first pass verifies the
integrity and the second pass performs the actual decryption of the file and
writing to the output file. This is done in a streaming manner so that only
a small part of the file is ever loaded into memory at a time.
**Cautions:**
Be aware that when `Defuse\Crypto\WrongKeyOrModifiedCiphertextException` is
thrown, some partial plaintext data may have been written to the output. Any
plaintext data that is output is guaranteed to be a prefix of the original
plaintext (i.e. at worst it was truncated). This can only happen if an attacker
modifies the input between the first pass (integrity check) and the second pass
(decryption) over the file.
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong key and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.
### File::encryptFileWithPassword($inputFilename, $outputFilename, $password)
**Description:**
Encrypts a file with a password.
**Parameters:**
1. `$inputFilename` is the path to a file containing the plaintext to encrypt.
2. `$outputFilename` is the path to save the ciphertext file.
3. `$password` is the password used for decryption.
**Behavior:**
Encrypts the contents of the input file, writing the result to the output file.
If the output file already exists, it is overwritten.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
This method is intentionally slow, using a lot of CPU resources for a fraction
of a second. It applies key stretching to the password in order to make password
guessing attacks more computationally expensive. If you need a faster way to
encrypt multiple ciphertexts under the same password, see the
`KeyProtectedByPassword` class.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
### File::decryptFileWithPassword($inputFilename, $outputFilename, $password)
**Description:**
Decrypts a file with a password.
**Parameters:**
1. `$inputFilename` is the path to a file containing the ciphertext to decrypt.
2. `$outputFilename` is the path to save the decrypted plaintext file.
3. `$password` is the password used for decryption.
**Behavior:**
Decrypts the contents of the input file, writing the result to the output file.
If the output file already exists, it is overwritten.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$password` is not the correct key for the given ciphertext, or if the
ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects and performance:**
This method is intentionally slow, using a lot of CPU resources for a fraction
of a second. It applies key stretching to the password in order to make password
guessing attacks more computationally expensive. If you need a faster way to
encrypt multiple ciphertexts under the same password, see the
`KeyProtectedByPassword` class.
The input ciphertext is processed in two passes. The first pass verifies the
integrity and the second pass performs the actual decryption of the file and
writing to the output file. This is done in a streaming manner so that only
a small part of the file is ever loaded into memory at a time.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
Be aware that when `Defuse\Crypto\WrongKeyOrModifiedCiphertextException` is
thrown, some partial plaintext data may have been written to the output. Any
plaintext data that is output is guaranteed to be a prefix of the original
plaintext (i.e. at worst it was truncated). This can only happen if an attacker
modifies the input between the first pass (integrity check) and the second pass
(decryption) over the file.
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong password and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.
### File::encryptResource($inputHandle, $outputHandle, Key $key)
**Description:**
Encrypts a resource (stream) with a secret key.
**Parameters:**
1. `$inputHandle` is a handle to a resource (like a file pointer) containing the
plaintext to encrypt.
2. `$outputHandle` is a handle to a resource (like a file pointer) that the
ciphertext will be written to.
3. `$key` is an instance of `Key` containing the secret key for encryption.
**Behavior:**
Encrypts the data read from the input stream and writes it to the output stream.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
None.
**Cautions:**
The ciphertext output by this method is decryptable by anyone with knowledge of
the key `$key`. It is the caller's responsibility to keep `$key` secret. Where
`$key` should be stored is up to the caller and depends on the threat model the
caller is designing their application under. If you are unsure where to store
`$key`, consult with a professional cryptographer to get help designing your
application.
### File::decryptResource($inputHandle, $outputHandle, Key $key)
**Description:**
Decrypts a resource (stream) with a secret key.
**Parameters:**
1. `$inputHandle` is a handle to a file-backed resource containing the
ciphertext to decrypt. It must be a file not a network stream or standard
input.
2. `$outputHandle` is a handle to a resource (like a file pointer) that the
plaintext will be written to.
3. `$key` is an instance of `Key` containing the secret key for decryption.
**Behavior:**
Decrypts the data read from the input stream and writes it to the output stream.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$key` is not the correct key for the given ciphertext, or if the
ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects and performance:**
The input ciphertext is processed in two passes. The first pass verifies the
integrity and the second pass performs the actual decryption of the file and
writing to the output file. This is done in a streaming manner so that only
a small part of the file is ever loaded into memory at a time.
**Cautions:**
Be aware that when `Defuse\Crypto\WrongKeyOrModifiedCiphertextException` is
thrown, some partial plaintext data may have been written to the output. Any
plaintext data that is output is guaranteed to be a prefix of the original
plaintext (i.e. at worst it was truncated). This can only happen if an attacker
modifies the input between the first pass (integrity check) and the second pass
(decryption) over the file.
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong key and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.
### File::encryptResourceWithPassword($inputHandle, $outputHandle, $password)
**Description:**
Encrypts a resource (stream) with a password.
**Parameters:**
1. `$inputHandle` is a handle to a resource (like a file pointer) containing the
plaintext to encrypt.
2. `$outputHandle` is a handle to a resource (like a file pointer) that the
ciphertext will be written to.
3. `$password` is the password used for encryption.
**Behavior:**
Encrypts the data read from the input stream and writes it to the output stream.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
This method is intentionally slow, using a lot of CPU resources for a fraction
of a second. It applies key stretching to the password in order to make password
guessing attacks more computationally expensive. If you need a faster way to
encrypt multiple ciphertexts under the same password, see the
`KeyProtectedByPassword` class.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
### File::decryptResourceWithPassword($inputHandle, $outputHandle, $password)
**Description:**
Decrypts a resource (stream) with a password.
**Parameters:**
1. `$inputHandle` is a handle to a file-backed resource containing the
ciphertext to decrypt. It must be a file not a network stream or standard
input.
2. `$outputHandle` is a handle to a resource (like a file pointer) that the
plaintext will be written to.
3. `$password` is the password used for decryption.
**Behavior:**
Decrypts the data read from the input stream and writes it to the output stream.
**Return value:**
Does not return a value.
**Exceptions:**
- `Defuse\Crypto\Exception\IOException` is thrown if there is an I/O error.
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
the `$password` is not the correct key for the given ciphertext, or if the
ciphertext has been modified (possibly maliciously). There is no way to
distinguish between these two cases.
**Side-effects and performance:**
This method is intentionally slow, using a lot of CPU resources for a fraction
of a second. It applies key stretching to the password in order to make password
guessing attacks more computationally expensive. If you need a faster way to
encrypt multiple ciphertexts under the same password, see the
`KeyProtectedByPassword` class.
The input ciphertext is processed in two passes. The first pass verifies the
integrity and the second pass performs the actual decryption of the file and
writing to the output file. This is done in a streaming manner so that only
a small part of the file is ever loaded into memory at a time.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
Be aware that when `Defuse\Crypto\WrongKeyOrModifiedCiphertextException` is
thrown, some partial plaintext data may have been written to the output. Any
plaintext data that is output is guaranteed to be a prefix of the original
plaintext (i.e. at worst it was truncated). This can only happen if an attacker
modifies the input between the first pass (integrity check) and the second pass
(decryption) over the file.
It is impossible in principle to distinguish between the case where you attempt
to decrypt with the wrong password and the case where you attempt to decrypt
a modified (corrupted) ciphertext. It is up to the caller how to best deal with
this ambiguity, as it depends on the application this library is being used in.
If in doubt, consult with a professional cryptographer.

View file

@ -0,0 +1,117 @@
Class: Defuse\Crypto\Key
=========================
The `Key` class represents a secret key used for encrypting and decrypting. Once
you have a `Key` instance, you can use it with the `Crypto` class to encrypt and
decrypt strings and with the `File` class to encrypt and decrypt files.
Instance Methods
-----------------
### saveToAsciiSafeString()
**Description:**
Saves the encryption key to a string of printable ASCII characters, which can be
loaded again into a `Key` instance using `Key::loadFromAsciiSafeString()`.
**Parameters:**
This method does not take any parameters.
**Return value:**
Returns a string of printable ASCII characters representing this `Key` instance,
which can be loaded back into an instance of `Key` using
`Key::loadFromAsciiSafeString()`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
None.
**Cautions:**
This method currently returns a hexadecimal string. You should not rely on this
behavior. For example, it may be improved in the future to return a base64
string.
Static Methods
---------------
### Key::createNewRandomKey()
**Description:**
Generates a new random key and returns an instance of `Key`.
**Parameters:**
This method does not take any parameters.
**Return value:**
Returns an instance of `Key` containing a randomly-generated encryption key.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
None.
**Cautions:**
None.
### Key::loadFromAsciiSafeString($saved\_key\_string, $do\_not\_trim = false)
**Description:**
Loads an instance of `Key` that was saved to a string by
`saveToAsciiSafeString()`.
By default, this function will call `Encoding::trimTrailingWhitespace()`
to remove trailing CR, LF, NUL, TAB, and SPACE characters, which are commonly
appended to files when working with text editors.
**Parameters:**
1. `$saved_key_string` is the string returned from `saveToAsciiSafeString()`
when the original `Key` instance was saved.
2. `$do_not_trim` should be set to `TRUE` if you do not wish for the library
to automatically strip trailing whitespace from the string.
**Return value:**
Returns an instance of `Key` representing the same encryption key as the one
that was represented by the `Key` instance that got saved into
`$saved_key_string` by a call to `saveToAsciiSafeString()`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\BadFormatException` is thrown whenever
`$saved_key_string` does not represent a valid `Key` instance.
**Side-effects and performance:**
None.
**Cautions:**
None.

View file

@ -0,0 +1,191 @@
Class: Defuse\Crypto\KeyProtectedByPassword
============================================
The `KeyProtectedByPassword` class represents a key that is "locked" with
a password. In order to obtain an instance of `Key` that you can use for
encrypting and decrypting, a `KeyProtectedByPassword` must first be "unlocked"
by providing the correct password.
`KeyProtectedByPassword` provides an alternative to using the
`encryptWithPassword()`, `decryptWithPassword()`, `encryptFileWithPassword()`,
and `decryptFileWithPassword()` methods with several advantages:
- The slow and computationally-expensive key stretching is run only once when
you unlock a `KeyProtectedByPassword` to obtain the `Key`.
- You do not have to keep the original password in memory to encrypt and decrypt
things. After you've obtained the `Key` from a `KeyProtectedByPassword`, the
password is no longer necessary.
Instance Methods
-----------------
### saveToAsciiSafeString()
**Description:**
Saves the protected key to a string of printable ASCII characters, which can be
loaded again into a `KeyProtectedByPassword` instance using
`KeyProtectedByPassword::loadFromAsciiSafeString()`.
**Parameters:**
This method does not take any parameters.
**Return value:**
Returns a string of printable ASCII characters representing this
`KeyProtectedByPassword` instance, which can be loaded back into an instance of
`KeyProtectedByPassword` using
`KeyProtectedByPassword::loadFromAsciiSafeString()`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
None.
**Cautions:**
This method currently returns a hexadecimal string. You should not rely on this
behavior. For example, it may be improved in the future to return a base64
string.
### unlockKey($password)
**Description:**
Unlocks the password-protected key, obtaining a `Key` which can be used for
encryption and decryption.
**Parameters:**
1. `$password` is the password required to unlock this `KeyProtectedByPassword`
to obtain the `Key`.
**Return value:**
If `$password` is the correct password, then this method returns an instance of
the `Key` class.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\WrongKeyOrModifiedCiphertextException` is thrown if
either the given `$password` is not the correct password for this
`KeyProtectedByPassword` or the ciphertext stored internally by this object
has been modified, i.e. it was accidentally corrupted or intentionally
corrupted by an attacker. There is no way for the caller to distinguish
between these two cases.
**Side-effects and performance:**
This method runs a small and very fast set of self-tests if it is the very first
time this method or one of the `Crypto` methods has been called. The performance
overhead is negligible and can be safely ignored in all applications.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
It is impossible in principle to distinguish between the case where you attempt
to unlock with the wrong password and the case where you attempt to unlock
a modified (corrupted) `KeyProtectedByPassword. It is up to the caller how to
best deal with this ambiguity, as it depends on the application this library is
being used in. If in doubt, consult with a professional cryptographer.
Static Methods
---------------
### KeyProtectedByPassword::createRandomPasswordProtectedKey($password)
**Description:**
Generates a new random key that's protected by the string `$password` and
returns an instance of `KeyProtectedByPassword`.
**Parameters:**
1. `$password` is the password used to protect the random key.
**Return value:**
Returns an instance of `KeyProtectedByPassword` containing a randomly-generated
encryption key that's protected by the password `$password`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
**Side-effects and performance:**
This method runs a small and very fast set of self-tests if it is the very first
time this method or one of the `Crypto` methods has been called. The performance
overhead is negligible and can be safely ignored in all applications.
**Cautions:**
PHP stack traces display (portions of) the arguments passed to methods on the
call stack. If an exception is thrown inside this call, and it is uncaught, the
value of `$password` may be leaked out to an attacker through the stack trace.
We recommend configuring PHP to never output stack traces (either displaying
them to the user or saving them to log files).
Be aware that if you protecting multiple keys with the same password, an
attacker with write access to your system will be able to swap the protected
keys around so that the wrong key gets used next time it is unlocked. This could
lead to data being encrypted with the wrong key, perhaps one that the attacker
knows.
### KeyProtectedByPassword::loadFromAsciiSafeString($saved\_key\_string)
**Description:**
Loads an instance of `KeyProtectedByPassword` that was saved to a string by
`saveToAsciiSafeString()`.
**Parameters:**
1. `$saved_key_string` is the string returned from `saveToAsciiSafeString()`
when the original `KeyProtectedByPassword` instance was saved.
**Return value:**
Returns an instance of `KeyProtectedByPassword` representing the same
password-protected key as the one that was represented by the
`KeyProtectedByPassword` instance that got saved into `$saved_key_string` by
a call to `saveToAsciiSafeString()`.
**Exceptions:**
- `Defuse\Crypto\Exception\EnvironmentIsBrokenException` is thrown either when
the platform the code is running on cannot safely perform encryption for some
reason (e.g. it lacks a secure random number generator), or the runtime tests
detected a bug in this library.
- `Defuse\Crypto\Exception\BadFormatException` is thrown whenever
`$saved_key_string` does not represent a valid `KeyProtectedByPassword`
instance.
**Side-effects and performance:**
None.
**Cautions:**
None.