| 1 |
<?php |
| 2 |
|
| 3 |
namespace Defuse\Crypto; |
| 4 |
|
| 5 |
use Defuse\Crypto\Exception as Ex; |
| 6 |
|
| 7 |
final class Key |
| 8 |
{ |
| 9 |
const KEY_CURRENT_VERSION = "\xDE\xF0\x00\x00"; |
| 10 |
const KEY_BYTE_SIZE = 32; |
| 11 |
|
| 12 |
private $key_bytes = null; |
| 13 |
|
| 14 |
/** |
| 15 |
* Creates new random key. |
| 16 |
* |
| 17 |
* @throws Ex\EnvironmentIsBrokenException |
| 18 |
* |
| 19 |
* @return Key |
| 20 |
*/ |
| 21 |
public static function createNewRandomKey() |
| 22 |
{ |
| 23 |
return new Key(Core::secureRandom(self::KEY_BYTE_SIZE)); |
| 24 |
} |
| 25 |
|
| 26 |
/** |
| 27 |
* Loads a Key from its encoded form. |
| 28 |
* |
| 29 |
* @param string $saved_key_string |
| 30 |
* |
| 31 |
* @throws Ex\BadFormatException |
| 32 |
* @throws Ex\EnvironmentIsBrokenException |
| 33 |
* |
| 34 |
* @return Key |
| 35 |
*/ |
| 36 |
public static function loadFromAsciiSafeString($saved_key_string) |
| 37 |
{ |
| 38 |
$key_bytes = Encoding::loadBytesFromChecksummedAsciiSafeString(self::KEY_CURRENT_VERSION, $saved_key_string); |
| 39 |
return new Key($key_bytes); |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Encodes the Key into a string of printable ASCII characters. |
| 44 |
* |
| 45 |
* @throws Ex\EnvironmentIsBrokenException |
| 46 |
* |
| 47 |
* @return string |
| 48 |
*/ |
| 49 |
public function saveToAsciiSafeString() |
| 50 |
{ |
| 51 |
return Encoding::saveBytesToChecksummedAsciiSafeString( |
| 52 |
self::KEY_CURRENT_VERSION, |
| 53 |
$this->key_bytes |
| 54 |
); |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* Gets the raw bytes of the key. |
| 59 |
* |
| 60 |
* @return string |
| 61 |
*/ |
| 62 |
public function getRawBytes() |
| 63 |
{ |
| 64 |
return $this->key_bytes; |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Constructs a new Key object from a string of raw bytes. |
| 69 |
* |
| 70 |
* @param string $bytes |
| 71 |
* |
| 72 |
* @throws Ex\EnvironmentIsBrokenException |
| 73 |
*/ |
| 74 |
private function __construct($bytes) |
| 75 |
{ |
| 76 |
if (Core::ourStrlen($bytes) !== self::KEY_BYTE_SIZE) { |
| 77 |
throw new Ex\EnvironmentIsBrokenException( |
| 78 |
'Bad key length.' |
| 79 |
); |
| 80 |
} |
| 81 |
$this->key_bytes = $bytes; |
| 82 |
} |
| 83 |
|
| 84 |
} |
| 85 |
|