pikirasa icon indicating copy to clipboard operation
pikirasa copied to clipboard

error:0406D06E:rsa routines:RSA_padding_add_PKCS1_type_2:data too large for key size

Open huiyonghkw opened this issue 8 years ago • 2 comments

Maybe 1024 bit can encrypt 117. so how to encrypt larger data

A trick not mentioned in manual to know :

  • openssl_private_encrypt can encrypt a maximum of 117 chars at one time.
  • the encrypted output string is always 129 char length. If you use base64_encode on the encrypted output, it will give always 172 chars, with the last always "=" (filler)

http://php.net/manual/zh/function.openssl-private-encrypt.php

huiyonghkw avatar Sep 18 '16 03:09 huiyonghkw

    /**
     * Encrypt data and then base64_encode it for long chars
     *
     * @param string $data Data to encrypt
     * @param int    $length split length
     * @return string Base64-encrypted data
     */
    public function base64EncryptForLangChars($data, $length = 117)
    {
        if (strlen($data) < $length ) {
            return $this->base64Encrypt($data);
        }

        $split = split($data, $length);

        foreach ($split as $part) {
            $encryptedData .= base64_encode($this->encrypt($part));
        }
        return $encryptedData;
    }

huiyonghkw avatar Sep 18 '16 04:09 huiyonghkw

@bravist I might be wrong be wouldn't it be simpler to go for openssl_seal/openssl_open() if you want to encrypt large data? But yes one should be aware of the maximum encryption length.

Nguimjeu avatar Apr 20 '17 13:04 Nguimjeu