gpt4 book ai didi

Java RSA 到 PHP phpseclib RSA

转载 作者:行者123 更新时间:2023-12-01 09:06:58 28 4
gpt4 key购买 nike

我正在开发一个支付网关,他们有一个正在运行的 Java 演示,但我想用 php 来实现它。

支付网关使用 3DES 和随机生成的 key 来加密有效负载。该 key 使用支付网关的公钥通过 RSA 进行加密。

问题是当我使用 php 脚本对该 key 进行 RSA 加密时,支付网关无法正确提取 key ,并且显然 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 phpseclib\Crypt\RSA 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,但它仍然无法工作。我错过了什么吗?谁能帮我指点一下吗?

更新:

不确定这是否是导致它的原因,但我删除了“-----BEGIN PUBLIC KEY-----”和“-----END PUBLIC KEY ----”部分,它工作了。

感谢大家的帮助。

最佳答案

在开始加密过程之前,尝试执行 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 \phpseclib\Crypt\RSA 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
*/

关于Java RSA 到 PHP phpseclib RSA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41193731/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com