简体   繁体   English

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

[英]RSA encrypt by PHP and decrypt by C#

I'm trying to encryption and decrpytion process between C# and PHP. 我正在尝试在C#和PHP之间进行加密和解密过程。

My C# code: 我的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;
}

and my PHP: lib( https://github.com/membersuite/sdk-php/blob/master/APISample/SSOWithSDK/phpseclib/Crypt/RSA_XML.php ) 和我的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)));

code after PHP encrypt cant decrypt by c# code. PHP加密后的C#代码无法用C#代码解密。 anyone can help? 有人可以帮忙吗?

Although Microsoft uses little endian notation for numbers, RSA has been defined by PKCS#1 / RFC 3447 . 尽管Microsoft对数字使用很少的字节序表示法,但RSA已由PKCS#1 / RFC 3447定义。 That explicitly defines how to do padding and such, but it also defines how the resulting octet string should look like using I2OSP or the integer-to-octet-string primitive. 这明确定义了如何进行填充等操作,但同时也定义了使用I2OSP或整数到八位位组字符串原语生成的八位位组字符串的外观。 This primitive specifies the output as fixed size (key size) byte array in big endian format . 此原语将输出指定为big endian格式的固定大小(键大小)字节数组。 This is also the encoding that PHP uses, so you should not reverse the output. 这也是PHP使用的编码,因此您不应该反转输出。

In other words, you should not have to use strrev . 换句话说,您不必使用strrev

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM