将代码从 C# 加密到 php(使用 phpseclib)

Encypting code from C# to php (with phpseclib)

我有一个加密 C# 代码,我试图在 PHP 和 phpseclib 中实现它并获得完全相同的结果。是RSA。但我无法完成它。它在 PHP 中为我提供了编码的空字符串。

Public 密钥的格式为:

<?xml version="1.0" encoding="utf-16"?>

<RSAParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Exponent>AQAB</Exponent>
      <Modulus>sMFsHSyxAP5N85yvx/XDs9acJa30qwBjoOdDKvNOHJUYBpspwatkdtErCqM2W6tXH9rbvhIn8/nqW4OqAdLinlgkEJoQ/qnzKjYJhHl4YzKFL6Wp+iFRH6ar6ZWOE87LeNQ0nHwlXKoWkJQKV8NB38XRw6aLvNTj8Po2yaFDbQFztsJ+ILkumRh7Leu77IV+124Swc6JqLRt5z2FnDX869dRi2fqcnFa1EHEBsPEndVd2HSeJUncTQiWJ9SNRU+WLltVVewYiGheqr1ABab++3XM5qrB6fWn/RN9Fcg5nM8fachAFSX2YRrEsg7mcbNALRes6OEdpI0LBdX8Wdw6oQ==</Modulus>
    </RSAParameters>

C#代码是:

public static string Encrypt(string data, string public)
    {
        RSAParameters pubKey = public;
        var csp = new RSACryptoServiceProvider();
        csp.ImportParameters(pubKey);

        var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(data);
        var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);
        return Convert.ToBase64String(bytesCypherText);
    }

在 PHP 中,我正在这样做,但结果是一个空字符串:

$rsa = new Crypt_RSA();
$modulus = new Math_BigInteger(($modulus), 16);
$exponent = new Math_BigInteger(($exponent), 16);
$rsa->loadKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setPublicKey(array('n' => $modulus, 'e' => $exponent));
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$encryptedPassword = $rsa->encrypt($password);

echo $encryptedPassword;

phpseclib 多年来一直支持这种格式的密钥。自 v0.2.2 以来,根据 https://github.com/phpseclib/phpseclib/releases/tag/0.2.2,发布时间不到五年。

无论如何,这对我有用:

<?php
include('Crypt/RSA.php');

$xml = '<RSAParameters xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <Exponent>AQAB</Exponent>
      <Modulus>sMFsHSyxAP5N85yvx/XDs9acJa30qwBjoOdDKvNOHJUYBpspwatkdtErCqM2W6tXH9rbvhIn8/nqW4OqAdLinlgkEJoQ/qnzKjYJhHl4YzKFL6Wp+iFRH6ar6ZWOE87LeNQ0nHwlXKoWkJQKV8NB38XRw6aLvNTj8Po2yaFDbQFztsJ+ILkumRh7Leu77IV+124Swc6JqLRt5z2FnDX869dRi2fqcnFa1EHEBsPEndVd2HSeJUncTQiWJ9SNRU+WLltVVewYiGheqr1ABab++3XM5qrB6fWn/RN9Fcg5nM8fachAFSX2YRrEsg7mcbNALRes6OEdpI0LBdX8Wdw6oQ==</Modulus>
    </RSAParameters>';

$rsa = new Crypt_RSA();
$rsa->loadKey($xml);

$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$encryptedPassword = $rsa->encrypt('password');

echo base64_encode($encryptedPassword);

我不得不从密钥中删除 <?xml version="1.0" encoding="utf-16"?> 位,但除此之外它还有效。