Java & PHP RSA key exchange, signature, sign inspection, encryption, decryption

RSA encryption algorithm is an asymmetric encryption algorithm. In public-key encryption and electronic commerce RSA is widely used. RSA 1977 by the Ronald Rivest (Ron Rivest), Adi Shamir (Adi Shamir) and Leonard Adleman (Leonard Adleman) presented together. At that time the three of them are working at MIT. RSA is the three of them last names beginning with the letter composed pieces together.

RSA is the first relatively complete public key algorithm, it is not only used for encryption, can also be used for digital signatures. This algorithm has withstood years of in-depth cryptographic analysis, although the cryptanalyst can neither prove nor deny the security of RSA, but this just shows that the algorithm has a certain credibility, now it has become the most popular public-key algorithm .

RSA Security based on the difficulty of factoring large integers. Its public and private key pair of functions is a large prime number (decimal number 100 to 200 or more). Difficulty recovering from a public key plaintext and ciphertext is equivalent to the decomposition product of two large prime number (which is recognized math problems).

RSA public key, private key composition, and encryption and decryption equations can be found in the following table:

RSA Demo herein Java part of the code for my project docking third-party companies (do not know where the tools Pa) somewhat chaotic, related to the sample code I posted alone, will give a complete end the file code for your reference .

version

Language version
PHP 7.2.19
Java 1.8.0_231

Key Generation

PHP

  • RSAUtils::resetGenKeyPair
public static function resetGenKeyPair()
{
    $config = array(
        "private_key_bits" => self::PRIVATE_KEY_BITS,
        "private_key_type" => self::KEY_ALGORITHM,
    );

    $openssl = openssl_pkey_new($config);
    openssl_pkey_export($openssl, $privateKey);
    $publicKey = openssl_pkey_get_details($openssl);
    $publicKey = $publicKey["key"];

    self::setGenKeyPair($publicKey, $privateKey);
}

Java

  • RSAUtils.genKeyPair
public static Map<String, Object> genKeyPair() throws Exception {
    KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
    keyPairGen.initialize(1024);
    KeyPair keyPair = keyPairGen.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    Map<String, Object> keyMap = new HashMap<String, Object>(2);
    keyMap.put(PUBLIC_KEY, publicKey);
    keyMap.put(PRIVATE_KEY, privateKey);
    return keyMap;
}

signature

Private key endorsement.

Sometimes because of the different signatures may lead to inconsistent data encoding, it requires PHP and Java both encode data processing.

PHP

  • RSAUtils::sign
public static function sign($dataStr)
{
    $dataStr = self::str2utf8($dataStr);
    $privateKeyId = openssl_get_privatekey(self::$PRIVATE_KEY);
    openssl_sign($dataStr, $sign, $privateKeyId, self::SIGNATURE_ALGORITHM);
    openssl_free_key($privateKeyId);
    return base64_encode($sign);
}

Java

  • RSAUtils.sign
public static String sign(byte[] data, String privateKey) throws Exception {
    byte[] keyBytes = Base64.decode(privateKey);
    PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
    Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
    signature.initSign(privateK);
    signature.update(data);
    return Base64.encodeToString(signature.sign());
}

Check test

Public inspection sign.

PHP

  • RSAUtils::verifySign
public static function verifySign($dataStr, $sign)
{
    $dataStr     = self::str2utf8($dataStr);
    $publicKeyId = openssl_get_publickey(self::$PUBLIC_KEY);
    return (boolean) openssl_verify($dataStr, base64_decode($sign), $publicKeyId, self::SIGNATURE_ALGORITHM);
}

Java

  • RSAUtils.verify
public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
    try {
        byte[] keyBytes = Base64.decode(publicKey);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey publicK = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(publicK);
        signature.update(data);
        return signature.verify(Base64.decode(sign));
    } catch (Exception e) {
        throw e;
    }
}

encryption

Public key encryption

PHP

  • RSAUtils::encryptByPublicKey
public static function encryptByPublicKey($dataStr)
{
    $dataStr     = self::str2utf8($dataStr);
    $publicKeyId = openssl_get_publickey(self::$PUBLIC_KEY);
    $data        = "";

    $dataArray = str_split($dataStr, self::PRIVATE_KEY_BITS / 8 - 11);
    foreach ($dataArray as $value) {
        openssl_public_encrypt($value,$encryptedTemp, $publicKeyId,self::EN_DE_ALGORITHM);
        $data .= $encryptedTemp;
    }
    openssl_free_key($publicKeyId);
    return base64_encode($data);
}

Java

  • RSASignCryptor.encrypt
