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.

 public static string EncryptAsymmetric(string data, string key)
  {
   byte[] keyBytes = Convert.FromBase64String(key);
   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(data);
   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.

 public static string Encrypt(byte[] data, string key)
  {
   byte[] keyBytes = Convert.FromBase64String(key);
   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 = data;
   byte[] ciphertext = rsa.Encrypt(plaintext, false);
   string cipherresult = Convert.ToBase64String(ciphertext);
   return cipherresult;
}

Symmetric Key Encryption (AES)

The following C#.Net code snippet can be used for encrypting the data using the symmetric key.

 public static string EncryptBySymmetricKey(string text, string sek)
    {
    //Encrypting SEK
    try
    {
      byte[] dataToEncrypt = Convert.FromBase64String(text);
      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;
   }
 }

Symmetric Decryption (AES)

The following C#.Net code snippet can be used for decrypting the encrypted sek using the appkey.

  public static byte[] DecryptBySymmetricKey(string encryptedText, byte[] key)
  {

   //Decrypting SEK
   try
   {

     byte[] dataToDecrypt = Convert.FromBase64String(encryptedText);
     var keyBytes = key;
     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;
   }
 }

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

 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;
    }