ASP.NET Core 7

Encrypt server (asp.net core7) api result to client (flutter)

o encrypt the server API result on the ASP.NET Core side and decrypt it on the Flutter side, you can use a symmetric encryption algorithm, such as AES. Here’s a high-level overview of the process:

On the ASP.NET Core side, you’ll need to generate an AES key and initialize a cipher in encryption mode. Use this cipher to encrypt the API result before sending it to the client.

using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;

namespace EncryptedApiExample.Controllers
{
public class ApiController : Controller
{
[HttpGet]
public IActionResult GetData()
{
// The API result you want to send to the client
string apiResult = “secret data”;

// Generate a random AES key
byte[] key = GenerateAesKey();

// Initialize a cipher in encryption mode
Aes aes = Aes.Create();
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
ICryptoTransform encryptor = aes.CreateEncryptor();

// Encrypt the API result
byte[] encryptedResult = encryptor.TransformFinalBlock(Encoding.UTF8.GetBytes(apiResult), 0, apiResult.Length);

// Return the encrypted result and the AES key to the client
return Ok(new { encryptedResult, key });
}

private byte[] GenerateAesKey()
{
// Your implementation for generating a random AES key goes here
// For this example, let’s generate a random key of 128 bits (16 bytes)
byte[] key = new byte[16];
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(key);
}
return key;
}
}
}

On the Flutter side, you’ll need to receive the encrypted result and the AES key, then initialize a cipher in decryption mode to decrypt the result.

import ‘dart:convert’;
import ‘dart:typed_data’;

import ‘package:flutter/widgets.dart’;
import ‘package:pointycastle/pointycastle.dart’;

class DecryptedData with ChangeNotifier {
String _apiResult;

String get apiResult => _apiResult;

set apiResult(String apiResult) {
_apiResult = apiResult;
notifyListeners();
}
}

class DecryptApiResult with ChangeNotifier {
Future decryptResult(Uint8List encryptedResult, Uint8List key) async {
// Initialize a cipher in decryption mode
var aesParams = new KeyParameter(key);
var cipher = new StreamCipher(“AES/ECB/PKCS7”);
cipher.init(false, aesParams);

// Decrypt the API result
Uint8List decryptedResult = cipher.process(encryptedResult);

// Convert the decrypted result to a string
String apiResult = utf8.decode(decryptedResult);

// Update the decrypted data

Sending the encryption key over the network like this is not secure, as it can be intercepted by attackers. To securely encrypt the data, you should use a combination of asymmetric encryption and symmetric encryption.

Here’s a high-level overview of how it could be done:

On the server side, generate a public-private key pair using a secure asymmetric encryption algorithm such as RSA. Share the public key with the client.

On the client side, generate a random symmetric encryption key, such as an AES key, and use the public key to encrypt it.

On the server side, use the private key to decrypt the symmetric encryption key.

Use the symmetric encryption key to encrypt the API result on the server side and send it to the client.

On the client side, use the symmetric encryption key to decrypt the API result.

By using a combination of asymmetric and symmetric encryption, you can ensure that the encryption key is securely transmitted from the client to the server and that the data is encrypted and decrypted using a secure key. This makes it much more difficult for attackers to intercept the key and access the encrypted data.

For More Secureway

using System;
using System.Security.Cryptography;

namespace EncryptionExample
{
public static class RSAKeyGenerator
{
public static void GenerateKeys(out string publicKey, out string privateKey)
{
using (var rsa = RSA.Create())
{
publicKey = Convert.ToBase64String(rsa.ExportSubjectPublicKeyInfo());
privateKey = Convert.ToBase64String(rsa.ExportPkcs8PrivateKey());
}
}
}
}

using System;
using System.IO;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;

namespace EncryptionExample.Controllers
{
[Route(“api/[controller]”)]
[ApiController]
public class DataController : ControllerBase
{
private static readonly byte[] _symmetricKey = new byte[32];
private static readonly byte[] _iv = new byte[16];

[HttpPost]
public IActionResult GetEncryptedData([FromBody] byte[] encryptedSymmetricKey)
{
using (var rsa = RSA.Create())
{
var privateKey = Convert.FromBase64String(““);
rsa.ImportPkcs8PrivateKey(privateKey, out _);

encryptedSymmetricKey = rsa.Decrypt(encryptedSymmetricKey, RSAEncryptionPadding.OaepSHA256);
}

using (var aes = Aes.Create())
{
aes.Key = encryptedSymmetricKey;
aes.IV = _iv;

using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
using (var streamWriter = new StreamWriter(cryptoStream))
{
streamWriter.Write(““);
}

return Ok(memoryStream.ToArray());
}
}
}
}
}

In Flutter

import ‘dart:convert’;
import ‘dart:io’;

import ‘package:flutter/material.dart’;
import ‘package:pointycastle/asymmetric/api.dart’;
import ‘package:pointycastle/asymmetric/rsa.dart’;
import ‘package:pointycastle/block/aes_fast.dart’;
import ‘package:pointycastle/key_generators/api.dart’;
import ‘package:pointycastle/random/fortuna_random.dart’;
import ‘package:http/http.dart’ as http;

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: RaisedButton(
onPressed: () async {
// Generate a random symmetric encryption key
var keyGenerator = KeyGenerator(“AES”);
keyGenerator.init(KeyParameter(“Fortuna”));
var key = keyGenerator.generateKey();

// Encrypt the symmetric encryption key using the public key
var rsa = RSAEngine();
rsa.init(true, PublicKeyParameter(PublicKey(““)));
var encryptedSymmetricKey = rsa.process(key.keyData);

// Send the encrypted symmetric encryption key to the server
var response = await http.post(““, body: encryptedSymmetricKey);

// Decrypt the API result
var aes = AESFastEngine();
aes.init(false, KeyParameter(key.keyData));
var decryptedData = aes.process(response.bodyBytes);

// Print the decrypted data
print(utf8.decode(decryptedData));
},
child: Text(“Get Encrypted Data”),
),
),
),
);
}
}

