{"id":1777,"date":"2023-05-24T09:29:53","date_gmt":"2023-05-24T09:29:53","guid":{"rendered":"https:\/\/whitebooks.in\/blog\/?p=1777"},"modified":"2023-05-24T09:31:49","modified_gmt":"2023-05-24T09:31:49","slug":"c-net-code-samples-for-generating-e-invoices-through-apis","status":"publish","type":"post","link":"https:\/\/whitebooks.in\/blog\/c-net-code-samples-for-generating-e-invoices-through-apis\/","title":{"rendered":"C#.net code samples for generating E-Invoices through APIs"},"content":{"rendered":"\n<h3 class=\"wp-block-heading\">Authentication sample code for Version 1.04<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\rusing Newtonsoft.Json;\r\nusing Org.BouncyCastle.Crypto;\r\nusing Org.BouncyCastle.Crypto.Parameters;\r\nusing Org.BouncyCastle.Security;\r\nusing System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing System.Linq;\r\nusing System.Net;\r\nusing System.Net.Http;\r\nusing System.Net.Http.Headers;\r\nusing System.Security.Cryptography;\r\nusing System.Text;\r\nusing System.Threading.Tasks;\r\nusing Newtonsoft.Json.Linq;\r\nnamespace EinvoiceAuth\r\n{\r\n    class Program\r\n    {\r\n        static void Main(string&#91;] args)\r\n        {\r\n            call_server_api();\r\n        }\r\n        public static void call_server_api()\r\n        {\r\n            try\r\n            {\r\n                string public_key = \"&lt;Public Key>\";\r\n                HttpClient client = new HttpClient();\r\n                string uri = \"&lt;URL>\/v1.04\/auth\";\r\n                client.DefaultRequestHeaders.Add(\"client-id\", \"&lt;Client ID>\");\r\n                client.DefaultRequestHeaders.Add(\"client-secret\", \"&lt;Client Secret>\");\r\n                string userName = \"&lt;User Id>\";\r\n                string password = \"&lt;Password>\";\r\n                client.DefaultRequestHeaders.Add(\"gstin\", \"&lt;GSTIN>\");\r\n                byte&#91;] _aeskey = generateSecureKey();\r\n                string straesKey = Convert.ToBase64String(_aeskey);\r\n                RequestPayloadN aRequestPayload = new RequestPayloadN();\r\n                Auth data = new Auth();\r\n                data.Password = password;\r\n                data.AppKey = straesKey;\r\n                data.UserName = userName;\r\n                data.ForceRefreshAccessToken = false;\r\n                string authStr = JsonConvert.SerializeObject(data);\r\n                byte&#91;] authBytes = System.Text.Encoding.UTF8.GetBytes(authStr);\r\n                aRequestPayload.Data = Encrypt(Convert.ToBase64String(authBytes), public_key);\r\n                string abc = JsonConvert.SerializeObject(aRequestPayload);\r\n                HttpResponseMessage res = client.PostAsJsonAsync(uri, aRequestPayload).Result;\r\n                if (res.IsSuccessStatusCode)\r\n                {\r\n                    Console.WriteLine(\"Call is success\");\r\n                    string verification = res.Content.ReadAsStringAsync().Result;\r\n                    Console.WriteLine($\"Response{verification}\");\r\n                    AuthResponse authResponse = res.Content.ReadAsAsync&lt;AuthResponse>().Result;\r\n                    string sek = DecryptBySymmerticKey(authResponse.Data.Sek, _aeskey);\r\n                    Console.WriteLine($\"Sek {sek}\");\r\n                }\r\n                else\r\n                {\r\n                    var stream = res.Content.ReadAsStreamAsync().Result;\r\n                    StreamReader reader = new StreamReader(stream);\r\n                    string text = reader.ReadToEnd();\r\n                    string err = res.ReasonPhrase;\r\n                    Console.WriteLine($\"error Response{text} reason{err}\");\r\n                }\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                Console.WriteLine(ex.ToString());\r\n            }\r\n        }\r\n        public static string DecryptBySymmerticKey(string encryptedText, byte&#91;] key)\r\n        {\r\n            try\r\n            {\r\n                byte&#91;] dataToDecrypt = Convert.FromBase64String(encryptedText);\r\n                var keyBytes = key;\r\n                AesManaged tdes = new AesManaged();\r\n                tdes.KeySize = 256;\r\n                tdes.BlockSize = 128;\r\n                tdes.Key = keyBytes;\r\n                tdes.Mode = CipherMode.ECB;\r\n                tdes.Padding = PaddingMode.PKCS7;\r\n                ICryptoTransform decrypt__1 = tdes.CreateDecryptor();\r\n                byte&#91;] deCipher = decrypt__1.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);\r\n                tdes.Clear();\r\n                string EK_result = Convert.ToBase64String(deCipher);\r\n                \/\/ var EK = Convert.FromBase64String(EK_result);\r\n                \/\/ return EK;\r\n                return EK_result;\r\n            }\r\n            catch (Exception ex)\r\n            {\r\n                throw ex;\r\n            }\r\n        }\r\n        public static byte&#91;] generateSecureKey()\r\n        {\r\n            Aes KEYGEN = Aes.Create();\r\n            byte&#91;] secretKey = KEYGEN.Key;\r\n            return secretKey;\r\n        }\r\n        public static string Encrypt(string data, string key)\r\n        {\r\n            byte&#91;] keyBytes =\r\n           Convert.FromBase64String(key); \/\/ your key here\r\n            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);\r\n            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;\r\n            RSAParameters rsaParameters = new RSAParameters();\r\n            rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();\r\n            rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();\r\n            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();\r\n            rsa.ImportParameters(rsaParameters);\r\n            byte&#91;] plaintext = Encoding.UTF8.GetBytes(data);\r\n            byte&#91;] ciphertext = rsa.Encrypt(plaintext, false);\r\n            string cipherresult = Convert.ToBase64String(ciphertext);\r\n            \/\/string cipherresult = Encoding.ASCII.GetString(ciphertext);\r\n            return cipherresult;\r\n        }\r\n       \r\n    }\r\n    public class Auth\r\n    {\r\n        public string Password { get; set; }\r\n        public string AppKey { get; set; }\r\n        public string UserName { get; set; }\r\n        public Boolean ForceRefreshAccessToken { get; set; }\r\n    }\r\n    public class RequestPayloadN\r\n    {\r\n        public string Data { get; set; }\r\n    }\r\n    public class AuthResponse\r\n    {\r\n        public string Status { get; set; }\r\n        public List&lt;ErrorDetail> ErrorDetails { get; set; }\r\n        public List&lt;InfoDtl> InfoDtls { get; set; }\r\n        public class ErrorDetail\r\n        {\r\n            public string ErrorCode { get; set; }\r\n            public string ErrorMessage { get; set; }\r\n        }\r\n        public class InfoDtl\r\n        {\r\n            public string InfCd { get; set; }\r\n            public List&lt;Infodata> Desc { get; set; }\r\n        }\r\n        public class Infodata\r\n        {\r\n            public string ErrorCode { get; set; }\r\n            public string ErrorMessage { get; set; }\r\n        }\r\n        public data Data { get; set; }\r\n        public class data\r\n        {\r\n            public string ClientId { get; set; }\r\n            public string UserName { get; set; }\r\n            public string AuthToken { get; set; }\r\n            public string Sek { get; set; }\r\n            public string TokenExpiry { get; set; }\r\n            public static implicit operator data(string v)\r\n            {\r\n                throw new NotImplementedException();\r\n            }\r\n        }\r\n    }\r\n}        <\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Symmetric Decryption (AES)<\/h3>\n\n\n\n<p>The following C#.Net code snippet can be used for decrypting the encrypted sek using the appkey. Here the encryptedSek is the one that is received in response to the authentication.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\r      public static byte&#91;] DecryptBySymmetricKey(string encryptedSek, byte&#91;] appkey)\r\n          {\r\n            \/\/Decrypting SEK\r\n            try\r\n              {\r\n                byte&#91;] dataToDecrypt = Convert.FromBase64String(encryptedSek);\r\n                var keyBytes = appkey;\r\n                AesManaged tdes = new AesManaged();\r\n                tdes.KeySize = 256;\r\n                tdes.BlockSize = 128;\r\n                tdes.Key = keyBytes;\r\n                tdes.Mode = CipherMode.ECB;\r\n                tdes.Padding = PaddingMode.PKCS7;\r\n                ICryptoTransform decrypt__1 = tdes.CreateDecryptor();\r\n                byte&#91;] deCipher = decrypt__1.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);\r\n                tdes.Clear();\r\n                string EK_result = Convert.ToBase64String(deCipher);\r\n                return EK_result;\r\n             }\r\n                catch (Exception ex)\r\n                    {\r\n                        throw ex;\r\n                    }\r\n          }\r\n  <\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Symmetric Key Encryption (AES)<\/h3>\n\n\n\n<p>The following C#.Net code snippet can be used for encrypting the data using the symmetric key. The decrypted sek need to be passed here.(It is got by decrypting the obtained SEK after successful authentication)<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\r\n          public static string EncryptBySymmetricKey(string jsondata, string sek)\r\n              {\r\n              \/\/Encrypting SEK\r\n              try\r\n                 {\r\n                    byte&#91;] dataToEncrypt = Convert.FromBase64String(jsondata);\r\n                    var keyBytes = Convert.FromBase64String(sek);\r\n                    AesManaged tdes = new AesManaged();\r\n                    tdes.KeySize = 256;\r\n                    tdes.BlockSize = 128;\r\n                    tdes.Key = keyBytes;\r\n                    tdes.Mode = CipherMode.ECB;\r\n                    tdes.Padding = PaddingMode.PKCS7;\r\n                    pICryptoTransform encrypt__1 = tdes.CreateEncryptor();\r\n                    byte&#91;] deCipher = encrypt__1.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);\r\n                    tdes.Clear();\r\n                    string EK_result = Convert.ToBase64String(deCipher);\r\n                    return EK_result;\r\n                }\r\n                    catch (Exception ex)\r\n                       {\r\n                         throw ex;\r\n                       }\r\n             }\r\n         <\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Decoding the Signed eInvoice<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>\r  public static string Decode(string token)\r\n    {\r\n       var parts = token.Split('.');\r\n       var header = parts&#91;0];\r\n       var payload = parts&#91;1];\r\n       var signature = parts&#91;2];\r\n       byte&#91;] crypto = Base64UrlDecode(parts&#91;2]);\r\n       var headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));\r\n       var headerData = JObject.Parse(headerJson);\r\n       var payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));\r\n       var payloadData = JObject.Parse(payloadJson);        \r\n       return headerData.ToString() + payloadData.ToString();\r\n     }<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Verifying the Signed eInvoice<\/h3>\n\n\n\n<p>Please note the \u2018ProdPubKey.cer\u2019 mentioned here is the Key provided for the verification of the signed content.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\r private  static bool ValidateToken(string token)\r\n    {\r\n      var handler = new JsonWebTokenHandler();\r\n      string path = HttpContext.Current.Server.MapPath(\"~\") + \"\\\\EncDesc\\\\ProdPubKey.cer\";\r\n      X509Certificate2 signingPublicCert = new X509Certificate2(path);\r\n      Microsoft.IdentityModel.Tokens.X509SecurityKey publickey = new Microsoft.IdentityModel.Tokens.X509SecurityKey(signingPublicCert);\r\n      TokenValidationResult result = handler.ValidateToken(token,\r\n      new TokenValidationParameters\r\n         {\r\n          ValidIssuer = \"NIC\",\r\n          ValidateAudience = false,\r\n          IssuerSigningKey = publickey,\r\n          ValidateLifetime = false\r\n         });\r\n        bool isValid = result.IsValid;\r\n        SecurityToken securityToken = handler.ReadToken(token);\r\n        return isValid;\r\n    }<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Authentication sample code for Version 1.04 Symmetric Decryption (AES) The following C#.Net code snippet can be used for decrypting the encrypted sek using the appkey. Here the encryptedSek is the one that is received in response to the authentication. Symmetric Key Encryption (AES) The following C#.Net code snippet can be used for encrypting the data&hellip;&nbsp;<a href=\"https:\/\/whitebooks.in\/blog\/c-net-code-samples-for-generating-e-invoices-through-apis\/\" class=\"\" rel=\"bookmark\">Read More &raquo;<span class=\"screen-reader-text\">C#.net code samples for generating E-Invoices through APIs<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"neve_meta_sidebar":"","neve_meta_container":"","neve_meta_enable_content_width":"","neve_meta_content_width":0,"neve_meta_title_alignment":"","neve_meta_author_avatar":"","neve_post_elements_order":"","neve_meta_disable_header":"","neve_meta_disable_footer":"","neve_meta_disable_title":"","neve_meta_reading_time":"","_themeisle_gutenberg_block_has_review":false,"footnotes":""},"categories":[95],"tags":[133,134],"class_list":["post-1777","post","type-post","status-publish","format-standard","hentry","category-e-invoicing","tag-e-invoice-api","tag-e-invoicing-api"],"_links":{"self":[{"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/posts\/1777","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/comments?post=1777"}],"version-history":[{"count":1,"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/posts\/1777\/revisions"}],"predecessor-version":[{"id":1778,"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/posts\/1777\/revisions\/1778"}],"wp:attachment":[{"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/media?parent=1777"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/categories?post=1777"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/whitebooks.in\/blog\/wp-json\/wp\/v2\/tags?post=1777"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}