C# RSA with no padding

后端 未结 2 1851
-上瘾入骨i
-上瘾入骨i 2021-02-06 16:28

I\'m busy trying to port Java code that looks like this

        Cipher rsa = Cipher.getInstance(\"RSA/ECB/nopadding\");
        rsa.init(Cipher.DECRYPT_MODE, RSA         


        
2条回答
  •  走了就别回头了
    2021-02-06 17:13

    BouncyCastle will help us to make nopadding RSA encryption.

    public string RsaEncryptWithPublic(string clearText, string publicKey)
        {
            //  analogue of Java:
            //  Cipher rsa = Cipher.getInstance("RSA/ECB/nopadding");
            try
            {
                var bytesToEncrypt = Encoding.ASCII.GetBytes(clearText);
    
                var encryptEngine = new RsaEngine(); // new Pkcs1Encoding (new RsaEngine());
    
    
                using (var txtreader = new StringReader("-----BEGIN PUBLIC KEY-----\n" + publicKey+ "\n-----END PUBLIC KEY-----"))
                {
                    var keyParameter = (AsymmetricKeyParameter)new PemReader(txtreader).ReadObject();
    
                    encryptEngine.Init(true, keyParameter);
                }
    
                var encrypted = Convert.ToBase64String(encryptEngine.ProcessBlock(bytesToEncrypt, 0, bytesToEncrypt.Length));
                return encrypted;
            }
            catch 
            {
    
                return "";
            }
        }
    

    also dont forget to put it at top:

    using Org.BouncyCastle.Crypto;
    using Org.BouncyCastle.Crypto.Engines;
    using Org.BouncyCastle.OpenSsl;
    

提交回复
热议问题