Sample Code in C#.net

Generation of appKey

public static byte[] generateAppKey()
  {
   Aes KEYGEN = Aes.Create();
   byte[] secretKey = KEYGEN.Key;
   return secretKey;
 }


Asymmetric Key Encryption (RSA)

The following C#.Net code snippet can be used for encrypting the password using the public key given by the e-Invoice System. The encryption method used here is RSA.

The publicKey used here is the Encryption PublicKey Provided.

      public static string EncryptAsymmetric(string password, string Publickey)
         {
            byte[] keyBytes = Convert.FromBase64String(Publickey);
            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
            RSAParameters rsaParameters = new RSAParameters();
            rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
            rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(rsaParameters);
            byte[] plaintext = Encoding.UTF8.GetBytes(password);
            byte[] ciphertext = rsa.Encrypt(plaintext, false);
            string cipherresult = Convert.ToBase64String(ciphertext);
            return cipherresult;
         }
    

The following C#.Net code snippet can be used for encrypting the appkey using the public key given by the e-Invoice System. The encryption method used here is RSA.

The publicKey used here is the Encryption PublicKey Provided.

     public static string Encrypt(byte[]appKey, string publicKey)
         {
            byte[] keyBytes = Convert.FromBase64String(publicKey);
            AsymmetricKeyParameter asymmetricKeyParameter = PublicKeyFactory.CreateKey(keyBytes);
            RsaKeyParameters rsaKeyParameters = (RsaKeyParameters)asymmetricKeyParameter;
            RSAParameters rsaParameters = new RSAParameters();
            rsaParameters.Modulus = rsaKeyParameters.Modulus.ToByteArrayUnsigned();
            rsaParameters.Exponent = rsaKeyParameters.Exponent.ToByteArrayUnsigned();
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(rsaParameters);
            byte[] plaintext = appKey;
            byte[] ciphertext = rsa.Encrypt(plaintext, false);
            string cipherresult = Convert.ToBase64String(ciphertext);
            return cipherresult;
         }
    

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.

      public static byte[] DecryptBySymmetricKey(string encryptedSek, byte[] appkey)
          {
            //Decrypting SEK
            try
              {
                byte[] dataToDecrypt = Convert.FromBase64String(encryptedSek);
                var keyBytes = appkey;
                AesManaged tdes = new AesManaged();
                tdes.KeySize = 256;
                tdes.BlockSize = 128;
                tdes.Key = keyBytes;
                tdes.Mode = CipherMode.ECB;
                tdes.Padding = PaddingMode.PKCS7;
                ICryptoTransform decrypt__1 = tdes.CreateDecryptor();
                byte[] deCipher = decrypt__1.TransformFinalBlock(dataToDecrypt, 0, dataToDecrypt.Length);
                tdes.Clear();
                string EK_result = Convert.ToBase64String(deCipher);
                return EK_result;
             }
                catch (Exception ex)
                    {
                        throw ex;
                    }
          }
    

Symmetric Key Encryption (AES)

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)

          public static string EncryptBySymmetricKey(string jsondata, string sek)
              {
              //Encrypting SEK
              try
                 {
                    byte[] dataToEncrypt = Convert.FromBase64String(jsondata);
                    var keyBytes = Convert.FromBase64String(sek);
                    AesManaged tdes = new AesManaged();
                    tdes.KeySize = 256;
                    tdes.BlockSize = 128;
                    tdes.Key = keyBytes;
                    tdes.Mode = CipherMode.ECB;
                    tdes.Padding = PaddingMode.PKCS7;
                    pICryptoTransform encrypt__1 = tdes.CreateEncryptor();
                    byte[] deCipher = encrypt__1.TransformFinalBlock(dataToEncrypt, 0, dataToEncrypt.Length);
                    tdes.Clear();
                    string EK_result = Convert.ToBase64String(deCipher);
                    return EK_result;
                }
                    catch (Exception ex)
                       {
                         throw ex;
                       }
             }
          

Decoding the Signed eInvoice

  public static string Decode(string token)
    {
       var parts = token.Split('.');
       var header = parts[0];
       var payload = parts[1];
       var signature = parts[2];
       byte[] crypto = Base64UrlDecode(parts[2]);
       var headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
       var headerData = JObject.Parse(headerJson);
       var payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
       var payloadData = JObject.Parse(payloadJson);        
       return headerData.ToString() + payloadData.ToString();
     }

Verifying the Signed eInvoice

Please note the ‘ProdPubKey.cer’ mentioned here is the Key provided for the verification of the signed content.

 private  static bool ValidateToken(string token)
    {
      var handler = new JsonWebTokenHandler();
      string path = HttpContext.Current.Server.MapPath("~") + "\\EncDesc\\ProdPubKey.cer";
      X509Certificate2 signingPublicCert = new X509Certificate2(path);
      Microsoft.IdentityModel.Tokens.X509SecurityKey publickey = new Microsoft.IdentityModel.Tokens.X509SecurityKey(signingPublicCert);
      TokenValidationResult result = handler.ValidateToken(token,
      new TokenValidationParameters
         {
          ValidIssuer = "NIC",
          ValidateAudience = false,
          IssuerSigningKey = publickey,
          ValidateLifetime = false
         });
        bool isValid = result.IsValid;
        SecurityToken securityToken = handler.ReadToken(token);
        return isValid;
    }