[Python] C# to Python RSA implement

Discussão em 'Python' iniciado por Stack, Fevereiro 6, 2025.

  1. Stack

    Stack Membro Participativo

    Just trying to rewrite this c# code to python. Server send public key(modulus, exponent), need to encrypt it with pkcs1 padding.

    using (TcpClient client = new TcpClient())
    {
    await client.ConnectAsync(ip, port);
    using (NetworkStream stream = client.GetStream())
    {
    await App.SendCmdToServer(stream, "auth", this.Ver.ToString().Split('.', StringSplitOptions.None));

    byte[] modulus = new byte[256];
    int num2 = await stream.ReadAsync(modulus, 0, modulus.Length);
    byte[] exponent = new byte[3];
    int num3 = await stream.ReadAsync(exponent, 0, exponent.Length);

    this.ServerRsa = RSA.Create();
    this.ServerRsa.ImportParameters(new RSAParameters()
    {
    Modulus = modulus,
    Exponent = exponent
    });

    using (MemoryStream data = new MemoryStream())
    {
    using (BinaryWriter writer = new BinaryWriter((Stream) data))
    {
    writer.Write(string1);
    writer.Write(string2);
    await App.SendDataToServer(stream, this.ServerRsa.Encrypt(data.ToArray(), RSAEncryptionPadding.Pkcs1));
    }
    }
    }
    }


    Everything works fine, except encrypted result by python. I've tried with rsa and pycryptodome, no luck at all, server returns reject. Tried something like this (rsa)

    server_rsa = rsa.newkeys(2048)[0]
    server_rsa.n = int.from_bytes(modulus, byteorder='big')
    server_rsa.e = int.from_bytes(exponent, byteorder='big')
    data = (string1 + string2).encode()
    encrypted_data = rsa.encrypt(data, server_rsa)


    or this (pycryptodome)

    pubkey = construct((int.from_bytes(modulus, 'big'), int.from_bytes(exponent, 'big')))
    cipher = PKCS1_v1_5.new(pubkey)
    encrypted_data = cipher.encrypt(data)


    Is there some special python RSA implementation, that just not working with C#, or vice versa?

    Continue reading...

Compartilhe esta Página