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 = crypt_random_string($key_block_bytes);
$prefix .= substr($prefix, -2);
$key = crypt_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(crypt_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);
}