none
Digital signature (SHA256 Hash with RSA algo) RRS feed

  • Question

  • Hi,

    I found this Java code and wanted to know if we can replicate this same in DotNet. 

    public class SHA256WithRSAAlgo {
        private static String consumerId = "b68d2a72....";   // Trimmed for security reason
        private static String baseUrl = "https://XXXXX/partner/item/status";
        private static String privateEncodedStr = "MIICeAIBADANBgkqhkiG9w0BAQEFAA......";       //Trimmed for security reasons
        public static void main(String[] args) {
            String httpMethod = "GET";
            String timestamp = String.valueOf(System.currentTimeMillis());
            String stringToSign = consumerId + "\n" +
                                    baseUrl + "\n" +
                                    httpMethod + "\n" +
                                    timestamp + "\n";
            String signedString = SHA256WithRSAAlgo.signData(stringToSign, privateEncodedStr);
            System.out.println("Signed String: " + signedString);
        }
        public static String signData(String stringToBeSigned, String encodedPrivateKey) {
            String signatureString = null;
            try {
                byte[] encodedKeyBytes = Base64.decodeBase64(encodedPrivateKey);
                PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(encodedKeyBytes);
                KeyFactory kf = KeyFactory.getInstance("RSA");
                PrivateKey myPrivateKey = kf.generatePrivate(privSpec);
                Signature signature = Signature.getInstance("SHA256withRSA");
                signature.initSign(myPrivateKey);
                byte[] data = stringToBeSigned.getBytes("UTF-8");
                signature.update(data);
                byte[] signedBytes = signature.sign();
                signatureString = Base64.encodeBase64String(signedBytes);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return signatureString;
        }
    }

    What I want to achieve is to Sign Data with SHA256 hash using RSA Algorithm. I already have received the Private Key.

    So have to use that Private Key to sign the data.

    Can anyone please provide me some more information about this?

    Warm Regards,

    Kamran

    Thursday, July 30, 2015 2:32 AM

Answers

  • Hi Kamran,

    >>What I want to achieve is to Sign Data with SHA256 hash using RSA Algorithm. I already have received the Private Key.

    In .Net Framework, you can consider using C# or VB language.

    RSA being a public key crypto-system has two keys, the Public key and the Private key. The Encryption is done using one and the decryption is done using the other. Normally, the encryption is done using the Public key and the decryption is done using the Private key. So the certificate with the private key is important. Microsoft's .NET framework has  support for encryption in the System.Security.Cryptography namespace. Everything you need to  perform encryption is available in that class, like RSACryptoServiceProvider does work with SHA2-based signatures.

    Here are some C# threads, you can get some hints from below. 

    How can I sign a file using RSA and SHA256 with .NET?

    signature with SHA256

    Additionally, since the code you posted is Java code, as far as I know, there is some third-party tools to helps you convert java code to C# or VB code, you could try to put "convert java to c#" in search engine, a bunch of material you'll get.

    Hope this helps.

    Best regards,

    Kristin

     


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.



    Friday, July 31, 2015 2:41 AM

All replies

  • Hi Kamran,

    >>What I want to achieve is to Sign Data with SHA256 hash using RSA Algorithm. I already have received the Private Key.

    In .Net Framework, you can consider using C# or VB language.

    RSA being a public key crypto-system has two keys, the Public key and the Private key. The Encryption is done using one and the decryption is done using the other. Normally, the encryption is done using the Public key and the decryption is done using the Private key. So the certificate with the private key is important. Microsoft's .NET framework has  support for encryption in the System.Security.Cryptography namespace. Everything you need to  perform encryption is available in that class, like RSACryptoServiceProvider does work with SHA2-based signatures.

    Here are some C# threads, you can get some hints from below. 

    How can I sign a file using RSA and SHA256 with .NET?

    signature with SHA256

    Additionally, since the code you posted is Java code, as far as I know, there is some third-party tools to helps you convert java code to C# or VB code, you could try to put "convert java to c#" in search engine, a bunch of material you'll get.

    Hope this helps.

    Best regards,

    Kristin

     


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.



    Friday, July 31, 2015 2:41 AM
  • I've found the exact same algorithm and am looking for the same solution.  Did you ever find a solution to this?
    Tuesday, November 1, 2016 4:55 PM
  • Option 1:===============================

    The algorithm above is from the Walmart Marketplace API Docs on how to sign the auth in data
    The private key is in PKCS#8 format and can be converted thanks to the generous people at
    Java Science. They provide source code that converts the PCK#8 key provided by the Walmart Marketplace portal to RSACrypoProvider Object. The code is here
    http://www.jensign.com/opensslkey/opensslkey.cs   I pulled the entire CS in and added it as a reference to my project.

    I then used the code below to sign the data
    The thing you will have to watch out for is how the url gets encoded to base64 as opposed to how java does it, so  I wrote a small java program to test it out and compare. The thing I found is for the baseURL do not use the URLEncoded version

    instead use the flat raw string (decoded) version. I was having the %2F of the "/" being  removed by the java -jar call  and leaving just "F"

    Class WalmartMrktPlcLab
    {
      const String m_strPrivKey = "MII,,,,,,,,,,," <-user your key here
      const String m_strComsumerID = ".......-....-....-....-............"; <-replace with your id
      const String m_strBaseURL = "https://developer.walmart.com/orderProxy/order-api-doc-app/rest/v3/orders/released?createdStartDate=03/01/2017&limit=10"; <-example call
      const String m_strHTTPMethod = "GET";
      const String m_strSvcName = "Walmart Marketplace";
      const String m_strChannelType = ".......-....-....-....-............"; <-replace with your Channel Type

      String GenAuth()
      {
        string l_strTimestamp = ((DateTime.UtcNow-DateTime.Parse("01/01/1970").ToUniversalTime()).Ticks/TimeSpan.TicksPerMillisecond).ToString();
        string l_strAuthData = m_strComsumerID + "\n"
                                + m_strBaseURL + "\n"
                                + m_strHTTPMethod + "\n"
                                + l_strTimestamp + "\n";
        RSACryptoServiceProvider l_oRSAIn = opensslkey.DecodePrivateKeyInfo(Convert.FromBase64String(m_strPrivKey));
        byte[] l_baAuthData = Encoding.UTF8.GetBytes(l_strAuthData);
        byte[] l_baSignature = l_oRSAIn.SignData(l_baAuthData, CryptoConfig.MapNameToOID("SHA256"));

        //Round Table
        if(l_oRSAIn.VerifyData(l_baAuthData,CryptoConfig.MapNameToOID("SHA256"),l_baSignature))
           lblAlgo.Text="Verified";
        else
           lblAlgo.Text="Failed";

        return Convert.ToBase64String(l_baSignature);
      }
    }    

    Option 2:======================================

    use the .net process to call the jar file provided by the Marketplace website to generate the base64 string for you

       void BtnProcJVMClick(object sender, EventArgs e)
        {
          using(System.Diagnostics.Process l_oProcess = new System.Diagnostics.Process())
          {
            String l_strLogFile = "testing.log";
            l_oProcess.EnableRaisingEvents = false;
            l_oProcess.StartInfo.UseShellExecute = false;
            l_oProcess.StartInfo.CreateNoWindow = true;
            l_oProcess.StartInfo.RedirectStandardOutput = true;
            l_oProcess.StartInfo.RedirectStandardError = true;
            l_oProcess.StartInfo.WorkingDirectory = "c:\\dev\\x86inc";
            l_oProcess.StartInfo.FileName="java.exe";
            l_oProcess.SynchronizingObject = this.textBox1;
            l_oProcess.StartInfo.Arguments=String.Format("-jar digitalSignatureUtil-1.0.0.jar DigitalSignatureUtil {0} {1} {2} {3} {4}"
                                                         , m_strBaseURL, m_strComsumerID, m_strPrivKey2, m_strHTTPMethod, l_strLogFile);
            l_oProcess.ErrorDataReceived += new DataReceivedEventHandler(Java_ErrorDataReceived);
            
             l_oProcess.Start();

            l_oProcess.BeginErrorReadLine();

            String l_strOutput = l_oProcess.StandardOutput.ReadToEnd();

            l_oProcess.WaitForExit(5000);
            textBox1.Text = l_oProcess.ExitCode.ToString();
            textBox2.Text = l_strOutput;
          }
        }

        private static void Java_ErrorDataReceived(object p_oSender, DataReceivedEventArgs p_oEventData)
        {
          if(!String.IsNullOrEmpty(p_oEventData.Data))
          {
               System.Windows.Forms.TextBox l_tbx1 = (System.Windows.Forms.TextBox)((System.Diagnostics.Process)p_oSender).SynchronizingObject;
            l_tbx1.Text+=l_tbx1.Text + p_oEventData.Data + '\n';
          }
        }



    • Edited by X86Inc Monday, May 1, 2017 5:45 PM fixed missing line in option 2
    • Proposed as answer by X86Inc Monday, May 1, 2017 5:45 PM
    Monday, May 1, 2017 8:54 AM
  • Stuck in the same problem, i already have the private key in PKCS8 string but not able to generate the signed data, in Java solution is there but .net couldn't find one !
    • Edited by Puru1996 Monday, March 30, 2020 8:23 AM
    Monday, March 30, 2020 8:22 AM