none
C# Equivalent code of Java RRS feed

  • Question

  • Hi!

    I'm unable to convert the Java encryption code to C#.

    package com.avenues.lib.utility;
    
    import java.security.KeyFactory;
    import java.security.PublicKey;
    import java.security.spec.X509EncodedKeySpec;
    
    import javax.crypto.Cipher;
    
    import android.util.Base64;
    
    
    public class RSAUtility {
    	public static String encrypt(String plainText, String key){
    		try{
    			PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.decode(key, Base64.DEFAULT)));
    		    Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
    		    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    		    return Base64.encodeToString(cipher.doFinal(plainText.getBytes("UTF-8")),Base64.DEFAULT);
    		}catch (Exception e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    }


    Thursday, January 10, 2019 3:55 PM

All replies

  • Hi Jeetendra,

    Thank you for posting here.

    According to your description, you want to convert the Java encryption code to C#.

    Please refer to the following code.

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace test1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string publicKey = "a383a2916281721498ff28226f851613bab6f89eb0536e9f237e158596d3b012e5707eba9f2a2963faca63fcb10f5de79caf246c1f587ee6e8f895fd848f2da5aba9d71af4dd8d06e99ff3729631626ed3f3202e56962957c0110a99d2b3893feb148291e09b54fe7df121751fb8bb589576542321b4f548be06b9845ebc6bbef1427741c00b632c05854146b597fdef5a89ace1556a769c5eaff8fc0589e7ad4adb2e2a929969c77f395b2f5a276a9389d1f43c061c9459a65b77bcd581c107aa8424223a0b44ee52582362cc96b90eea071a0dda5e9cb8fd5c9fd4ac86e177c07d79071788cb08231240dc1c9169af2629ecec31751069f0c7ccc1c1752303";
                string plaintext= "Test123";
                string m=RSAUtility.encrypt(plaintext,publicKey);
                Console.WriteLine(m);
                Console.ReadKey();
            }
        }
        public class RSAUtility
        {
           
            public static string encrypt(string plainText,string key)
            {
                try
                {
                    using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
                    {
                        RSAParameters rsp = new RSAParameters
                        {
                            Modulus = HexStringToByteArray(key),
                             Exponent = HexStringToByteArray("01000122")
                        };
                        rsa.ImportParameters(rsp);
                        byte[] encryptdata= rsa.Encrypt(Encoding.UTF8.GetBytes(plainText), false);
                        return Convert.ToBase64String(encryptdata);
                    }
                }
                catch (CryptographicException e)
                {
                    Console.WriteLine(e.ToString());
                }
                return null;
            }
            public static byte[] HexStringToByteArray(string hexString)
            {
                MemoryStream stream = new MemoryStream(hexString.Length / 2);
    
                for (int i = 0; i < hexString.Length; i += 2)
                {
                    stream.WriteByte(byte.Parse(hexString.Substring(i, 2), System.Globalization.NumberStyles.AllowHexSpecifier));
                }
                return stream.ToArray();
            }
        }
    
    }
    

    Test Result: 

    Hope my suggestion could be helpful.

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 11, 2019 6:44 AM
    Moderator
  • Thank you for the response. I appreciate your help. But the code you gave is not working.

    Let me give some context to it. We are integrating CCAvenue Payment Gateway in Xamarin.Android App. Before redirecting to payment gateway we have to encrypt the amount and currency using a RSA key generated (a new key is generated for every transaction) on payment gateway server. The encryption logic given CCAvenue is in Java.

    I'm not good with encryption, but I think we have to extract the public key the RSA key provided by payment gateway.

    Key format:

    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAieittffvHkrzV+VsKu3FYpnRs/+Lr0mL\niSniGIj1LEq8UyXV9J7Rq23NFjEcbd/IeRy/P/lj3BExyznelYp0Op4Bu77Esdo7aeKuDHNbeHbn\nVX25tkvHsAv1wJZlwxp7rsuGALMlK5La4Jws4p+9myELT7yjWFn4esbbcdYbL9G7YvU40eWv4ME4\nYN7BKtp8VXLDAj0IyM1Q+ykbDHwaU/5YvUSdUWxN8FSlLAT9KJPdhEHj/NckbadgNLnbdJUBP51W\nWl20pli1LN738n+D7RAP18sYTzehLXrm2YGwqO089Jkq5evD0Xt1eH66CO32zqNrj/mgw8hlNaIu\nYerKHwIDAQAB


    Friday, January 11, 2019 8:26 AM
  • Hi Jeetendra,

    For your reply, I find the problem and update the following code.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.IO;
    using System.Linq;
    using System.Security.Cryptography;
    using System.Security.Cryptography.X509Certificates;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace test1
    {
        class Program
        {
            static void Main(string[] args)
            {
                string publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAieittffvHkrzV+VsKu3FYpnRs/+Lr0mL\niSniGIj1LEq8UyXV9J7Rq23NFjEcbd/IeRy/P/lj3BExyznelYp0Op4Bu77Esdo7aeKuDHNbeHbn\nVX25tkvHsAv1wJZlwxp7rsuGALMlK5La4Jws4p+9myELT7yjWFn4esbbcdYbL9G7YvU40eWv4ME4\nYN7BKtp8VXLDAj0IyM1Q+ykbDHwaU/5YvUSdUWxN8FSlLAT9KJPdhEHj/NckbadgNLnbdJUBP51W\nWl20pli1LN738n+D7RAP18sYTzehLXrm2YGwqO089Jkq5evD0Xt1eH66CO32zqNrj/mgw8hlNaIu\nYerKHwIDAQAB";
                string m = RSAUtility.RSAEncrypt("test13", publicKey);
                Console.WriteLine(m);
                Console.ReadKey();
            }
        }
        public class RSAUtility
        {
           
            public static string  RSAEncrypt(string plainText, string key)
            {
                try
                {
                    using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                    {
                        RSAParameters RSAKeyInfo = RSA.ExportParameters(false);
                        byte []pulickey= Encoding.Default.GetBytes(key);
                        RSAKeyInfo.Modulus = pulickey;
                        RSA.ImportParameters(RSAKeyInfo);
                        byte[] encryp = RSA.Encrypt(Encoding.UTF8.GetBytes(plainText), false);
                        return Convert.ToBase64String(encryp);
                    }
        
                }
               catch (CryptographicException e)
                {
                    Console.WriteLine(e.Message);
    
                    return null;
                }
    
            }
    
        }
    
    }
    

    Test Result: 

    Hope my suggestion could be helpful.

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Friday, January 11, 2019 9:27 AM
    Moderator