If Client is JAVA

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class Main {
public static void main(String[] args) throws Exception {
// Generate a random symmetric encryption key
KeyGenerator keyGenerator = KeyGenerator.getInstance(“AES”);
SecretKey secretKey = keyGenerator.generateKey();

// Encrypt the symmetric encryption key using the public key
byte[] publicKeyBytes = Base64.decodeBase64(““);
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(“RSA”);
PublicKey publicKey = keyFactory.generatePublic(keySpec);
Cipher cipher = Cipher.getInstance(“RSA/ECB/OAEPWithSHA-1AndMGF1Padding”);
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
byte[] encryptedSymmetricKey = cipher.doFinal(secretKey.getEncoded());

// Send the encrypted symmetric encryption key to the server
// …

// Decrypt the API result
cipher = Cipher.getInstance(“AES”);
SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), “AES”);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decryptedData = cipher.doFinal();

// Print the decrypted data
System.out.println(new String(decryptedData));
}
}

VB.NET

Imports System.Security.Cryptography
Imports System.Text

Module Main
Sub Main()
Dim publicKey As String = “
Dim encryptedSymmetricKey As Byte() = EncryptSymmetricKey(publicKey)
Dim apiResult As Byte() =
Dim decryptedData As Byte() = DecryptApiResult(encryptedSymmetricKey, apiResult)
Console.WriteLine(Encoding.UTF8.GetString(decryptedData))
End Sub

Private Function EncryptSymmetricKey(publicKey As String) As Byte()
Dim symmetricKey As New RijndaelManaged
symmetricKey.KeySize = 256
symmetricKey.GenerateKey()

Dim publicKeyBytes As Byte() = Convert.FromBase64String(publicKey)
Dim publicKeyObject As New RSACryptoServiceProvider
publicKeyObject.ImportCspBlob(publicKeyBytes)

Return publicKeyObject.Encrypt(symmetricKey.Key, False)
End Function

Private Function DecryptApiResult(encryptedSymmetricKey As Byte(), apiResult As Byte()) As Byte()
Dim symmetricKey As New RijndaelManaged
symmetricKey.Key = encryptedSymmetricKey

Dim decryptor As ICryptoTransform = symmetricKey.CreateDecryptor(symmetricKey.Key, symmetricKey.IV)
Return decryptor.TransformFinalBlock(apiResult, 0, apiResult.Length)
End Function
End Module

