Skip to content

Commit 8d540e1

Browse files
committed
RSA: split ciphertext and plaintext up by block size
1 parent 9a4cfa4 commit 8d540e1

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

src/Crypt/RSA.php

+31-3
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,7 @@ public function __toString()
456456
*/
457457
public function setPublicKey()
458458
{
459-
return false;
459+
return false;
460460
}
461461

462462
/**
@@ -823,7 +823,23 @@ public function getComment()
823823
public function encrypt($plaintext)
824824
{
825825
if ($this->key instanceof PublicKey) {
826-
return $this->key->encrypt($plaintext);
826+
switch ($this->encryptionMode) {
827+
case self::ENCRYPTION_PKCS1:
828+
$len = ($this->key->getLength() - 88) >> 3;
829+
break;
830+
case self::ENCRYPTION_NONE:
831+
$len = $this->key->getLength() >> 3;
832+
break;
833+
//case self::ENCRYPTION_OAEP:
834+
default:
835+
$len = ($this->key->getLength() - 2 * $this->key->getHash()->getLength() - 16) >> 3;
836+
}
837+
$plaintext = str_split($plaintext, $len);
838+
$ciphertext = '';
839+
foreach ($plaintext as $m) {
840+
$ciphertext.= $this->key->encrypt($m);
841+
}
842+
return $ciphertext;
827843
}
828844

829845
return false;
@@ -840,7 +856,19 @@ public function encrypt($plaintext)
840856
public function decrypt($ciphertext)
841857
{
842858
if ($this->key instanceof PrivateKey) {
843-
return $this->key->decrypt($ciphertext);
859+
$len = $this->key->getLength() >> 3;
860+
$ciphertext = str_split($ciphertext, $len);
861+
$ciphertext[count($ciphertext) - 1] = str_pad($ciphertext[count($ciphertext) - 1], $len, chr(0), STR_PAD_LEFT);
862+
863+
$plaintext = '';
864+
foreach ($ciphertext as $c) {
865+
try {
866+
$plaintext.= $this->key->decrypt($c);
867+
} catch (\Exception $e) {
868+
return false;
869+
}
870+
}
871+
return $plaintext;
844872
}
845873

846874
return false;

0 commit comments

Comments
 (0)