public static String encrypt(String encryptKey, String plainText) {
    try {
        RSAPublicKey publicKey = (RSAPublicKey) getPublicKey(encryptKey);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] plainData = plainText.getBytes(ENCODING);

        int MAX_ENCRYPT_BLOCK = publicKey.getModulus().bitLength() / 8 - 11;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] cache;
        for (int i = 0, offset = 0, len = plainData.length; offset < len;) {
            if (len - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(plainData, offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(plainData, offset, len - offset);
            }
            out.write(cache, 0, cache.length);
            offset = (++i) * MAX_ENCRYPT_BLOCK;
        }
        byte[] enBytes = out.toByteArray();
        out.close();
        return new String(Base64.encodeBase64(enBytes), ENCODING);
    } catch (Exception e) {
    }
    return null;
}

Private key encryption

PHP

  • RSAUtils::encryptByPrivateKey
public static function encryptByPrivateKey($dataStr)
{
    $dataStr      = self::str2utf8($dataStr);
    $privateKeyId = openssl_get_privatekey(self::$PRIVATE_KEY);
    $data         = "";

    $dataArray = str_split($dataStr, self::PRIVATE_KEY_BITS / 8 - 11);
    foreach ($dataArray as $value) {
        openssl_private_encrypt($value,$encryptedTemp, $privateKeyId,self::EN_DE_ALGORITHM);
        $data .= $encryptedTemp;
    }
    openssl_free_key($privateKeyId);
    return base64_encode($data);
}

Decryption

Public key to decrypt

PHP

  • RSAUtils::decryptByPublicKey
public static function decryptByPublicKey($encryptData) {
    $decrypted   = "";
    $decodeStr   = base64_decode($encryptData);
    $publicKeyId = openssl_get_publickey(self::$PUBLIC_KEY);

    $enArray = str_split($decodeStr, self::PRIVATE_KEY_BITS / 8);

    foreach ($enArray as $value) {
        openssl_public_decrypt($value,$decryptedTemp, $publicKeyId,self::EN_DE_ALGORITHM);
        $decrypted .= $decryptedTemp;
    }
    openssl_free_key($publicKeyId);
    return $decrypted;
}

Private key to decrypt

PHP

  • RSAUtils::decryptByPrivateKey
public static function decryptByPrivateKey($encryptData) {
    $decrypted    = "";
    $decodeStr    = base64_decode($encryptData);
    $privateKeyId = openssl_get_privatekey(self::$PRIVATE_KEY);

    $enArray = str_split($decodeStr, self::PRIVATE_KEY_BITS / 8);

    foreach ($enArray as $value) {
        openssl_private_decrypt($value,$decryptedTemp, $privateKeyId,self::EN_DE_ALGORITHM);
        $decrypted .= $decryptedTemp;
    }
    openssl_free_key($privateKeyId);
    return $decrypted;
}

Java

  • RSASignCryptor.decrypt
public static String decrypt(String decryptKey, String encryptText) throws Exception {
    try {
        RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(decryptKey);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] enData = Base64.decodeBase64(encryptText.getBytes(ENCODING));

        int MAX_DECRYPT_BLOCK = privateKey.getModulus().bitLength() / 8;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] cache;
        for (int i = 0, offset = 0, len = enData.length; offset < len;) {
            if (len - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(enData, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(enData, offset, len - offset);
            }
            out.write(cache, 0, cache.length);
            offset = (++i) * MAX_DECRYPT_BLOCK;
        }
        byte[] deBytes = out.toByteArray();
        out.close();
        return new String(deBytes, ENCODING);
    } catch (Exception e) {
        throw e;
    }
}

Demo

PHP

RSAUtils.php

<?php

/**
 * RSA工具类
 * Class RSAUtils
 * @author dbn
 */
class RSAUtils
{
    /**
     * 签名算法
     */
    const KEY_ALGORITHM       = OPENSSL_KEYTYPE_RSA;
    const SIGNATURE_ALGORITHM = OPENSSL_ALGO_MD5;
    const EN_DE_ALGORITHM     = OPENSSL_PKCS1_PADDING;

    /**
     * 字节数
     */
    const PRIVATE_KEY_BITS = 1024;

    /**
     * 公私钥
     */
    public static $PUBLIC_KEY;
    public static $PRIVATE_KEY;

    public static $PUBLIC_KEY_STR;
    public static $PRIVATE_KEY_STR;

    /**
     * 设置密钥对
     * @param string $publicKey  公钥
     * @param string $privateKey 私钥
     */
    public static function setGenKeyPair($publicKey, $privateKey)
    {
        self::$PUBLIC_KEY  = $publicKey;
        self::$PRIVATE_KEY = $privateKey;

        self::$PUBLIC_KEY_STR  = self::key2str(self::$PUBLIC_KEY);
        self::$PRIVATE_KEY_STR = self::key2str(self::$PRIVATE_KEY);
    }

