RSA通过PHP加密并通过C#解密

时间:2015-03-18 08:32:05

标签: c# php rsa phpseclib

我尝试在C#和PHP之间进行加密和解密过程。

我的C#代码:

this.EncryptData("123456", 1024, this.PublicKey);

public byte[] Encrypt(byte[] byte_0, int keysize, string publicKey)
{
    byte[] numArray;    
    using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(keysize))
    {
        rSACryptoServiceProvider.FromXmlString(publicKey);
        numArray = rSACryptoServiceProvider.Encrypt(byte_0, this.bool_0);
    }
    return numArray;
}

public string EncryptData(string string_0, int keysize, string publicKey)
{
    string base64String;
    try
    {
        byte[] numArray = this.Encrypt(Encoding.UTF8.GetBytes(string_0), keysize, publicKey);
        base64String = Convert.ToBase64String(numArray);
    }
    catch (Exception exception)
    {
        base64String = string.Empty;
    }
    return base64String;
}
public byte[] Decrypt(byte[] byte_0, int keysize, string Key)
{
    byte[] numArray;    
    using (RSACryptoServiceProvider rSACryptoServiceProvider = new RSACryptoServiceProvider(keysize))
    {
        rSACryptoServiceProvider.FromXmlString(Key);
        numArray = rSACryptoServiceProvider.Decrypt(byte_0, this.bool_0);
    }
    return numArray;
}

public string DecryptData(string string_0, int keysize, string Key)
{
    string str;
    try
    {
        byte[] numArray = this.Decrypt(Convert.FromBase64String(string_0), keysize, Key);
        str = Encoding.UTF8.GetString(numArray);
    }
    catch (Exception exception)
    {
        str = string.Empty;
    }
    return str;
}

和我的PHP:lib(https://github.com/membersuite/sdk-php/blob/master/APISample/SSOWithSDK/phpseclib/Crypt/RSA_XML.php

$rsa = new Crypt_RSA_XML();
$plaintext = '123456';
$rsa->loadKeyfromXML($publicKey);
$ciphertext = base64_encode(strrev($rsa->encrypt($plaintext)));
PHP加密后的代码不能通过c#代码解密。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:1)

虽然Microsoft对数字使用小端符号,但RSA已由PKCS#1 / RFC 3447定义。这明确定义了如何进行填充等,但它也定义了使用I2OSP或整数到八位字符串原语的结果八位字节串的外观。此原语将输出指定为大端格式中的固定大小(密钥大小)字节数组。这也是PHP使用的编码,因此您不应该反转输出。

换句话说,您不必使用strrev