Java RSA to PHP phpseclib RSA



有一个我正在处理的付款网关,并且他们有一个正在工作的Java演示,但是我想在PHP中实现此操作。

通过使用随机生成的密钥,使用3DE来加密付款网关。该密钥通过使用付款网关的公共密钥对RSA进行加密。

问题是,当我使用PHP脚本在该密钥上进行RSA加密时,付款网关无法正确提取密钥,显然PHP上的RSA加密无法正常工作...

这是RSA加密的Java版本:

public static byte[] encrypt(byte[] data, String pubKey64) {
    try {
         byte[] key = Toolkit.base64Decode(pubKey64);
         KeyFactory rsaKeyFac = KeyFactory.getInstance("RSA");
         X509EncodedKeySpec keySpec = new X509EncodedKeySpec(key);
         RSAPublicKey pbk = (RSAPublicKey) rsaKeyFac.generatePublic(keySpec);
         System.out.println("MODE:"+Cipher.ENCRYPT_MODE);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1PADDING");
        cipher.init(Cipher.ENCRYPT_MODE, pbk);
        byte[] encDate = cipher.doFinal(data);
        return encDate;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

,我在PHP脚本上提出了什么:

use phpseclibCryptRSA as RSA;


$PUB_KEY = '-----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDJ1fKGMV/yOUnY1ysFCk0yPP4bfOolC/nTAyHmoser+1yzeLtyYsfitYonFIsXBKoAYwSAhNE+ZSdXZs4A5zt4EKoU+T3IoByCoKgvpCuOx8rgIAqC3O/95pGb9n6rKHR2sz5EPT0aBUUDAB2FJYjA9Sy+kURxa52EOtRKolSmEwIDAQAB
-----END PUBLIC KEY-----';
$PAYLOAD = 'b78850d2f35108b4bc4e7a41';
function encrypt($key,$payload){
    $rsa = new RSA();
    $rsa->loadKey($key); // public key
    $rsa->setEncryptionMode(2);
    $ciphertext = $rsa->encrypt($payload);
    return base64_encode($ciphertext);
}

Java版本使用的是PKCSpadding,因此我将Phpseclib上的模式设置为2是PKCSpadding,但仍然无法使用。我错过了什么吗?有人可以为我指出吗?

更新:

不确定这是否是引起它的原因,但我删除了" -----开始公共密钥------"one_answers" -----结束公共密钥----"部分,工作。

感谢大家的帮助。

在开始加密过程之前尝试进行define('CRYPT_RSA_PKCS15_COMPAT', true);

引用phpseclib 2.0的rsa.php:

/**
 * RSAES-PKCS1-V1_5-DECRYPT
 *
 * See {@link http://tools.ietf.org/html/rfc3447#section-7.2.2 RFC3447#section-7.2.2}.
 *
 * For compatibility purposes, this function departs slightly from the description given in RFC3447.
 * The reason being that RFC2313#section-8.1 (PKCS#1 v1.5) states that ciphertext's encrypted by the
 * private key should have the second byte set to either 0 or 1 and that ciphertext's encrypted by the
 * public key should have the second byte set to 2.  In RFC3447 (PKCS#1 v2.1), the second byte is supposed
 * to be 2 regardless of which key is used.  For compatibility purposes, we'll just check to make sure the
 * second byte is 2 or less.  If it is, we'll accept the decrypted string as valid.
 *
 * As a consequence of this, a private key encrypted ciphertext produced with phpseclibCryptRSA may not decrypt
 * with a strictly PKCS#1 v1.5 compliant RSA implementation.  Public key encrypted ciphertext's should but
 * not private key encrypted ciphertext's.
 *
 * @access private
 * @param string $c
 * @return string
 */

最新更新