    /**
     * 重新生成密钥对
     */
    public static function resetGenKeyPair()
    {
        $config = array(
            "private_key_bits" => self::PRIVATE_KEY_BITS,
            "private_key_type" => self::KEY_ALGORITHM,
        );

        $openssl = openssl_pkey_new($config);
        openssl_pkey_export($openssl, $privateKey);
        $publicKey = openssl_pkey_get_details($openssl);
        $publicKey = $publicKey["key"];

        self::setGenKeyPair($publicKey, $privateKey);
    }

    /**
     * 加签
     * @param string $dataStr 数据字符串
     * @return string
     */
    public static function sign($dataStr)
    {
        $dataStr = self::str2utf8($dataStr);
        $privateKeyId = openssl_get_privatekey(self::$PRIVATE_KEY);
        openssl_sign($dataStr, $sign, $privateKeyId, self::SIGNATURE_ALGORITHM);
        openssl_free_key($privateKeyId);
        return base64_encode($sign);
    }

    /**
     * 验签
     * @param string $dataStr 加签原数据字符串
     * @param string $sign 签名
     * @return bool
     */
    public static function verifySign($dataStr, $sign)
    {
        $dataStr     = self::str2utf8($dataStr);
        $publicKeyId = openssl_get_publickey(self::$PUBLIC_KEY);
        return (boolean) openssl_verify($dataStr, base64_decode($sign), $publicKeyId, self::SIGNATURE_ALGORITHM);
    }

    /**
     * 公钥加密
     * @param string $dataStr 加签原数据字符串
     * @return string
     */
    public static function encryptByPublicKey($dataStr)
    {
        $dataStr     = self::str2utf8($dataStr);
        $publicKeyId = openssl_get_publickey(self::$PUBLIC_KEY);
        $data        = "";

        $dataArray = str_split($dataStr, self::PRIVATE_KEY_BITS / 8 - 11);
        foreach ($dataArray as $value) {
            openssl_public_encrypt($value,$encryptedTemp, $publicKeyId,self::EN_DE_ALGORITHM);
            $data .= $encryptedTemp;
        }
        openssl_free_key($publicKeyId);
        return base64_encode($data);
    }

    /**
     * 私钥加密
     * @param string $dataStr 加签原数据字符串
     * @return string
     */
    public static function encryptByPrivateKey($dataStr)
    {
        $dataStr      = self::str2utf8($dataStr);
        $privateKeyId = openssl_get_privatekey(self::$PRIVATE_KEY);
        $data         = "";

        $dataArray = str_split($dataStr, self::PRIVATE_KEY_BITS / 8 - 11);
        foreach ($dataArray as $value) {
            openssl_private_encrypt($value,$encryptedTemp, $privateKeyId,self::EN_DE_ALGORITHM);
            $data .= $encryptedTemp;
        }
        openssl_free_key($privateKeyId);
        return base64_encode($data);
    }

    /**
     * 公钥解密
     * @param string $encryptData 加密数据字符串
     * @return string
     */
    public static function decryptByPublicKey($encryptData) {
        $decrypted   = "";
        $decodeStr   = base64_decode($encryptData);
        $publicKeyId = openssl_get_publickey(self::$PUBLIC_KEY);

        $enArray = str_split($decodeStr, self::PRIVATE_KEY_BITS / 8);

        foreach ($enArray as $value) {
            openssl_public_decrypt($value,$decryptedTemp, $publicKeyId,self::EN_DE_ALGORITHM);
            $decrypted .= $decryptedTemp;
        }
        openssl_free_key($publicKeyId);
        return $decrypted;
    }

    /**
     * 私钥解密
     * @param string $encryptData 加密数据字符串
     * @return string
     */
    public static function decryptByPrivateKey($encryptData) {
        $decrypted    = "";
        $decodeStr    = base64_decode($encryptData);
        $privateKeyId = openssl_get_privatekey(self::$PRIVATE_KEY);

        $enArray = str_split($decodeStr, self::PRIVATE_KEY_BITS / 8);

        foreach ($enArray as $value) {
            openssl_private_decrypt($value,$decryptedTemp, $privateKeyId,self::EN_DE_ALGORITHM);
            $decrypted .= $decryptedTemp;
        }
        openssl_free_key($privateKeyId);
        return $decrypted;
    }

    /**
     * 公私钥转为字符串格式
     * @param $key
     * @return string
     */
    private static function key2str($key)
    {
        $key = preg_replace('/-----.*-----/','', $key);
        $key = preg_replace('/[\n\s]/','', $key);
        return is_string($key) ? $key : '';
    }

    /**
     * 将字符串编码转为 utf8
     * @param $str
     * @return string
     */
    private static function str2utf8($str)
    {
        $encode = mb_detect_encoding($str, array('ASCII', 'UTF-8', 'GB2312', 'GBK', 'BIG5'));
        $str = $str ? $str : mb_convert_encoding($str, 'UTF-8', $encode);
        $str = is_string($str) ? $str : '';
        return $str;
    }
}

Test.php

<?php

require_once dirname(__FILE__) . '/RSAUtils.php';

