Java到PHP - X509EncodedKeySpec的函数

时间:2014-04-04 08:45:54

标签: java php rsa x509 phpseclib

我使用基本64格式的公钥来获取RSA加密的Java示例代码。现在我想在PHP中转换相同的东西。我试图转换,但有些类让我困惑。这是java示例代码。

public static String encrypt(String msg, String fileName) throws Exception {
    try {
        Cipher cipher = Cipher.getInstance("RSA");
        RSAPublicKey cryptPublicKey = readPublicKeyFromFile(fileName);
        System.out.println("public "+cryptPublicKey);
        cipher.init(1, cryptPublicKey);
        String tempStr = msg;
        int modulus = tempStr.length() / 8;
        if (modulus != 0) {
            for (int i = modulus; i < 8; i++)
                tempStr = tempStr + " ";
        }
        byte plainData[] = tempStr.getBytes();
        byte binaryCryptData[] = cipher.doFinal(plainData);
        BASE64Encoder encoder = new BASE64Encoder();
        String encData = encoder.encode(binaryCryptData);
        msg = encData;
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return msg;
}

private static RSAPublicKey readPublicKeyFromFile(String fileName) throws Exception {
    RSAPublicKey cryptPublicKey = null;
    try {
        KeyFactory keyFac = KeyFactory.getInstance("RSA");
        FileInputStream fis = new FileInputStream(fileName);
        byte cryptKey[] = new byte[fis.available()];
        fis.read(cryptKey);
        fis.close();
        cryptKey = (new BASE64Decoder()).decodeBuffer(new String(cryptKey));
        X509EncodedKeySpec encodedKeySpec = new X509EncodedKeySpec(cryptKey);
        cryptPublicKey = (RSAPublicKey) keyFac.translateKey(keyFac.generatePublic(encodedKeySpec));
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return cryptPublicKey;
}

现在这就是我试图在PHP中实现同样的东西:

$keyData =base64_decode(file_get_contents($configValues['metPubKey']));

print_r($keyData);
$rsa = new Crypt_RSA();

try{
    $rsa->loadKey($keyData); // public key
    $encryptedToken = base64_encode($rsa->encrypt($token));
}catch(Exception $e){
    die;
}

在Java代码中,X509EncodedKeySpec函数中有readPublicKeyFromFile个类,它返回公钥。我不确定我应该在PHP中使用什么。而且看起来像PHP脚本与Java代码不匹配。对此有何帮助?

1 个答案:

答案 0 :(得分:0)

请在PHP中尝试以下代码,它对我有用。

diag_kind

十六进制至字节:

use phpseclib\Crypt\RSA;

        $key = base64_decode(file_get_contents('PATH_TO_PUBLIC_FILE'));
        $rsa = new RSA();
        $rsa->setEncryptionMode(RSA::ENCRYPTION_PKCS1);
        $rsa->loadKey($key);
        $rsa->setPublicKey($key);
        $cipher = 'xxxx';
        $data = $this->hex2bin($cipher);
        $plaintext = $rsa->decrypt($data);
        echo '<pre>';
        print_r($plaintext);
        echo '</pre>';die;