Create an encrypted download link for a file in ASP.NET Core:

In your controller, you can generate a unique, encrypted identifier for the file:

using System;
using System.IO;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Mvc;

namespace DownloadFileExample.Controllers
{
public class DownloadController : Controller
{
[HttpGet]
public IActionResult Download(string id)
{
// Decrypt the identifier to get the file path
string filePath = DecryptFileIdentifier(id);

// Check if the file exists
if (!System.IO.File.Exists(filePath))
{
return NotFound();
}

// Return the file as a FileResult
return File(System.IO.File.OpenRead(filePath), “application/pdf”, Path.GetFileName(filePath));
}

private string DecryptFileIdentifier(string encryptedIdentifier)
{
// Your implementation for decrypting the encrypted identifier goes here

// For this example, let’s assume the encrypted identifier is just a base64-encoded string of the file path
return System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(encryptedIdentifier));
}
}
}

To create an encrypted download link, you could generate an encrypted identifier for the file and include it in the link:

Download

@functions {
private string EncryptFileIdentifier(string filePath)
{
// Your implementation for encrypting the file path goes here

// For this example, let’s assume the encrypted identifier is just a base64-encoded string of the file path
return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(filePath));
}
}

This is just one way to create an encrypted download link for a file in ASP.NET Core. You can use other encryption techniques to encrypt the identifier, such as AES encryption, if needed. The specific encryption technique you choose will depend on the level of security you require for your application.

The client/user will not know the actual web path or file name as the information is encrypted and can only be decrypted by the server. By encoding the file path in the download link, you are effectively obscuring the actual file location from the client/user. This can help to prevent unauthorized access to the file and protect sensitive information.

In the example I provided earlier, the file path is encrypted using a base64 encoding and included in the download link. When the user clicks the link, the encrypted identifier is passed to the Download action in the controller. The controller then uses the DecryptFileIdentifier method to decrypt the identifier and retrieve the actual file path. Finally, the file is returned to the client/user as a FileResult.

ASP.Net 7 : Using ADO Helper Class in Minimal API/Controller

public class MyController : Controller
{
private readonly ADONetHelper _ado;

public MyController(ADONetHelper ado)
{
_ado = ado;
}

[HttpGet(“/a”)]
public async Task GetData()
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter(“MobileNo”, “1234”),
new SqlParameter(“FullNo”, “1234”),
new SqlParameter(“TZDiff”, “0”)
};
var jsonData = await _ado.GetDT_SP_Async2(“getHukamnama”, parameters);
return Ok(jsonData);
}
}

app.MapGet(“/a”, async (ADONetHelper ado) =>
{

SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter(“MobileNo”, “1234”),
new SqlParameter(“FullNo”, “1234”),
new SqlParameter(“TZDiff”, “0”)
};
var jsonData = await ado.GetDT_SP_Async2(“getHukamnama”, parameters);
return jsonData;
});

ADO.NET Helper Class

using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System.Data;

namespace EkHukam_Gurudwara.Data
{

public class ADONetHelper
{
private readonly IConfiguration _config;

public ADONetHelper(IConfiguration config)
{
_config = config;
}

public string GetDefaultConnection()
{
return _config.GetConnectionString(“DefaultConnection”);
}
public async Task GetConnStr()
{
return await Task.FromResult(_config.GetConnectionString(“DefaultConnection”));
}

public async Task GetDT_SP_Async(string spName, SqlParameter[] parameters)
{
string connString = GetDefaultConnection();
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(spName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(parameters);
await conn.OpenAsync();
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
}
}
}

public async Task GetDT_SP_Async2(string spName, SqlParameter[] parameters)
{
string connString = GetDefaultConnection();
string json = “”;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(spName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;

if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}

await conn.OpenAsync();
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
DataTable dt = new DataTable();
dt.Load(reader);
json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}
}
}
}

public async Task GetTest()
{
return await Task.FromResult(“EkOnkar”);
}

