Skip to content

Commit

Permalink
RSA: split ciphertext and plaintext up by block size
Browse files Browse the repository at this point in the history
  • Loading branch information
terrafrost committed Dec 29, 2020
1 parent 9a4cfa4 commit 8d540e1
Showing 1 changed file with 31 additions and 3 deletions.
34 changes: 31 additions & 3 deletions src/Crypt/RSA.php
Original file line number Diff line number Diff line change
Expand Up @@ -456,7 +456,7 @@ public function __toString()
*/
public function setPublicKey()
{
return false;
return false;
}

/**
Expand Down Expand Up @@ -823,7 +823,23 @@ public function getComment()
public function encrypt($plaintext)
{
if ($this->key instanceof PublicKey) {
return $this->key->encrypt($plaintext);
switch ($this->encryptionMode) {
case self::ENCRYPTION_PKCS1:
$len = ($this->key->getLength() - 88) >> 3;
break;
case self::ENCRYPTION_NONE:
$len = $this->key->getLength() >> 3;
break;
//case self::ENCRYPTION_OAEP:
default:
$len = ($this->key->getLength() - 2 * $this->key->getHash()->getLength() - 16) >> 3;
}
$plaintext = str_split($plaintext, $len);
$ciphertext = '';
foreach ($plaintext as $m) {
$ciphertext.= $this->key->encrypt($m);
}
return $ciphertext;
}

return false;
Expand All @@ -840,7 +856,19 @@ public function encrypt($plaintext)
public function decrypt($ciphertext)
{
if ($this->key instanceof PrivateKey) {
return $this->key->decrypt($ciphertext);
$len = $this->key->getLength() >> 3;
$ciphertext = str_split($ciphertext, $len);
$ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $len, chr(0), STR_PAD_LEFT);

$plaintext = '';
foreach ($ciphertext as $c) {
try {
$plaintext.= $this->key->decrypt($c);
} catch (\Exception $e) {
return false;
}
}
return $plaintext;
}

return false;
Expand Down

0 comments on commit 8d540e1

Please sign in to comment.