Nagaveni Katari

Nagaveni Katari

  • 1.3k
  • 106
  • 7.4k

generate token by passing private key and jsonstring

May 18 2023 11:43 AM

public class TokenGenerator
    {
    private static string privateKey = "65e365bd06f7f54a5282a63278bb21c2";
    public static string jsonString = "{\"UserID\":\"1\",\"UserName\":\"Ayyappa\",\"txnId\":\"123456\",\"customerMob\":\"8569896857\",\"lname\":\"lakshman\",\"name\":\"Balasubbiramani\",\"mname\":\"ram\",\"productCode\":\"DMT\",\"address\":\"Mumbai\",\"dateOfBirth\":\"05/10/1982\",\"agentId\":\"CUSTOMER123456\",\"partnerId\":\"4121\",\"kycStatus\":\"0\",\"pancardStatus\":\"0\",\"identityDocType\":\"0\",\"identityDocNo\":\"BgQkkDr14\",\"channel\":\"4\",\"isOTPValidated\":\"0\",\"hashKey\":\"9f3f9eb0451e8c2e3955551c57458072\"}";

    public static string GenerateToken()
    {
        using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
        {
            RSAParameters privateKeyParameters = new RSAParameters();
            privateKeyParameters.Modulus = HexStringToByteArray(privateKey);

            rsa.ImportParameters(privateKeyParameters);

            byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonString);

            // Compute the hash of the JSON bytes using SHA1
            SHA1Managed sha1 = new SHA1Managed();
            byte[] hash = sha1.ComputeHash(jsonBytes);

            // Sign the hash using RSA
            byte[] signature = rsa.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));

            // Convert the signature to a string representation
            string token = Convert.ToBase64String(signature);

            return token;
        }
    }

    private static byte[] HexStringToByteArray(string hexString)
    {
        int length = hexString.Length;
        byte[] bytes = new byte[length / 2];
        for (int i = 0; i < length; i += 2)
            bytes[i / 2] = Convert.ToByte(hexString.Substring(i, 2), 16);
        return bytes;
    }

this my code i am getting the Error:System.Security.Cryptography.CryptographicException: 'Bad Data.
' can you please help me


Answers (1)