public DataTable getDataTable(string ConnStr, string sql)
{
using (SqlConnection connection = new SqlConnection(ConnStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
}

public async Task getDataTableAsync(string ConnStr, string sql)
{
using (SqlConnection connection = new SqlConnection(ConnStr))
{
await connection.OpenAsync();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = await command.ExecuteReaderAsync();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
return dataTable;
}
}

}

}
}

ASP.Net Core7 : Set Global Static Variable For Application Life

public class UserService
{
public int UserId { get; set; }
}

builder.Services.AddSingleton();

public IActionResult Login(string username, string password)
{
// Authenticate the user and get their ID
int userId = …

// Set the UserId in the UserService class
var userService = HttpContext.RequestServices.GetService();
userService.UserId = userId;

return RedirectToAction(“Index”, “Home”);
}

In Controller

public IActionResult Index()
{
var userService = HttpContext.RequestServices.GetService();
var userId = userService?.UserId ?? 0;
ViewData[“userId”] = userId;
return View();
}

public async Task Logout()
{
await HttpContext.SignOutAsync();
var userService = HttpContext.RequestServices.GetService();
if (userService != null)
{
userService.UserId = 0;
}
return RedirectToAction(“Index”, “Hukam”);
}

In View
@using EkHukam_Gurudwara.Data

@{
ViewData[“Title”] = “Dashboard”;

var userService = (UserService)ViewContext.HttpContext.RequestServices.GetService(typeof(UserService));

var @UID = (userService?.UserId ?? 0);
}

ASP.Net Core7 , How To Check Run Time Environment (Development/Production) In Controller and view both

In ASP.NET Core, you can check the runtime environment by using the IHostEnvironment interface, which is available in the controller and view.

To check the runtime environment in a controller, you can inject the IHostEnvironment interface into the constructor of the controller and then use the EnvironmentName property to determine the environment. Here is an example:

public class HomeController : Controller
{
private readonly IHostEnvironment _hostEnvironment;

public HomeController(IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}

public IActionResult Index()
{
if (_hostEnvironment.IsDevelopment())
{
// Development environment-specific code
}
else if (_hostEnvironment.IsProduction())
{
// Production environment-specific code
}

return View();
}
}

In View (Razor Pages)

@using Microsoft.AspNetCore.Hosting
@inject IHostEnvironment HostEnvironment

Environment: @HostEnvironment.EnvironmentName

When Core-7 MVC Then

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment hostingEnv
string EnvName = @hostingEnv.EnvironmentName;

How To Use Remote Procedure Call (RPC) in C#:

Server Codes

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace RPCServer
{
public class MathService : MarshalByRefObject
{

public int Add(int a, int b)
{
Console.WriteLine(“Received Add request”);
return a + b;
}

public int Subtract(int a, int b)
{
Console.WriteLine(“Received Subtract request”);
return a – b;
}
}

class Program
{
static void Main(string[] args)
{
TcpChannel channel = new TcpChannel(8080);
ChannelServices.RegisterChannel(channel, false);
RemotingConfiguration.RegisterWellKnownServiceType(
typeof(MathService),
“MathService”,
WellKnownObjectMode.SingleCall
);
Console.WriteLine(“Press enter to exit”);
Console.ReadLine();
}
}
}

Client Code

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

namespace RPCCLient
{
class Program
{
static void Main(string[] args)
{
TcpChannel channel = new TcpChannel();
ChannelServices.RegisterChannel(channel, false);

MathService service = (MathService)Activator.GetObject(
typeof(MathService),
“tcp://localhost:8080/MathService”
);

Console.WriteLine(“5 + 3 = ” + service.Add(5, 3));
Console.WriteLine(“5 – 3 = ” + service.Subtract(5, 3));

Console.WriteLine(“Press enter to exit”);
Console.ReadLine();
}
}
}

This example creates a simple math service that can perform addition and subtraction operations, and makes it available over the network using the TCP protocol. The MathService class is decorated with the MarshalByRefObject attribute, which makes it possible to call its methods from a remote client.

The RPCServer project contains the code for the server, which registers the MathService class with the .NET remoting framework and makes it available over the network. The RPCCLient project contains the code for the client, which uses the .NET remoting framework to call methods on the remote MathService instance.

Scroll to Top