RSAUtils::resetGenKeyPair();

echo "生成公钥:" . RSAUtils::$PUBLIC_KEY_STR . PHP_EOL;
echo "生成私钥:" . RSAUtils::$PRIVATE_KEY_STR . PHP_EOL;

echo str_repeat("==", 100) . PHP_EOL;

$publicKey = <<<EOF
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyJn4YYj+Ng/xjOPvGrt3MVLZ+
xk3yjqBUu5U5tO1xC1Q/Wae8gWpIC3ipS9UVMCNUOKm2GHdQFI1EXaAu0bRQhBb4
aE5IdXrT9Xoo4Zeuv/ut9UvKEpjBB7Geiy6OvAoA0ROBRLA9/j9W8jZraWiirXRA
xI7ZyqgZSr5lHgJWdwIDAQAB
-----END PUBLIC KEY-----

EOF;

$privateKey = <<<EOF
-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALImfhhiP42D/GM4
+8au3cxUtn7GTfKOoFS7lTm07XELVD9Zp7yBakgLeKlL1RUwI1Q4qbYYd1AUjURd
oC7RtFCEFvhoTkh1etP1eijhl66/+631S8oSmMEHsZ6LLo68CgDRE4FEsD3+P1by
NmtpaKKtdEDEjtnKqBlKvmUeAlZ3AgMBAAECgYB0/En5gSrypyVpktXjFpmXwFlG
zroI+hfXDIdlqaXygdoE777yTpmYTdAifCWlEENi3wKzDUXsVFKf/ktd819QF4gH
Cby8Hlk39Gj1itUJ90V7XZVWgJJYMaudGg4rKa3w+VYhw2fut5EXJ9R6o7rQtp9M
9mlq6NuQIK30GYZEoQJBAN0hh3YYhPmeKLDwGsh/Ys+SbVWsSPkVnu6O9wcMk3JH
4bs/n2+hIPvPTYTHixcO/iMwILKdVWSdn5XtKnXR3zMCQQDOPfM7VJbyZVoe0f8i
AJfRAZ0d0oq/qTL30ypx3P7VltkcfszQH6M1+gapcZ8mCXpeV510V2U3AlsU+vun
S3utAkAE2GM7dzYSsiB6IAi2M/RaT/8NTYUb0Bl3aLKI+QGSE3kivTYlIAa0/cnZ
CvZFPxLaeod84m2okruYcWXoxvx5AkEAqM5J7FDjL8lHBxzoj2Me38JLYCJ40EDj
57Yd8o5owleyosEiUGLkyoQ3ua63DYIKd3eM97GktW6nMDfxjE+bDQJBANcwDRf4
CRW646Y/7kizjVOM4MUiJqAoBC4IEawrk25wfo0gBpBbcl24IOTERLUVtMZvqoc6
mbNoMUny2LuWvVI=
-----END PRIVATE KEY-----

EOF;

RSAUtils::setGenKeyPair($publicKey, $privateKey);

echo "自定义公钥:" . RSAUtils::$PUBLIC_KEY_STR . PHP_EOL;
echo "自定义私钥:" . RSAUtils::$PRIVATE_KEY_STR . PHP_EOL;

echo str_repeat("==", 100) . PHP_EOL;

$data = "{\r\n" . "    \"tenantryId\":\"1548226942116\",\r\n" . "    \"waybillCode\":\"T19000100152750\",\r\n" . "    \"billDate\":\"2019-01-25 16:00:00\",\r\n"
    . "    \"driverContractCode\":\"\",\r\n" . "    \"planStartTime\":\"2019-01-25 16:00:00\",\r\n" . "    \"planEndTime\":\"2019-01-26 16:00:01\",\r\n"
    . "    \"shipperCorporationName\":\"江苏省常隆化工有限公司\",\r\n" . "    \"loadingAddress\":\"发货详细地址\",\r\n" . "    \"loadingLongitude\":\"456456\",\r\n" . "    \"loadingLatitude\":\"123\",\r\n"
    . "    \"shipperPerson\":\"李四\",\r\n" . "    \"shipperPhone\":\"18983746362\",\r\n" . "    \"receiveCorporationName\":\"江苏省智联云物流科技有限公司\",\r\n"
    . "    \"unloadAddress\":\"收货详细地址\",\r\n" . "    \"unloadLongitude\":\"2342\",\r\n" . "    \"unloadLatitude\":\"234\",\r\n" . "    \"receivePerson\":\"唐唐\",\r\n"
    . "    \"receivePhone\":\"18387473723\",\r\n" . "    \"goodsCategory\":\"JXSBDQ\",\r\n" . "    \"goodsName\":\"机床\",\r\n" . "    \"goodsAmount\":\"1\",\r\n"
    . "    \"goodsPacking\":\"MX\",\r\n" . "    \"goodsWeight\":\"1\",\r\n" . "    \"goodsVolume\":\"0\",\r\n" . "    \"plateNo\":\"苏D269ZP\",\r\n" . "    \"truckTonnage\":\"1\",\r\n"
    . "    \"truckLength\":\"1\",\r\n" . "    \"truckBox\":\"GL\",\r\n" . "    \"owner\":\"赵六\",\r\n" . "    \"driverName\":\"王五\",\r\n" . "    \"driverPhone\":\"1234123\",\r\n"
    . "    \"driverLicense\":\"320483198209933456\",\r\n" . "    \"receiptName\":\"张三\",\r\n" . "    \"receiptCard\":\"6230202013315354\",\r\n"
    . "    \"receiptIdentity\":\"320483198209933874\",\r\n" . "    \"receiptPhone\":\"1231231\",\r\n" . "    \"feePrice\":\"50000\",\r\n" . "    \"feeAmount\":\"1.2\",\r\n"
    . "    \"feeUnit\":\"2\",\r\n" . "    \"payFare\":\"50000\",\r\n" . "    \"isPolicy\":\"\",\r\n" . "    \"isLocate\":\"\"\r\n" . "}";

