OpenPGP_Crypt_Symmetric::encrypt PHP Method

encrypt() public static method

public static encrypt ( $passphrases_and_keys, $message, $symmetric_algorithm = 9 )
    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 . "Ó", 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();
                $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_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(10));
                    $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);
    }

Usage Example

Example #1
0
 public function testEncryptAsymmetric()
 {
     $key = OpenPGP_Message::parse(file_get_contents(dirname(__FILE__) . '/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)));
     $decryptor = new OpenPGP_Crypt_RSA($key);
     $decrypted = $decryptor->decrypt($encrypted);
     $this->assertEquals($decrypted[0]->data, 'This is text.');
 }
All Usage Examples Of OpenPGP_Crypt_Symmetric::encrypt