c# uses RSA public key to decrypt


foreword

The new project is connected to a third party, and the user information will be encrypted by rsa in the url anyway. After getting it, I decrypt the user data and only give a public key. They use java and I use c#. Record the decryption process


1. Decryption function

1. Upload the code!

Not much nonsense, just upload the code directly:
pass in the public key and encrypt the string

引入包:
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto.Engines;


    public static string DecryptPublicKeyJava(string publicKeyJava, string data, string encoding = "UTF-8")
    {
    
    
        RsaKeyParameters publicKeyParam = (RsaKeyParameters)PublicKeyFactory.CreateKey(Convert.FromBase64String(publicKeyJava));

        //判断data是否是4的倍数,不是的话后面加=号,再接着判断,直到是4的倍数
        data = IsMultipleOfFour(data);

        byte[] cipherbytes = Convert.FromBase64String(data);
        RsaEngine rsa = new RsaEngine();
        rsa.Init(false, publicKeyParam);//参数true表示加密/false表示解密。
        cipherbytes = rsa.ProcessBlock(cipherbytes, 0, cipherbytes.Length);

        string decryptStr= Encoding.GetEncoding(encoding).GetString(cipherbytes).ToString();
        decryptStr = Regex.Replace(decryptStr, @"[^\u0000-\u007F]", string.Empty);
        decryptStr = decryptStr.Replace("\x01", "");

        Log.WriteToFile("DecryptPublicKeyJava", "decryptStr:"+ decryptStr );
        return decryptStr;
    }

    public static string IsMultipleOfFour(string str)
    {
    
    
        int _cnt = 0;
        while (str.Length % 4 != 0)
        {
    
    
            _cnt++;
            if (_cnt>10)
            {
    
    
                return str;
            }
            str+="=";
        }
        return str.ToString();
    }

2. The incoming string is not in base64 format

There is a little problem with using it, and sometimes an error is reported when decrypting: the string is not in base64 format

I am puzzled.
After asking about the powerful chatgpt, I suddenly realized that the string needs to be a multiple of 4. If it is not, you can use the = sign to supplement it. The above code has already added this function.
insert image description here

2. Online verification

I found several online rsa encryption and decryption sites, and I feel that this is the best:
https://www.bchrt.com/tools/rsa/

Example:
insert image description here

Others: Make a complaint, how does this third party achieve that the encrypted string is not a multiple of 4?


Summarize

Reference: chatgpt, new bing

Guess you like

Origin blog.csdn.net/lyk520dtf/article/details/131088392
Recommended