$signData = RSAUtils::sign($data);
echo "签名:" . $signData . PHP_EOL;

$verify = RSAUtils::verifySign($data, $signData);
echo "验签:" . ($verify ? 'true' : 'false') . PHP_EOL;

echo str_repeat("==", 100) . PHP_EOL;


$str = "{\"env\":{\"server_name\":\"loc.test.net\",\"request_uri\":\"\/Test\/test\",\"client_ip\":\"172.18.0.1\",\"request_time\":1573192923,\"request_date\":\"2019-11-08 14:02:03\"},\"params\":{\"app_token\":\"123456789\",\"money\":\"123\",\"bankCard\":\"123123\",\"PHPSESSID\":\"eqc6h0dtg971s8488glelhedsb\"},\"result\":{\"code\":\"201\",\"msg\":\"\u53c2\u6570\u9a8c\u8bc1\u9519\u8bef\",\"result\":{}}}";
echo "加密文字:" . $str . PHP_EOL;

echo str_repeat("==", 100) . PHP_EOL;

$encrypt = RSAUtils::encryptByPublicKey($str);
echo "公钥加密:" . $encrypt . PHP_EOL;
$decrypt = RSAUtils::decryptByPrivateKey($encrypt);
echo "私钥解密:" . $decrypt . PHP_EOL;

echo str_repeat("==", 100) . PHP_EOL;

$encrypt = RSAUtils::encryptByPrivateKey($str);
echo "私钥加密:" . $encrypt . PHP_EOL;
$decrypt = RSAUtils::decryptByPublicKey($encrypt);
echo "公钥解密:" . $decrypt . PHP_EOL;

operation result:

生成公钥:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvhG5CuPcyEROKrZyxlTJDP1iFsGALoZlepcWMkuKbxT2mS5PT11vCIc2tBBF5fTADLaUGguzTRPquXjFgTLTnAYmmjPYXwFKmFyS51Mf0sI3NMwRBwwhjQ4drLG4YH5uypDfq6h3hqj75ER+2/VUBqFdaJI/7m+ht4v+lqTT4oQIDAQAB
生成私钥:MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAK+EbkK49zIRE4qtnLGVMkM/WIWwYAuhmV6lxYyS4pvFPaZLk9PXW8Ihza0EEXl9MAMtpQaC7NNE+q5eMWBMtOcBiaaM9hfAUqYXJLnUx/Swjc0zBEHDCGNDh2ssbhgfm7KkN+rqHeGqPvkRH7b9VQGoV1okj/ub6G3i/6WpNPihAgMBAAECgYEAop6PzlAz8HZz5axfnwV+EWJysUMuafhq8o+jDlDVlr/UE+y4ZbGGecL6HpDDZA3CW1+CJBtQM5sYrE/nbbMEc+4pI7mKf9Vct2GULj0lfhhZVc8pPH8I/wsZOS9cbdHojZc2XGnVI/+UoAtKH9SKtR8tcQNP2Sc4sxAhxkftL1UCQQDlaYNmTFusfWlw6YJhVDjBV/6qaOK1nFUWGhNMOG6OdhGZOoqp/nNPX2bU/Qw7eG9rgIEZkwvLYk7XEsgor8Q7AkEAw9vlxYVocwt9UlSZBDFfiYF1RTFcfxM3JNrYJ1ojc0MrI56uj9uUVGdBqLN3FltDep0uNiKc/agn57Xg3Qr00wJBAI38uhjslaiyjjoWLF309JOl1La/5+Ejev4M8XixTKvbo5TEyOHh3Jh5oXmdjJ6aMcvFYyHjAt/EXqt6smuMLdUCQHWT2hFEsFp4KEi3jpCMz0yuEedy5ZNHxs/yLNca7rMwPIKKrUKhUB+HSUxsSG58ZTsDhw1qpBJG04Xvksk/3Y8CQQCV359laYTqNdnVa5RO2335TyEZyPJNt065XoU+8ruDIsJ+D4Ep54idv/ZRObnu8qt7/sU3l7cQRnQm+WzvKDNE
========================================================================================================================================================================================================
自定义公钥:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCyJn4YYj+Ng/xjOPvGrt3MVLZ+xk3yjqBUu5U5tO1xC1Q/Wae8gWpIC3ipS9UVMCNUOKm2GHdQFI1EXaAu0bRQhBb4aE5IdXrT9Xoo4Zeuv/ut9UvKEpjBB7Geiy6OvAoA0ROBRLA9/j9W8jZraWiirXRAxI7ZyqgZSr5lHgJWdwIDAQAB
自定义私钥:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALImfhhiP42D/GM4+8au3cxUtn7GTfKOoFS7lTm07XELVD9Zp7yBakgLeKlL1RUwI1Q4qbYYd1AUjURdoC7RtFCEFvhoTkh1etP1eijhl66/+631S8oSmMEHsZ6LLo68CgDRE4FEsD3+P1byNmtpaKKtdEDEjtnKqBlKvmUeAlZ3AgMBAAECgYB0/En5gSrypyVpktXjFpmXwFlGzroI+hfXDIdlqaXygdoE777yTpmYTdAifCWlEENi3wKzDUXsVFKf/ktd819QF4gHCby8Hlk39Gj1itUJ90V7XZVWgJJYMaudGg4rKa3w+VYhw2fut5EXJ9R6o7rQtp9M9mlq6NuQIK30GYZEoQJBAN0hh3YYhPmeKLDwGsh/Ys+SbVWsSPkVnu6O9wcMk3JH4bs/n2+hIPvPTYTHixcO/iMwILKdVWSdn5XtKnXR3zMCQQDOPfM7VJbyZVoe0f8iAJfRAZ0d0oq/qTL30ypx3P7VltkcfszQH6M1+gapcZ8mCXpeV510V2U3AlsU+vunS3utAkAE2GM7dzYSsiB6IAi2M/RaT/8NTYUb0Bl3aLKI+QGSE3kivTYlIAa0/cnZCvZFPxLaeod84m2okruYcWXoxvx5AkEAqM5J7FDjL8lHBxzoj2Me38JLYCJ40EDj57Yd8o5owleyosEiUGLkyoQ3ua63DYIKd3eM97GktW6nMDfxjE+bDQJBANcwDRf4CRW646Y/7kizjVOM4MUiJqAoBC4IEawrk25wfo0gBpBbcl24IOTERLUVtMZvqoc6mbNoMUny2LuWvVI=
========================================================================================================================================================================================================
签名:FibUiFnO6bGKwua5bV2k1AQPIFTms6REYSybBsTEUlXyo2Tc79UZ0ett1pNUU3qhhsCOeBTCdKlI5j/aygpzkYANv7Ff2eT/Jd1gRG3X+XGX1bQpRm/6CNesVV99EPLfUMXWmulGX2FxMY/7XY49H7jtJcbUnyZjjHR2MEWGbHQ=
验签:true
========================================================================================================================================================================================================
加密文字:{"env":{"server_name":"loc.test.net","request_uri":"\/Test\/test","client_ip":"172.18.0.1","request_time":1573192923,"request_date":"2019-11-08 14:02:03"},"params":{"app_token":"123456789","money":"123","bankCard":"123123","PHPSESSID":"eqc6h0dtg971s8488glelhedsb"},"result":{"code":"201","msg":"\u53c2\u6570\u9a8c\u8bc1\u9519\u8bef","result":{}}}
========================================================================================================================================================================================================
公钥加密:BLF/zEOuHoLHDFM9aNXu0I5kke1L6AiBAyBjFycFpQPiPctGXzP2m0/xWTq7H6jqbTvpvw5QvvJK04u2PMhvxaprmXEQtE7dsOj4D/K2UoSgD6zaPcxEaS6ToDvJeOvtRAQCyAeXQhFIdeM8roziVr8O/dKQ0HxG/Yah2Ap+9Ctvofu2HlSmxjsHVCFg+WrA1bbSR20Ukm4NEu3gYI2eWRkv0LkXbSFkAsWs8/naA/P/VCMtU/0MShYd6cXEEhknKev1WLB97LMl/840MJEaapZa25+APO/HAfjTUMsCW+yZz8944JCUXdjVJ43NsR4m6Ja/t2cPqE5iaKFmrMkg+nSTwp17IHOcWCtImgMtt0CtyPixa5tylLFf56Uy+GUkYLSwST+RyvecFzCLYnnJwo2po82B8Cs6LGUCMKjs0SOwNsGVqD2MnOuAn2UbzRstS8866O/B+YuYKQdDjoIFY25f7mW1Vl+BtxwPL0GbdptRJVMtZxBvBxMJigXuOEo4
私钥解密:{"env":{"server_name":"loc.test.net","request_uri":"\/Test\/test","client_ip":"172.18.0.1","request_time":1573192923,"request_date":"2019-11-08 14:02:03"},"params":{"app_token":"123456789","money":"123","bankCard":"123123","PHPSESSID":"eqc6h0dtg971s8488glelhedsb"},"result":{"code":"201","msg":"\u53c2\u6570\u9a8c\u8bc1\u9519\u8bef","result":{}}}
========================================================================================================================================================================================================
私钥加密:Mwjypj/tbtfjLz+qbUKgs5cOOutmvHdwXQnAuYovGyx6yFE3mcBUeqB+Z+uMJUaNuH/qZGevaxAvkGesotnIIL6YmobxtA0apxMCfKGX+BV+7n/6t4G68gj0Yy9ng54c5CdjEZmxull7iKl5zmsUO5PIxDBiWKYblpgItwnuuz0xMKe2opPrmP0BBDFXGyBmGBjBFyORSEJ5brX0+w6EU/mbFGnAjaEOsQDLFrO7O0Uh0l4WUvz7NKxxcHV62a2HWgW/wXOyKxmf9Z6bdTIQFXXYBynG+D5JR6EY/rIHj/dMZIvPLG+b4UZNwjLU4QhM2VL1TDUNV8hJDQQdxbeQrKzUq3Z089H/3VWff/hHtq2hh5rtIIG0Buo54P7Gjqs3MO5ursDWq54NBltVnuSJpi+4+zAkWTbMMmJLjtRuFJ6sc5gFjKW0ovLDG/4RcKZ0a1wj3nfLoL/HU5JIV5XYUQLX8dEkM9XpakzsU7UbLrbBRszHDgOg6laUlVLIWe/A
公钥解密:{"env":{"server_name":"loc.test.net","request_uri":"\/Test\/test","client_ip":"172.18.0.1","request_time":1573192923,"request_date":"2019-11-08 14:02:03"},"params":{"app_token":"123456789","money":"123","bankCard":"123123","PHPSESSID":"eqc6h0dtg971s8488glelhedsb"},"result":{"code":"201","msg":"\u53c2\u6570\u9a8c\u8bc1\u9519\u8bef","result":{}}}

