【问题标题】:How to code public key encryption logic in php given sample java logic? [closed]给定示例 java 逻辑,如何在 php 中编写公钥加密逻辑? [关闭]
【发布时间】:2020-02-19 02:31:50
【问题描述】:

我有一个使用 php 中的公钥对加密逻辑进行编码的项目。 给定以下示例 Java 代码,您如何在 php 中对其进行编码? 规范文档说要使用 RSA(2048 位)加密源。

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import org.apache.commons.codec.binary.Base64;
import org.json.JSONObject;

//some other codes...

String PUBLIC_KEY = "";
Map<String, String> map = new HashMap<>();
String data = new JSONObject(map).toString();

//generating public key object
byte[] buffer = Base64.decodeBase64(PUBLIC_KEY.getBytes());
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PublicKey publicKey = keyFactory.generatePublic(keySpec);
//encryption data
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedByte = cipher.doFinal(data.getBytes());
//base 64
String encrypted = Base64.encodeToString(encryptedByte, Base64.DEFAULT);
return encrypted;

【问题讨论】:

  • StackOverflow 不是代码编写服务 - 展示您解决问题的尝试。

标签: java php laravel encryption rsa


【解决方案1】:

使用模块 phpseclib\Crypt\RSA 自己解决了 php 转换

    $token = file_get_contents($path);
    $base64_decoded = base64_decode($token);
    $pubKey = new RSA();
    $pubKey->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
    $pubKey->loadKey($base64_decoded);
    $crypted = $pubKey->encrypt($json);
    return base64_encode($crypted);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多