Record: Solution to PHP rsa encryption processing failure

藏色散人
Release: 2023-04-10 21:22:02
forward
4888 people have browsed it

About php rsa encryption processing

Recently I just need to connect several interfaces with a third-party system. The other party requires that post data needs rsa encryption, so Baidu searched php about rsa encryption processing, and then you may search for the following example like me:

  /**     
     * @uses 公钥加密     
     * @param string $data     
     * @return null|string     
     */    
    public function publicEncrypt($data = '') {        
        if (!is_string($data)) {
            return null;        
        }        
        return openssl_public_encrypt($data, $encrypted, $this->_getPublicKey()) ? base64_encode($encrypted) : null;
    }
Copy after login

So you happily copy it to your own project, slightly modify it, and test it, and simply pass a few strings into it:

<?php
$string = &#39;基督教解决基督教解决决&#39;;
$ret = publicEncrypt($string);
var_dump($ret);
/**     
 * @uses 公钥加密     
 * @param string $data     
 * @return null|string     
 */    
function publicEncrypt($data = &#39;&#39;) {    
    $publicKey = &#39;MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiX1bIq02AFypLOJ4byShfo6+D6pj0rQrdAtZ8Bb2Z4YwdCZS5vlEduBiVCZSKfF70M0nk4gMqhAKcgwqWxgI1/j8OrX401AssfaiXr2JqsAl679s+Xlwe0jppNe1832+3g0YOawDTpAQsUJDu1DpnyGnUz0qeac0/GiAJlXzKUP+/3db8haDuOkgYrT8A6twGAm7YwIuliieDWDcUS/CQzXGRtwtZQqUJDQsWC1lCML1kRUjbZ2EM2EzyttgHN0SsNryhVLHXSFXpDWbeqQwk36axojGF1lbg/oVQy+BnYJx8pKpTgSwIDAQAB&#39;;    
    $publicKey = "-----BEGIN PUBLIC KEY-----\n" .
    wordwrap($publicKey, 64, "\n", true) .
    "\n-----END PUBLIC KEY-----";
    if (!is_string($data)) {
        return null;        
    }        
    return openssl_public_encrypt($data, $encrypted, $publicKey) ? base64_encode($encrypted) : null;
}
Copy after login

The program prints:

string(344) "HSqVQbyhmWYrptvgzK+ggqmma88QRFVJerXTrZ+RpYqhZr/Dr9au9wxX+aAYy1wRh0eBk+fIpU4wkEZs6P5yozf5e/rAAEYUOImTJZcOvZqr89znT3yqaV8ME+vR16FLK5sk3BwgpOWI6X+wBwU2cLnHKDdj9RpYWAYhi/mn8XJj4/srKZbSgAjvzWqZI9gfqiJNdz8kf/MPtQ65cSlAhvh4eByY8cLGfgUXV0dxzWAkwTSPl2faSq3GHsNMXnxwoNjIvqz/IuZavqABNVZCwrZC3ZVb+Op7wF9GxrkIdJYzmHpX/wNn1DPLHUvghtO/WmfN4Jb2ZVzTsneB5B3Z6g=="
Copy after login

Everything seems to be normal. When encrypting a relatively long json string in the actual project, it was found that null was returned. I traced the openssl_public_encrypt function and returned false at this time. , indicating that encryption failed. After passing in strings of different lengths and testing several times, I found that encryption failure will occur when the string length exceeds 100 characters. After referring to the java encryption example sent by the other party, I found that they need to The string to be encrypted undergoes a split operation, so the following modified version is available:

    /**
     * 用公钥加密
     * @param data
     * @param publicKey
     * @return
     * @throws Exception
     */
    public static String rsaEncrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        // 加密后的字符串
        return Base64.getEncoder().encodeToString(encryptedData);
    }
Copy after login

The current test has not found the encryption failure problem ~ Problem Solving

Recommendation: "

PHP Video tutorial

The above is the detailed content of Record: Solution to PHP rsa encryption processing failure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template