Java

RSAUtils.java

package com.localhost;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

import org.apache.shiro.codec.Base64;

/**
 * @Title RSAUtils.java
 * @Description RSA工具类
 * @Create DateTime: 2018年10月11日 下午14:00:00
 *
 * @author wangxiaohui
 *
 */
public class RSAUtils {

    /**
     * 加密算法RSA
     */

    /**
     * 签名算法
     */
    public static final String KEY_ALGORITHM = "RSA";

    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * <p>
     * 生成密钥对(公钥和私钥)
     * </p>
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Object> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, Object> keyMap = new HashMap<String, Object>(2);
        keyMap.put(PUBLIC_KEY, publicKey);
        keyMap.put(PRIVATE_KEY, privateKey);
        return keyMap;
    }

    /**
     * <p>
     * 用私钥对信息生成数字签名
     * </p>
     *
     * @param data
     *            已加密数据
     * @param privateKey
     *            私钥(BASE64编码)
     *
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(privateK);
        signature.update(data);
        return Base64.encodeToString(signature.sign());
    }

    /** */
    /**
     * <p>
     * 校验数字签名
     * </p>
     *
     * @param data
     *            已加密数据
     * @param publicKey
     *            公钥(BASE64编码)
     * @param sign
     *            数字签名
     *
     * @return
     * @throws Exception
     *
     */
    public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
        try {
            byte[] keyBytes = Base64.decode(publicKey);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicK);
            signature.update(data);
            return signature.verify(Base64.decode(sign));
        } catch (Exception e) {
            throw e;
        }
    }

    /** */
    /**
     * <P>
     * 私钥解密
     * </p>
     *
     * @param encryptedData
     *            已加密数据
     * @param privateKey
     *            私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    /** */
    /**
     * <p>
     * 公钥解密
     * </p>
     *
     * @param encryptedData
     *            已加密数据
     * @param publicKey
     *            公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
        byte[] keyBytes = Base64.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
        int inputLen = encryptedData.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decryptedData = out.toByteArray();
        out.close();
        return decryptedData;
    }

    public static String encryptByPublicKey(String str, String publicKey) throws Exception {
        return new String((encryptByPublicKey(str.getBytes(), publicKey)), "utf-8");
    }

    public static String decryptByPrivateKey(String str, String privateKey) throws Exception {
        return new String(decryptByPrivateKey(str.getBytes(), privateKey), "utf-8");
    }

    /**
     * <p>
     * 公钥加密
     * </p>
     *
     * @param data
     *            源数据
     * @param publicKey
     *            公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
        byte[] keyBytes = Base64.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
        int inputLen = data.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, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * <p>
     * 私钥加密
     * </p>
     *
     * @param data
     *            源数据
     * @param privateKey
     *            私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
        byte[] keyBytes = Base64.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
        int inputLen = data.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, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }

    /**
     * <p>
     * 获取私钥
     * </p>
     *
     * @param keyMap
     *            密钥对
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return Base64.encodeToString(key.getEncoded());
    }

    /**
     * <p>
     * 获取公钥
     * </p>
     *
     * @param keyMap
     *            密钥对
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
        Key key = (Key) keyMap.get(PUBLIC_KEY);
        return Base64.encodeToString(key.getEncoded());
    }

}

RsaSignCryptor.java

package com.localhost;

import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Map;
import java.util.TreeMap;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Title RSASignCryptor.java
 * @Description RSA加密工具类
 * @Create DateTime: 2018年10月11日 下午14:00:00
 * 
 * @author wangxiaohui
 * 
 */
public class RSASignCryptor {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "SHA1WithRSA";
    public static final String ENCODING = "utf-8";
    public static final String X509 = "X.509";
    // private static final int MAX_ENCRYPT_BLOCK = 117; //RSA最大加密明文大小
    // private static final int MAX_DECRYPT_BLOCK = 128; //RSA最大解密密文大小

    public static PrivateKey getPrivateKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(ENCODING));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        return privateKey;
    }

    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes = Base64.decodeBase64(key.getBytes(ENCODING));
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(keyBytes));
        return pubKey;
    }

    public String getSignData(Map<String, String> params, String sep) {
        if (params instanceof TreeMap) {
            StringBuilder builder = new StringBuilder();
            boolean isFirst = true;
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (StringUtils.isEmpty(entry.getKey()) || StringUtils.isEmpty(entry.getValue())) {
                    continue;
                }
                if (!isFirst) {
                    builder.append(sep);
                }
                builder.append(entry.getKey()).append("=").append(entry.getValue());
                isFirst = false;
            }
            return builder.toString();
        } else {
            Map<String, String> sortedMap = new TreeMap<String, String>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                sortedMap.put(entry.getKey(), entry.getValue());
            }
            return getSignData(sortedMap, sep);
        }
    }

    public static String sign(String signData, String signKey) {
        String ret = null;
        try {
            PrivateKey priKey = getPrivateKey(signKey);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(priKey);
            signature.update(signData.getBytes(ENCODING));
            byte[] signed = signature.sign();
            // ret = new String(UrlBase64.encode(signed), ENCODING);
            ret = new String(Base64.encodeBase64(signed), ENCODING);
        } catch (Exception e) {
        }
        return ret;
    }

    public static boolean verifySign(String signData, String signKey, String sign) {
        try {
            PublicKey pubKey = getPublicKey(signKey);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(pubKey);
            signature.update(signData.getBytes(ENCODING));
            return signature.verify(Base64.decodeBase64(sign.getBytes(ENCODING)));
        } catch (Exception e) {
        }
        return false;
    }

    public static String encrypt(String encryptKey, String plainText) {
        try {
            RSAPublicKey publicKey = (RSAPublicKey) getPublicKey(encryptKey);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            byte[] plainData = plainText.getBytes(ENCODING);

            int MAX_ENCRYPT_BLOCK = publicKey.getModulus().bitLength() / 8 - 11;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] cache;
            for (int i = 0, offset = 0, len = plainData.length; offset < len;) {
                if (len - offset > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(plainData, offset, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(plainData, offset, len - offset);
                }
                out.write(cache, 0, cache.length);
                offset = (++i) * MAX_ENCRYPT_BLOCK;
            }
            byte[] enBytes = out.toByteArray();
            out.close();
            return new String(Base64.encodeBase64(enBytes), ENCODING);
        } catch (Exception e) {
        }
        return null;
    }

    public static String decrypt(String decryptKey, String encryptText) throws Exception {
        try {
            RSAPrivateKey privateKey = (RSAPrivateKey) getPrivateKey(decryptKey);
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] enData = Base64.decodeBase64(encryptText.getBytes(ENCODING));

            int MAX_DECRYPT_BLOCK = privateKey.getModulus().bitLength() / 8;
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] cache;
            for (int i = 0, offset = 0, len = enData.length; offset < len;) {
                if (len - offset > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(enData, offset, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(enData, offset, len - offset);
                }
                out.write(cache, 0, cache.length);
                offset = (++i) * MAX_DECRYPT_BLOCK;
            }
            byte[] deBytes = out.toByteArray();
            out.close();
            return new String(deBytes, ENCODING);
        } catch (Exception e) {
            throw e;
        }
    }
}

Guess you like

Origin www.cnblogs.com/bndong/p/11842135.html